body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Can anyone point me in the direction of a C# or pseudocode implementation of A* optimised for relatively sparsely connected graphs (average <code>&lt; 3</code> edges per node)?</p> <p>The implementation below that I have currently runs in 100-200ms for a graph of ~3500 nodes. I need this to be as low as absolutely possible. According to the Visual Studios CPU profiling, the bit taking the longest is searching for the lowest cost node.</p> <p><strong>Current Implementation</strong></p> <pre><code>public List&lt;NodeRow&gt; BuildAStar(string start, string end) { ILookup&lt;string, DijkstraNodeData&gt; nodes = AllNodes.ToLookup(n =&gt; n.Key, n =&gt; new DijkstraNodeData(n.FirstOrDefault())); if (start == end) { return new List&lt;NodeRow&gt;(); } var startNode = nodes[start].FirstOrDefault(); var endNode = nodes[end].FirstOrDefault(); var endCorridor = FindNextCorridorNode(endNode.Node); startNode.Closed = false; startNode.Cost = 0; while (!endNode.Closed) { // Find Lowest Cost. float smallest = float.PositiveInfinity; string smallestId = nodes.FirstOrDefault().Key; foreach (var node in nodes) { if (!node.First().Closed) { if (node.First().Cost &lt; smallest) { smallest = node.First().Cost; smallestId = node.Key; } } } if(smallest == float.PositiveInfinity) { return new List&lt;NodeRow&gt;(); } // Close this location. nodes[smallestId].First().Closed = true; // Calculate new costs. var currentNode = nodes[smallestId].First(); foreach (var node in currentNode.Node.Edges) { float currentCost = currentNode.Cost + node.Weight; DijkstraNodeData currentConnection; if (node.NodeId1 != currentNode.Node.NodeId) { currentConnection = nodes[node.NodeId1].First(); } else { currentConnection = nodes[node.NodeId2].First(); } double heuristicCost; if (currentConnection.Node.Type.ToLower() == "c") { heuristicCost = SharedFunctions.GetDistanceFromLatLonInMeters((double)currentConnection.Node.Latitude, (double)currentConnection.Node.Longitude, (double)endCorridor.Latitude, (double)endCorridor.Longitude); } else { heuristicCost = 10000; } if (currentCost &lt; currentConnection.Cost + heuristicCost) { currentConnection.Cost = currentCost + (float)heuristicCost; currentConnection.Link = smallestId; } } } List&lt;NodeRow&gt; pathStartToEnd = new List&lt;NodeRow&gt;(); bool done = false; string nextClosed = end; startNode.InPath = true; while (!done) { if (nextClosed.Length &gt; 0) { var thisNode = nodes[nextClosed].First(); thisNode.InPath = true; pathStartToEnd.Add(thisNode.Node); nextClosed = thisNode.Link; if (nextClosed == start) { done = true; } } } pathStartToEnd.Add(startNode.Node); pathStartToEnd.Reverse(); return pathStartToEnd; } private NodeRow FindNextCorridorNode(NodeRow node) { if (node.Type.ToLower() == "c") { return node; } foreach (NodeEdgeRow edge in node.Edges) { if (edge.Node2.Type.ToLower() == "c") { return edge.Node2; } } foreach (NodeEdgeRow edge in node.Edges) { FindNextCorridorNode(edge.Node2); } return null; } public class DijkstraNodeData { public NodeRow Node; public bool Closed; public float Cost = float.PositiveInfinity; public string Link = ""; public bool InPath = false; public DijkstraNodeData(NodeRow node) { Node = node; } } </code></pre>
[]
[ { "body": "<h2>Performance</h2>\n\n<p>I won't say much about the algorithm, but the profiler has pointed you in the right direction: what you need is a <a href=\"https://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow noreferrer\">Priority Queue</a>.</p>\n\n<p>A Priority Queue will enable you to keep trac...
{ "AcceptedAnswerId": "203062", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T14:41:04.717", "Id": "203027", "Score": "5", "Tags": [ "c#", "graph", "pathfinding", "a-star" ], "Title": "Latitude/Longitude graph optimised A* Algorithm" }
203027
<p>When you're working with trees one of the most useful methods to implement is a clear way to print them, the following is my solution to print a tree in Java: </p> <pre><code>class BlackRedBST{ public static final NodeRB NILL = null; public static final boolean RED = true; public static final boolean BLACK = false; NodeRB root; public BlackRedBST () { root = NILL; } public void printTree(NodeRB tree, String indent, boolean print_leaf) { if(tree == NILL) { System.out.print((print_leaf?indent+" |-+*\n":"")); } else { indent += " "; if(tree.p == NILL || tree.p == null) { printTree(tree.right, indent + " ", print_leaf); System.out.print(indent + "+" + tree.value + "\n"); printTree(tree.left, indent + " ", print_leaf); }else if(tree.p.right==tree) { printTree(tree.right, indent + " ", print_leaf); System.out.print(indent + "|+" + tree.value + "\n"); printTree(tree.left, indent + "|", print_leaf); } else { printTree(tree.right, indent + "|", print_leaf); System.out.print(indent + "|+" + tree.value + "\n"); printTree(tree.left, indent + " ", print_leaf); } } } } </code></pre> <p>To be clear in the following the NodeRB class:</p> <pre><code>class NodeRB{ int value; NodeRB p; NodeRB left; NodeRB right; boolean color; int level; public NodeRB(int v) { value = v; color = BlackRedBST.RED; left = BlackRedBST.NILL; right = BlackRedBST.NILL; level = 1; } } </code></pre> <p>To complete the code, here is a class with main to test my code:</p> <pre><code>public class PreattyPrintTree { public static void main(String[] args) { BlackRedBST bst = new BlackRedBST(); // this is a sample, but a method to add the nodes should be write bst.root = new NodeRB(1); bst.root.left = new NodeRB(2); bst.root.left.level = 2; bst.root.left.p=bst.root; bst.root.right = new NodeRB(3); bst.root.right.p = bst.root; bst.root.right.level = 2; bst.printTree(bst.root, "\t", true); } } </code></pre> <p>An output sample, with three nodes and print of leaf enabled:</p> <pre><code> |-+* |+3 | |-+* +1 | |-+* |+2 |-+* </code></pre> <p>How can the printTree method be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T23:07:44.667", "Id": "391531", "Score": "7", "body": "Welcome to Code Review! Does this compile? What's `NILL`? Please always make sure that any code is working *as far as you know* before posting it here, otherwise it's considered ...
[ { "body": "<p>A view more suggestions with explanation to the current source code (first <code>BlackRedBST</code>).</p>\n\n<p>I deleted <code>public static final NodeRB NILL = null;</code> because <code>null</code> can be used instead of <code>NILL</code> for less code.</p>\n\n<p>I also deleted <code>public sta...
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T15:34:08.337", "Id": "203031", "Score": "8", "Tags": [ "java", "tree", "formatting", "ascii-art" ], "Title": "Pretty print a tree" }
203031
<p>I am computing a random weighted classifier based on the rates at which 3 labels appear in a "train" set. I want to use this RWC as a baseline for other classifiers. I'm doing this over 1000 iterations and then computing the mean of F1, Precision and Recall of each class besides the overall kappa.</p> <p>Can this code run faster/look nicer? Minimum example here:</p> <pre><code>library(caret) random_weighted_classifier &lt;- function(weightA, weightB, weightC){ random_number = sample(1:100,1) / 100 if(random_number &lt;= weightA){ return("better") }else if (random_number &gt; weightA &amp;&amp; random_number &lt;= (weightA + weightB)){ return("worse") }else if(random_number &gt; (weightA + weightB) &amp;&amp; random_number &lt;= (weightA + weightB + weightC)){ return("no change") } } test &lt;- function(){ betters = rep(x = "better", 100) worses = rep(x = "worse", 50) no_changes = rep(x = "no_change", 10) reference = sample(c(betters, worses, no_changes)) better = sum(reference == "better") worse = sum(reference == "worse") no_change = sum(reference == "no_change") total = length(reference) # rwc = random weighted classifer prediction_rwc = vector("character", total) iterations = 1000 f1_rwc = matrix(0., iterations, 3) pres_rwc = matrix(0.,iterations, 3) rec_rwc = matrix(0., iterations, 3) kappa_rwc = vector("double", iterations) for(i in seq(1:iterations)){ for(j in seq(1:total)){ prediction_rwc[[j]] = random_weighted_classifier(better/total, worse/total, no_change/total) } cm = (confusionMatrix(data = factor(prediction_rwc, levels = c("better","worse", "no_change")), reference = factor(reference, levels = c("better","worse", "no_change")), positive = c("better", "worse"), mode = "everything")) f1_rwc[i,1:3] &lt;- cm$byClass[,"F1"] pres_rwc[i,1:3] = cm$byClass[,"Precision"] rec_rwc[i,1:3] = cm$byClass[,"Recall"] kappa_rwc[[i]] = round(cm$overall["Kappa"],2) } print(list("f1" = c(mean(f1_rwc[,1], na.rm = T),mean(f1_rwc[,2], na.rm = T),mean(f1_rwc[,3], na.rm = T)), "precision" = c(mean(pres_rwc[,1], na.rm = T),mean(pres_rwc[,2], na.rm = T),mean(pres_rwc[,3], na.rm = T)), "recall" = c(mean(rec_rwc[,1], na.rm = T),mean(rec_rwc[,2], na.rm = T),mean(rec_rwc[,3], na.rm = T)), "kappa" = mean(kappa_rwc, na.rm = T))) } test() </code></pre>
[]
[ { "body": "<p>Some improvements:</p>\n\n<pre><code>random_weighted_classifier2 &lt;- function(n = 1, weightA, weightB, weightC){\n x &lt;- sample(1:100, n, replace = T) / 100\n i1 &lt;- x &lt;= weightA\n i2 &lt;- x &gt; weightA &amp; x &lt;= (weightA + weightB)\n rez &lt;- rep('no_change', n)\n rez[i2] &lt...
{ "AcceptedAnswerId": "203079", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T16:43:25.490", "Id": "203033", "Score": "7", "Tags": [ "r", "machine-learning" ], "Title": "Random Weighted Classifier in R" }
203033
<pre><code>#!/bin/bash #extractApacheResolutionName GrepAndFilter="ServerName|ServerAlias" RemoveBadMatch="s/^\s*($GrepAndFilter)\s+//gI" RemoveTrailingWhitespaces="s/\s*$//" RemoveComas="s/,//g" ReplaceSpacesWithNewLines="s/ +/\s/g" grep --line-buffered -Ei "$GrepAndFilter" /dev/stdin \ | sed -E "$RemoveBadMatch; $RemoveTrailingWhitespaces; $RemoveComas; $ReplaceSpacesWithNewLines" </code></pre> <p>The script is to be used mainly to gather all the URLs of a remote Httpd Configuration, and output them one URL per line, such as </p> <pre><code>ssh hostname "cat /etc/httpd/conf.d/*.conf" | extractApacheResolutionName </code></pre> <p>Nb : the actual script contains a sort </p> <pre><code>... | rev | sort -u | rev </code></pre> <p>... but that's <a href="https://stackoverflow.com/questions/52153947/how-can-i-sort-urls-in-bash-shell-such-as-hostnames-are-evaluated-before-subdoma">another question I asked on StackOverflow</a>, because I would like to extract it to another piece of software.</p> <p>What can I do to improve my script ?</p> <ul> <li><p>from a readability point of view ?</p></li> <li><p>from a performance point of view ?</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-18T14:51:53.007", "Id": "397004", "Score": "0", "body": "Do you have sample input and expected output? I've prepared an alternative, but have nothing to test it with." } ]
[ { "body": "<p>What is \"bad match\" in here?</p>\n\n<blockquote>\n<pre><code>RemoveBadMatch=\"s/^\\s*($GrepAndFilter)\\s+//gI\"\n</code></pre>\n</blockquote>\n\n<p>My understanding is that this pattern is used to remove the <code>$GrepAndFilter</code> prefix from lines, with any surrounding whitespace. I don't ...
{ "AcceptedAnswerId": "205825", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T17:30:48.803", "Id": "203038", "Score": "3", "Tags": [ "bash", "sed" ], "Title": "Filter some Apache Conf to extract all ServerName and ServerAlias, then output them one per line" }
203038
<p>The following code implements the logic for moving tiles in the game <a href="http://gabrielecirulli.github.io/2048/" rel="noreferrer">2048</a>. The "move"(GameBoard::moveRight(), GameBoard::moveUp(), etc.) methods appear to be duplicating implementation. Any ideas for removing the duplication from the "move" methods? I would prefer that the time complexity for each "move" method be equivalent. I think an implementation that rotates the board to promote reusable movements would result in nonequivalent time complexities. </p> <pre><code>#include "GameBoard.h" GameBoard::GameBoard(std::vector&lt;std::vector&lt;double&gt;&gt; _board) : board(std::move(_board)), N(board.size()) { if (N == 0) throw std::runtime_error("Empty board."); for (const auto &amp;row : board) if (row.size() != N) throw std::runtime_error("Invalid board dimensions."); } const std::vector&lt;std::vector&lt;double&gt;&gt; &amp;GameBoard::getBoard() { return board; } void GameBoard::moveRight() { for (size_t row = 0; row &lt; N; ++row) { std::vector&lt;bool&gt; hasBeenCombined(N, false); for (size_t adjacentCol = N - 1; adjacentCol &gt; 0; --adjacentCol) { const auto col = adjacentCol - 1; const auto value = board[row][col]; const auto nextNonzeroOrLastColumn = getNextNonzeroOrLastColumn(row, col); if (board[row][nextNonzeroOrLastColumn] == 0) board[row].back() = value; else if ( board[row][nextNonzeroOrLastColumn] == value &amp;&amp; !hasBeenCombined[nextNonzeroOrLastColumn]) { board[row][nextNonzeroOrLastColumn] += value; hasBeenCombined[nextNonzeroOrLastColumn] = true; } else if (nextNonzeroOrLastColumn != adjacentCol) board[row][nextNonzeroOrLastColumn - 1] = value; else continue; board[row][col] = 0; } } } void GameBoard::moveLeft() { for (size_t row = 0; row &lt; N; ++row) { std::vector&lt;bool&gt; hasBeenCombined(N, false); for (size_t adjacentCol = 0; adjacentCol &lt; N - 1; ++adjacentCol) { const auto col = adjacentCol + 1; const auto value = board[row][col]; const auto previousNonzeroOrFirstColumn = getPreviousNonzeroOrFirstColumn(row, col); if (board[row][previousNonzeroOrFirstColumn] == 0) board[row].front() = value; else if ( board[row][previousNonzeroOrFirstColumn] == value &amp;&amp; !hasBeenCombined[previousNonzeroOrFirstColumn]) { board[row][previousNonzeroOrFirstColumn] += value; hasBeenCombined[previousNonzeroOrFirstColumn] = true; } else if (previousNonzeroOrFirstColumn != adjacentCol) board[row][previousNonzeroOrFirstColumn + 1] = value; else continue; board[row][col] = 0; } } } void GameBoard::moveDown() { for (size_t col = 0; col &lt; N; ++col) { std::vector&lt;bool&gt; hasBeenCombined(N, false); for (size_t adjacentRow = N - 1; adjacentRow &gt; 0; --adjacentRow) { const auto row = adjacentRow - 1; const auto value = board[row][col]; const auto nextNonzeroOrLastRow = getNextNonzeroOrLastRow(row, col); if (board[nextNonzeroOrLastRow][col] == 0) board.back()[col] = value; else if ( board[nextNonzeroOrLastRow][col] == value &amp;&amp; !hasBeenCombined[nextNonzeroOrLastRow]) { board[nextNonzeroOrLastRow][col] += value; hasBeenCombined[nextNonzeroOrLastRow] = true; } else if (nextNonzeroOrLastRow != adjacentRow) board[nextNonzeroOrLastRow - 1][col] = value; else continue; board[row][col] = 0; } } } void GameBoard::moveUp() { for (size_t col = 0; col &lt; N; ++col) { std::vector&lt;bool&gt; hasBeenCombined(N, false); for (size_t adjacentRow = 0; adjacentRow &lt; N - 1; ++adjacentRow) { const auto row = adjacentRow + 1; const auto value = board[row][col]; const auto previousNonzeroOrFirstRow = getPreviousNonzeroOrFirstRow(row, col); if (board[previousNonzeroOrFirstRow][col] == 0) board.front()[col] = value; else if ( board[previousNonzeroOrFirstRow][col] == value &amp;&amp; !hasBeenCombined[previousNonzeroOrFirstRow]) { board[previousNonzeroOrFirstRow][col] += value; hasBeenCombined[previousNonzeroOrFirstRow] = true; } else if (previousNonzeroOrFirstRow != adjacentRow) board[previousNonzeroOrFirstRow + 1][col] = value; else continue; board[row][col] = 0; } } } size_t GameBoard::getNextNonzeroOrLastColumn(size_t row, size_t col) { while (col &lt; N - 1 &amp;&amp; board[row][++col] == 0) ; return col; } size_t GameBoard::getPreviousNonzeroOrFirstColumn(size_t row, size_t col) { while (col &gt; 0 &amp;&amp; board[row][--col] == 0) ; return col; } size_t GameBoard::getNextNonzeroOrLastRow(size_t row, size_t col) { while (row &lt; N - 1 &amp;&amp; board[++row][col] == 0) ; return row; } size_t GameBoard::getPreviousNonzeroOrFirstRow(size_t row, size_t col) { while (row &gt; 0 &amp;&amp; board[--row][col] == 0) ; return row; } </code></pre> <p>The corresponding header:</p> <pre><code>#pragma once #include &lt;vector&gt; #ifdef GAME_EXPORTS #define GAME_API __declspec(dllexport) #else #define GAME_API __declspec(dllimport) #endif class GameBoard { // Order important for construction. std::vector&lt;std::vector&lt;double&gt;&gt; board; const size_t N; public: GAME_API GameBoard(std::vector&lt;std::vector&lt;double&gt;&gt; board); GAME_API const std::vector&lt;std::vector&lt;double&gt;&gt; &amp;getBoard(); GAME_API void moveRight(); GAME_API void moveLeft(); GAME_API void moveDown(); GAME_API void moveUp(); private: size_t getNextNonzeroOrLastColumn(size_t row, size_t col); size_t getPreviousNonzeroOrFirstColumn(size_t row, size_t col); size_t getNextNonzeroOrLastRow(size_t row, size_t col); size_t getPreviousNonzeroOrFirstRow(size_t row, size_t col); }; </code></pre> <p>The following tests demonstrate the intended usage:</p> <pre><code>#include "stdafx.h" #include "CppUnitTest.h" #include &lt;GameBoard.h&gt; #include "assert_utility.h" #include "test_board_utility.h" namespace MSTest { TEST_CLASS(GameBoardTester) { public: TEST_METHOD(testInvalidBoardThrows) { using namespace Microsoft::VisualStudio::CppUnitTestFramework; Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({}); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ {}, {} }); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ { 0 }, {} }); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ {}, { 0 } }); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ { 0 }, { 0 } }); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ { 0, 0 }, {} }); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ {}, { 0, 0 } }); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ { 0, 0 }, { 0 } }); }); Assert::ExpectException&lt;std::runtime_error&gt;([]() { GameBoard({ { 0 }, { 0, 0 } }); }); GameBoard( { { 0 } } ); GameBoard( { { 0, 0 }, { 0, 0 } }); GameBoard( { { 0, 0, 0 }, { 0, 0, 0 }, { 0, 0, 0 } }); GameBoard( { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testAllZeros) { assertAllRotatedTransformTransitions( { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } private: void assertAllRotatedTransformTransitions( std::vector&lt;std::vector&lt;double&gt;&gt; initial, std::string movement, std::vector&lt;std::vector&lt;double&gt;&gt; final ) { for (int i = 0; i &lt; 4; i++) { assertBoardTransition(initial, movement, final); initial = rotateClockwise(std::move(initial)); movement = clockwiseMovementTransform(std::move(movement)); final = rotateClockwise(std::move(final)); } } void assertBoardTransition( const std::vector&lt;std::vector&lt;double&gt;&gt; &amp;initial, const std::string &amp;movement, const std::vector&lt;std::vector&lt;double&gt;&gt; &amp;final ) { GameBoard board(initial); for (const auto &amp;c : movement) switch (c) { case 'r': case 'R': board.moveRight(); break; case 'd': case 'D': board.moveDown(); break; case 'l': case 'L': board.moveLeft(); break; case 'u': case 'U': board.moveUp(); break; } assertAreEqual(final, board.getBoard()); } std::string clockwiseMovementTransform(std::string movement) { for (auto &amp;c : movement) switch (c) { case 'r': case 'R': c = 'd'; break; case 'd': case 'D': c = 'l'; break; case 'l': case 'L': c = 'u'; break; case 'u': case 'U': c = 'r'; break; } return movement; } public: TEST_METHOD(testOneTwo) { assertAllRotatedTransformTransitions( { { 2, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 2, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 0, 2, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 0, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testTwoTwos) { assertAllRotatedTransformTransitions( { { 2, 2, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 0, 2, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 0, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 2, 2, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 2, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 0, 2, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testThreeTwos) { assertAllRotatedTransformTransitions( { { 2, 2, 2, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 2, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 0, 2, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 2, 2, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testFourTwos) { assertAllRotatedTransformTransitions( { { 2, 2, 2, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 4, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testTwoUnequals) { assertAllRotatedTransformTransitions( { { 2, 4, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 0, 4, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 0, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 2, 4, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 2, 0, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 2, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testThreeUnequals) { assertAllRotatedTransformTransitions( { { 2, 4, 8, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 2, 4, 8 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 4, 0, 8 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 2, 4, 8 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 2, 0, 4, 8 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 2, 4, 8 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 2, 4, 8 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 2, 4, 8 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testFourUnequals) { assertAllRotatedTransformTransitions( { { 2, 4, 8, 16 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 2, 4, 8, 16 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testCombinesOnlyOnce) { assertAllRotatedTransformTransitions( { { 4, 2, 2, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 4, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 4, 2, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 4, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 4, 0, 2, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 4, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); assertAllRotatedTransformTransitions( { { 0, 4, 2, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "r", { { 0, 0, 4, 4 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testTwiceAllZeros) { assertAllRotatedTransformTransitions( { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "rr", { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testThreeCombos) { assertAllRotatedTransformTransitions( { { 8, 4, 2, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }, "rrr", { { 0, 0, 0, 16 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } TEST_METHOD(testUnfortunateBoard) { assertAllRotatedTransformTransitions( { { 2, 4, 2, 4 }, { 4, 2, 4, 2 }, { 2, 4, 2, 4 }, { 4, 2, 4, 2 } }, "rdlu", { { 2, 4, 2, 4 }, { 4, 2, 4, 2 }, { 2, 4, 2, 4 }, { 4, 2, 4, 2 } }); } TEST_METHOD(testVeryFortunateBoard) { assertAllRotatedTransformTransitions( { { 2, 2, 2, 2 }, { 2, 2, 2, 2 }, { 2, 2, 2, 2 }, { 2, 2, 2, 2 } }, "rdlu", { { 32, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }); } }; }; </code></pre> <p>The repository including tests can be found <a href="https://github.com/sbash64/2048/tree/bf3fb8d64a16cce3b23b4dbd629e09b072dde839" rel="noreferrer">here</a>.</p>
[]
[ { "body": "<p>One way to do this, is to have a <code>Cell</code> class. This way you make your board a <code>vector&lt;vector&lt;Cell*&gt;&gt;</code> You can have one collection that is organized by rows and one that is organized by columns. The overhead is minimal because they're stored as pointers. </p>\n...
{ "AcceptedAnswerId": "203219", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T18:04:18.480", "Id": "203041", "Score": "8", "Tags": [ "c++", "algorithm", "2048" ], "Title": "2048 game: logic implementation" }
203041
<p>I did the following two exercises in <em>Programming: Principles and Practice Using C++ (2nd Edition)</em>, by Stroustrup, which build upon each other:</p> <p>From Chapter 22 (Ideals and History),</p> <blockquote> <ol start="15"> <li>Write a program that given a file of (name,year) pairs, such as (Algol,1960) and (C,1974), graphs the names on a timeline.</li> <li>Modify the program from the previous exercise so that it reads a file of (name,year,(ancestor)) tuples, such as (Fortran,1956,()), (Algol,1960,(Fortran)), and (C++,1985,(C,Simula)), and graphs them on a timeline with arrows from ancestor to descendants.</li> </ol> </blockquote> <p>The result I got looks like this: <a href="https://i.stack.imgur.com/X8g4U.png" rel="noreferrer"><img src="https://i.stack.imgur.com/X8g4U.png" alt="screenshot"></a></p> <p>I used <a href="https://bumpyroadtocode.com/2017/08/05/how-to-install-and-use-fltk-1-3-4-in-visual-studio-2017-complete-guide/" rel="noreferrer">FLTK on Visual Studio</a> to draw this with the <a href="http://www.stroustrup.com/Programming/PPP2code/" rel="noreferrer">support files of the book</a>. I will only post the code I added to these files to solve the exercise to not blow up this post too much.</p> <p>Here my approach to solve this Excercise:</p> <p>First of all I created a file which contains languages and ancestors:</p> <p><b> languages.txt </b></p> <pre><code>(Plankalkül,1948,()), (Assembly,1949,()), (Fortran,1956,()), (LISP,1958,()), (Algol58,1958,(Plankalkül,Fortran)), (COBOL,1959,()), (Algol60,1960,(Algol58)), (CPL,1963,(Algol60)), (PL/I,1964,(COBOL,Fortran,Algol60)), (BASIC,1964,(Algol60,Fortran)), (P'',1964,()), (Simula,1965,(Algol60)), (Euler,1965,(Algol60)), (IMP,1965,(Algol60)), (Algol-W,1966,(Algol60)), (BCPL,1967,(CPL)), (Logo,1967,(LISP)), (Algol68,1968,(Algol60)), (Planner,1969,()), (B,1969,(BCPL,PL/I)), (Pascal,1970,(Algol W)), (PLEX,1970,()), (Smalltalk,1972,(LISP,Simula,Euler,IMP,Planner,Logo)), (C,1972,(B,Algol68,Assembly,PL/I,Fortran)), (Prolog,1972,(Planner)), (Modula-2,1978,(Algol-W,Pascal)), (C with Classes,1980,(C,BCPL,Simula)), (ADA,1980,(Algol68,Pascal,Modula-2)), (Turbo Pascal,1983,(Pascal)), (Objective C,1984,(C,Smalltalk)), (ABC,1985,()), (Early C++,1985,(C with Classes)), (Erlang,1986,(Prolog,Smalltalk,PLEX,LISP)), (Eiffel,1986,(Ada,Algol68,Simula)), (Object Pascal,1986,(Turbo Pascal,Simula,Smalltalk)), (Perl,1987,(C,Early C++,LISP,Pascal)), (C89,1989,(C,C with Classes)), (ARM C++,1989,(Early C++,C89)), (Python,1990,(ABC,C89,ARM C++)), (Visual Basic,1991,(BASIC)), (Brainfuck,1993,(P'')), (Java,1995,(ARM C++,Smalltalk,Objective C)), (C95,1995,(C89)), (C++98,1998,(ARM C++,C89)), (C99,1999,(C95,ARM C++)), (C#,2001,(Java,C++98,Objective Pascal)), (D,2001,(C99,C++98,C#,Eiffel,Java,Python)), (Visual Basic .NET,2001,(Visual Basic)), (LOLCODE,2007,()), (Go,2009,(C99,BCPL,Pascal,Smalltalk)), (C11,2011,(C99)), (C++11,2011,(C++98)), (C++14,2014,(C++11)), (C++17,2017,(C++14)), (C18,2018,(C11)), </code></pre> <p>For the file i/o i defined a class <code>Programming_language</code> to read in the data of the file.</p> <p><b> Programming_language.h </b></p> <pre><code>#ifndef PROGRAMMING_LANGUAGE_GUARD_29082018 #define PROGRAMMING_LANGUAGE_GUARD_29082018 #include &lt;string&gt; #include &lt;vector&gt; namespace programming_language { using Name = std::string; using Year = size_t; using Position = size_t; class Programming_language { public: Programming_language() = default; Programming_language(const Name&amp; name, const Year&amp; year, const std::vector&lt;Name&gt;&amp; name_of_presessors) :m_name{ name }, m_year{ year }, m_position{ 0 },m_name_of_predessors{ name_of_presessors } { } Name get_name() const { return m_name; } Year get_year() const { return m_year; } void set_position(Position position) { m_position = position; } Position get_position() const { return m_position; } std::vector&lt;Name&gt; get_name_of_predessors() const { return m_name_of_predessors;} private: Name m_name; Year m_year; // position on x-graph Position m_position; // position on y-graph std::vector&lt;Name&gt; m_name_of_predessors; }; bool read_sign(std::istream&amp; is, char expected_sign); std::istream&amp; operator&gt;&gt;(std::istream&amp; is, Programming_language&amp; obj); std::vector&lt;Programming_language&gt; read_from_file(const std::string&amp; filename); } #endif </code></pre> <p><b> Programming_language.cpp </b></p> <pre><code>#include "Programming_language.h" #include &lt;cctype&gt; #include &lt;exception&gt; #include &lt;fstream&gt; #include &lt;filesystem&gt; namespace programming_language { bool read_sign(std::istream&amp; is, char expected_sign) { char sign = is.get(); if (sign != expected_sign) { is.putback(sign); is.setstate(std::ios::failbit); return false; } return true; } std::istream&amp; operator&gt;&gt;(std::istream&amp; is, Programming_language&amp; obj) // valid formats: // (Algol58,1958,(Plankalkül,Fortran), // (Assembly,1949,()), { is &gt;&gt; std::ws; if (!read_sign(is, '(')) { return is; } Name name; for (char c; c = is.get();) { if (c == ',') break; name.push_back(c); } if (!is) { is.setstate(std::ios::failbit); return is; } std::string str_number; for (char c; is &gt;&gt; c;) { if (c == ',') break; str_number.push_back(c); } Year number{}; try { number = std::stoi(str_number); } catch (...) { is.setstate(std::ios::failbit); return is; } if (!read_sign(is, '(')) { return is; } std::vector&lt;Name&gt; predessor_names; Name current_name; for (char c; c=is.get();) { if (c == ')') { predessor_names.push_back(current_name); break; } else if (c == ',') { predessor_names.push_back(current_name); current_name.clear(); } else { current_name.push_back(c); } } if (!is) { is.setstate(std::ios::failbit); return is; } if (!read_sign(is, ')')) { return is; } if (!read_sign(is, ',')) { return is; } obj = Programming_language{ name ,number,predessor_names }; return is; } std::vector&lt;Programming_language&gt; read_from_file(const std::string&amp; filename) { std::ifstream ifs{ filename }; if (!ifs) { throw std::filesystem::filesystem_error( "std::vector&lt;Programming_language&gt; read_from_file(const std::string&amp; filename)\n" "File could not be opened", std::error_code{}); } std::vector&lt;Programming_language&gt; languages; for (Programming_language p; ifs &gt;&gt; p;) { languages.push_back(p); } return languages; } } </code></pre> <p>Now to display the data on the Screen I used the libraries from stroustrup as a base. He already provides some Shapes so i derived from them to create a Text_ellipse.class and a Arrow.class. These are used to draw the languages and the arrows between them.</p> <p><b> Arrow.h </b></p> <pre><code>#ifndef ARROW_GUARD_300820181840 #define ARROW_GUARD_300820181840 #include "Graph.h" namespace Graph_lib { class Arrow : public Shape { public: Arrow(Point p1, Point p2, int arrow_height, int arrow_width); void draw_lines() const; private: int m_arrow_height; int m_arrow_width; }; inline bool line_pointing_down(const Point&amp; p_start, const Point&amp; p_end) { return p_end.x == p_start.x &amp;&amp; p_end.y &gt; p_start.y; } inline bool line_pointing_up(const Point&amp; p_start, const Point&amp; p_end) { return p_end.x == p_start.x &amp;&amp; p_start.y &gt; p_end.y; } inline bool line_pointing_left(const Point&amp; p_start, const Point&amp; p_end) { return p_end.y == p_start.y &amp;&amp; p_start.x &gt; p_end.x; } inline bool line_pointing_right(const Point&amp; p_start, const Point&amp; p_end) { return p_end.y == p_start.y &amp;&amp; p_start.x &lt; p_end.x; } inline bool line_pointing_up_right(const Point&amp; p_start, const Point&amp; p_end) { return p_start.x &lt; p_end.x &amp;&amp; p_end.y &lt; p_start.y; } inline bool line_pointing_up_left(const Point&amp; p_start, const Point&amp; p_end) { return p_start.x &gt; p_end.x &amp;&amp; p_end.y &lt; p_start.y; } inline bool line_pointing_down_right(const Point&amp; p_start, const Point&amp; p_end) { return p_start.x &lt; p_end.x &amp;&amp; p_end.y &gt; p_start.y; } inline bool line_pointing_down_left(const Point&amp; p_start, const Point&amp; p_end) { return p_start.x &gt; p_end.x &amp;&amp; p_end.y &gt; p_start.y; } double calculate_alpha(const Point&amp; p_start, const Point&amp; p_end); inline double calculate_triangle_side_a(double alpha, double side_c) { return side_c * std::sin(alpha); } inline double calculate_triangle_side_b(double alpha, double side_c) { return side_c * std::cos(alpha); } std::pair&lt;Point, Point&gt; calculate_arrow_points(const int arrow_height, const int arrow_width, const Point p_start, const Point p_end); } #endif </code></pre> <p><b> Arrow.cpp </b></p> <pre><code>#include "Arrow.h" #include &lt;cmath&gt; #include &lt;utility&gt; namespace Graph_lib { Arrow::Arrow(Point p_start, Point p_end, int arrow_height, int arrow_width) // construct a line from two points : m_arrow_height{ arrow_height }, m_arrow_width{ arrow_width } { add(p_start); // add p_start to this shape add(p_end); // add p_end to this shape } void Arrow::draw_lines() const { Shape::draw_lines(); auto arrow_points_left_right = calculate_arrow_points(m_arrow_height, m_arrow_width, point(0), point(1)); Point p_arrow_left = arrow_points_left_right.first; Point p_arrow_right = arrow_points_left_right.second; Fl_Color oldc = fl_color(); // there is no good portable way of retrieving the current style fl_color(color().as_int()); // set color fl_line_style(style().style(), style().width()); // set style if (color().visibility()) { // draw sole pixel? fl_line(p_arrow_left.x, p_arrow_left.y, p_arrow_right.x, p_arrow_right.y); fl_line(p_arrow_right.x, p_arrow_right.y, point(1).x, point(1).y); fl_line(point(1).x, point(1).y, p_arrow_left.x, p_arrow_left.y); } fl_color(oldc); // reset color (to previous) fl_line_style(0); // reset line style to default if (fill_color().visibility()) { fl_color(fill_color().as_int()); fl_begin_complex_polygon(); fl_vertex(p_arrow_left.x, p_arrow_left.y); fl_vertex(p_arrow_right.x, p_arrow_right.y); fl_vertex(point(1).x, point(1).y); fl_end_complex_polygon(); fl_color(color().as_int()); // reset color } } double calculate_alpha(const Point&amp; p_start, const Point&amp; p_end) { double alpha = 0; if (line_pointing_up_right(p_start, p_end)) { return std::atan(static_cast&lt;double&gt;(p_start.y - p_end.y) / static_cast&lt;double&gt;(p_end.x - p_start.x)); } else if (line_pointing_up_left(p_start, p_end)) { return std::atan(alpha = static_cast&lt;double&gt;(p_start.y - p_end.y) / static_cast&lt;double&gt;(p_start.x - p_end.x)); } else if (line_pointing_down_right(p_start, p_end)) { return std::atan(static_cast&lt;double&gt;(p_end.y - p_start.y) / static_cast&lt;double&gt;(p_end.x - p_start.x)); } else if (line_pointing_down_left(p_start, p_end)) { return std::atan(static_cast&lt;double&gt;(p_end.y - p_start.y) / static_cast&lt;double&gt;(p_start.x - p_end.x)); } else { throw std::runtime_error( "double calculate_alpha(const Point&amp; p_start, const Point&amp; p_end)\n" "Invalid posiition of line\n"); } } std::pair&lt;Point, Point&gt; calculate_arrow_points(const int arrow_height, const int arrow_width, const Point p_start, const Point p_end) { if (line_pointing_down(p_start,p_end)) { Point p_arrow_left{ p_end.x + arrow_width / 2 ,p_end.y - arrow_height }; Point p_arrow_right{ p_end.x - arrow_width / 2 ,p_arrow_left.y }; return std::make_pair(p_arrow_left, p_arrow_right); } else if (line_pointing_up(p_start, p_end)) { Point p_arrow_left{ p_end.x - arrow_width / 2 , p_end.y + arrow_height }; Point p_arrow_right{ p_end.x + arrow_width / 2 ,p_arrow_left.y }; return std::make_pair(p_arrow_left, p_arrow_right); } else if (line_pointing_left(p_start, p_end)) { Point p_arrow_left{ p_end.x + arrow_height,p_end.y + arrow_width / 2 }; Point p_arrow_right{ p_arrow_left.x,p_end.y - arrow_width / 2 }; return std::make_pair(p_arrow_left, p_arrow_right); } else if (line_pointing_right(p_start, p_end)) { Point p_arrow_left{ p_end.x - arrow_height,p_end.y - arrow_width / 2 }; Point p_arrow_right{ p_arrow_left.x,p_end.y + arrow_width / 2 }; return std::make_pair(p_arrow_left, p_arrow_right); } else { auto alpha = calculate_alpha(p_start, p_end); auto length_p_end_to_arrow_bottom_x = calculate_triangle_side_b(alpha, arrow_height); auto length_p_end_to_arrow_bottom_y = calculate_triangle_side_a(alpha, arrow_height); const double pi = std::atan(1) * 4; double alpha1 = pi / 2.0 - alpha; auto length_arrow_bottom_to_left_right_x = calculate_triangle_side_b(alpha1, arrow_width / 2.0); auto length_arrow_bottom_to_left_right_y = calculate_triangle_side_a(alpha1, arrow_width / 2.0); if (line_pointing_up_right(p_start, p_end)) { Point p_arrow_left{ p_end.x - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x + length_arrow_bottom_to_left_right_x), p_end.y + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y - length_arrow_bottom_to_left_right_y) }; Point p_arrow_right{ p_end.x - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x - length_arrow_bottom_to_left_right_x), p_end.y + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y + length_arrow_bottom_to_left_right_y) }; return std::make_pair(p_arrow_left, p_arrow_right); } else if (line_pointing_up_left(p_start, p_end)) { Point p_arrow_left{ p_end.x + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x - length_arrow_bottom_to_left_right_x), p_end.y + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y + length_arrow_bottom_to_left_right_y) }; Point p_arrow_right{ p_end.x + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x + length_arrow_bottom_to_left_right_x), p_end.y + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y - length_arrow_bottom_to_left_right_y) }; return std::make_pair(p_arrow_left, p_arrow_right); } else if (line_pointing_down_right(p_start, p_end)) { Point p_arrow_left{ p_end.x - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x + length_arrow_bottom_to_left_right_x), p_end.y - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y - length_arrow_bottom_to_left_right_y) }; Point p_arrow_right{ p_end.x - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x - length_arrow_bottom_to_left_right_x), p_end.y - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y + length_arrow_bottom_to_left_right_y) }; return std::make_pair(p_arrow_left, p_arrow_right); } else if (line_pointing_down_left(p_start, p_end)) { Point p_arrow_left{ p_end.x + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x - length_arrow_bottom_to_left_right_x), p_end.y - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y + length_arrow_bottom_to_left_right_y) }; Point p_arrow_right{ p_end.x + static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_x + length_arrow_bottom_to_left_right_x), p_end.y - static_cast&lt;int&gt;(length_p_end_to_arrow_bottom_y - length_arrow_bottom_to_left_right_y) }; return std::make_pair(p_arrow_left, p_arrow_right); } } } } </code></pre> <p><b> Text_ellipse.h </b></p> <pre><code>#ifndef TEXT_ELLIPSE_GUARD_300820182217 #define TEXT_ELLIPSE_GUARD_300820182217 #include "Graph.h" namespace Graph_lib { class Text_ellipse : public Ellipse { public: Text_ellipse(Point p, const std::string&amp; text_label, int font_size); void draw_lines() const override; std::string label() { return text.label(); } private: Text text; }; int calculate_ellipse_width(const std::string&amp; text_label, int font_size); int calculate_ellipse_height(int font_size); Point calculate_ellipse_text_position(Point p, const std::string&amp; text_label, int font_size); Point north(Text_ellipse&amp; text_ellipse); Point east(Text_ellipse&amp; text_ellipse); Point south(Text_ellipse&amp; text_ellipse); Point west(Text_ellipse&amp; text_ellipse); } #endif </code></pre> <p><b> Text_ellipse.cpp </b></p> <pre><code>#include "Text_ellipse.h" namespace Graph_lib { Text_ellipse::Text_ellipse(Point p, const std::string&amp; text_label, int font_size) : Ellipse( p, calculate_ellipse_width(text_label, font_size), calculate_ellipse_height(font_size) ), text{ calculate_ellipse_text_position(p,text_label,font_size), text_label } { text.set_font_size(font_size); } void Text_ellipse::draw_lines() const { Ellipse::draw_lines(); text.draw_lines(); } int calculate_ellipse_width(const std::string&amp; text_label, int font_size) { return static_cast&lt;int&gt;(text_label.size()*font_size * 0.4); } int calculate_ellipse_height(int font_size) { return static_cast&lt;int&gt;(font_size * 0.7); } Point calculate_ellipse_text_position(Point p, const std::string&amp; text_label, int font_size) { return Point{ p.x - static_cast&lt;int&gt;(calculate_ellipse_width(text_label, font_size) * 0.8), p.y + static_cast&lt;int&gt;(calculate_ellipse_height(font_size) * 0.55) }; } Point north(Text_ellipse&amp; text_ellipse) { return Point{ text_ellipse.point(0).x + text_ellipse.major(), text_ellipse.point(0).y }; } Point east(Text_ellipse&amp; text_ellipse) { return Point{ text_ellipse.point(0).x + text_ellipse.major() * 2, text_ellipse.point(0).y + text_ellipse.minor() }; } Point south(Text_ellipse&amp; text_ellipse) { return Point{ text_ellipse.point(0).x + text_ellipse.major(), text_ellipse.point(0).y + text_ellipse.minor() * 2 }; } Point west(Text_ellipse&amp; text_ellipse) { return Point{ text_ellipse.point(0).x, text_ellipse.point(0).y + text_ellipse.minor() }; } } </code></pre> <p>I used a small helper class to scale the x and the y axis:</p> <p><b> Scale.h </b></p> <pre><code>#ifndef SCALE_GUARD_310820181451 #define SCALE_GUARD_310820181451 namespace programming_language { class Scale { public: Scale(int coordinate_base, int base_of_values, double scale) :m_coordinate_base{ coordinate_base }, m_base_of_values{ base_of_values }, m_scale{ scale } { } int operator()(int value) const { return static_cast&lt;int&gt;(m_coordinate_base + (value - m_base_of_values)*m_scale); } private: int m_coordinate_base; int m_base_of_values; double m_scale; }; } #endif </code></pre> <p>Now the biggest headache i had during implementation, was how to place the elements on the y-axis. The x-axis is pretty clear It is just by the years in the file. The y-axis should place the text_ellipse objects on thescreen that they dont overlap. I created a class Grid_y and a class Grid to assign the languages the y position. The Goal here was that the objects dont intersect with each other.</p> <p>The first object is always put in the middle of the y_grid. If more objects are added and intersect with the previous objects they get put out of the middle. See the code of the classes.</p> <p><b> Grid_y.h </b></p> <pre><code>#ifndef GRID_Y_GUARD_160820181608 #define GRID_Y_GUARD_160820181608 #include &lt;vector&gt; namespace programming_language { class Grid_y { public: explicit Grid_y(int size) :positions_occupied(size,false) { } int next_free_position(); void occupy(int position) { positions_occupied[position] = true; } void release(int position) { positions_occupied[position] = false; } bool is_free(int position) { return !positions_occupied[position]; } private: std::vector&lt;bool&gt; positions_occupied; }; } #endif </code></pre> <p><b> Grid_y.cpp </b></p> <pre><code>#include "Grid_y.h" namespace programming_language { int Grid_y::next_free_position() // returns the next free position on the grid // first it is always occupied the middle // if already occupied take middle +1 // if middle + 1 occupied try middle -1 // then middle +2 and so on... // return -1 to indicate whole grid is full { auto start = 0; if (positions_occupied.size() / 2 == 0) { start = (positions_occupied.size() / 2) - 1; } else { start = (positions_occupied.size() / 2); } auto highest = start; auto lowest = start; if (!positions_occupied[start]) { return start; } else { ++highest; } for (;;) { if (!positions_occupied[highest]) { return highest; } else { if (lowest == 0) { return -1; } --lowest; } if (!positions_occupied[lowest]) { return lowest; } else { if (highest == positions_occupied.size() - 1) { return -1; } ++highest; } } } } </code></pre> <p><b> Grid.h </b></p> <pre><code>#ifndef GRID_GUARD_310820181828 #define GRID_GUARD_310820181828 #include "Grid_y.h" #include &lt;vector&gt; namespace programming_language { class Grid { public: Grid(int x_begin, int x_end, int y_begin, int y_end); int occupy(int x_value, double length); private: std::vector&lt;Grid_y&gt; x_axis; int m_x_begin; int m_x_end; }; } #endif </code></pre> <p><b> Grid.cpp </b></p> <pre><code>#include "Grid.h" #include &lt;cmath&gt; namespace programming_language { Grid::Grid(int x_begin,int x_end, int y_begin, int y_end) :m_x_begin{x_begin},m_x_end{x_end} { if (x_begin &gt; x_end) { throw std::range_error( "Grid(int x_begin,int x_end, int y_begin, int y_end)\n" "x_begin &gt; x_end"); } if (y_begin &gt; y_end) { throw std::range_error( "Grid(int x_begin,int x_end, int y_begin, int y_end)\n" "y_begin &gt; y_end"); } for (int i = 0; i &lt; (x_end-x_begin)+1; ++i) { x_axis.push_back(Grid_y{ y_end - y_begin+1}); } } int Grid::occupy(int x_position, double length) { length = std::ceil(length); // round up to the next notch int x_position_begin = x_position - length - m_x_begin; if (x_position_begin &lt; 0) { x_position_begin = 0; } int x_position_end = x_position + length - m_x_begin; if (x_position_end &gt;= x_axis.size()) { x_position_end = x_axis.size() - 1; } x_position = x_position - m_x_begin; std::vector&lt;int&gt; marked_elements; for (;;) { auto free_position_y = x_axis[x_position].next_free_position(); if (free_position_y == -1) { for (auto&amp; x : marked_elements) { x_axis[x_position].release(x); } return free_position_y; } // range is free bool range_is_free = true; for (int i = x_position_begin; i &lt;= x_position_end; ++i) { if (!x_axis[i].is_free(free_position_y)) { range_is_free = false; break; } } // install element on grid if (range_is_free) { for (int i = x_position_begin; i &lt;= x_position_end; ++i) { x_axis[i].occupy(free_position_y); } for (auto&amp; x : marked_elements) { x_axis[x_position].release(x); } return free_position_y; } else { // mark the element in center to get a new free element on next iteration x_axis[x_position].occupy(free_position_y); marked_elements.push_back(free_position_y); } } } } </code></pre> <p>The Window is drawn and the presented classes are used in Programming_language_gui.</p> <p><b> Programming_language_gui.h </b></p> <pre><code>#ifndef PROGRAMMING_LANGUAGE_GUI_GUARD_300820181737 #define PROGRAMMING_LANGUAGE_GUI_GUARD_300820181737 #include "Programming_language.h" #include "Grid.h" #include "Scale.h" #include "Text_ellipse.h" namespace programming_language { int gui_display_languages(); Year find_min_year(const std::vector&lt;Programming_language&gt;&amp; languages); Year find_max_year(const std::vector&lt;Programming_language&gt;&amp; languages); Year first_year_of_decade(const Year&amp; year); Year first_year_of_next_decade(const Year&amp; year); std::string make_x_axis_label(const Year&amp; start_year, const Year&amp; end_year, int x_axis_length); std::vector&lt;Programming_language&gt; put_on_grid(const std::vector&lt;Programming_language&gt;&amp; languages, Grid grid, int font_size, double x_scale); Graph_lib::Color get_shuffled_color(); } #endif </code></pre> <p><b> Programming_language_gui.cpp </b></p> <pre><code>#include "Programming_language_gui.h" #include "Window.h" #include "Graph.h" #include "Arrow.h" #include &lt;algorithm&gt; #include &lt;random&gt; #include &lt;cmath&gt; namespace programming_language { int gui_display_languages() { auto programming_languages = read_from_file("languages.txt"); constexpr int xmax = 1600; constexpr int ymax = 900; constexpr int xoffset = 100; constexpr int yoffset = 60; constexpr int xspace = 40; constexpr int yspace = 40; constexpr int xlength = xmax - xoffset - xspace; constexpr int ylength = ymax - yoffset - yspace; const int start_year = first_year_of_decade(find_min_year(programming_languages)); const int end_year = first_year_of_next_decade(find_max_year(programming_languages)); const int x_count = (end_year - start_year); constexpr int y_count = 20; const double xscale = double(xlength) / x_count; const double yscale = double(ylength) / y_count; Scale xs{ xoffset,start_year,xscale }; Scale ys{ ymax - yoffset,0,-yscale }; Graph_lib::Window win{ Point{100,100},xmax,ymax,"Programming Languages" }; Graph_lib::Axis x{ Graph_lib::Axis::x, Point{xoffset,ymax - yoffset},xlength,(end_year - start_year) / 1, make_x_axis_label(start_year,end_year,xlength) }; x.label.move(static_cast&lt;int&gt;(-xlength / 3.6), 0); // position to begin of axis Graph_lib::Axis y{ Graph_lib::Axis::y, Point{xoffset,ymax - yoffset},ylength,20,"" }; x.set_color(Graph_lib::Color::black); y.set_color(Graph_lib::Color::black); win.attach(x); win.attach(y); auto language_font_size = static_cast&lt;int&gt;(yscale*0.5); programming_languages = put_on_grid(programming_languages, Grid{ start_year,end_year,0,y_count }, language_font_size, xscale); Graph_lib::Vector_ref&lt;Graph_lib::Text_ellipse&gt; gui_languages; for (const auto&amp; language : programming_languages) { gui_languages.push_back( new Graph_lib::Text_ellipse{ Point{ xs(language.get_year()), ys(language.get_position()) }, language.get_name(), language_font_size } ); gui_languages[gui_languages.size() - 1].set_fill_color(Graph_lib::Color::yellow); gui_languages[gui_languages.size() - 1].set_color(Graph_lib::Color::black); } const int arrow_height = static_cast&lt;int&gt;(xscale / 2); const int arrow_width = static_cast&lt;int&gt;(xscale / 2); Graph_lib::Vector_ref&lt;Graph_lib::Arrow&gt; gui_arrows; for (auto target = 0; target &lt; gui_languages.size(); ++target) { std::string name = gui_languages[target].label(); auto it = std::find_if(programming_languages.begin(), programming_languages.end(), [&amp;name](const Programming_language&amp; pl) { return pl.get_name() == name; }); if (it != programming_languages.end()) { auto name_of_predessors = it-&gt;get_name_of_predessors(); auto color = get_shuffled_color(); for (const auto&amp; predessor : name_of_predessors) { for (auto source = 0; source &lt; gui_languages.size(); ++source) { if (predessor == gui_languages[source].label()) { gui_arrows.push_back( new Graph_lib::Arrow{ east(gui_languages[source]), west(gui_languages[target]), arrow_height, arrow_width } ); gui_arrows[gui_arrows.size() - 1].set_color(color); gui_arrows[gui_arrows.size() - 1].set_fill_color(color); } } } } } for (auto i = 0; i &lt; gui_arrows.size(); ++i) { win.attach(gui_arrows[i]); } for (auto i = 0; i &lt; gui_languages.size(); ++i) { win.attach(gui_languages[i]); } return Graph_lib::gui_main(); } Year find_min_year(const std::vector&lt;Programming_language&gt;&amp; languages) { auto it = std::min_element( languages.begin(), languages.end(), [](const Programming_language&amp; a, const Programming_language&amp; b) { return a.get_year() &lt; b.get_year(); } ); return it-&gt;get_year(); } Year find_max_year(const std::vector&lt;Programming_language&gt;&amp; languages) { auto it = std::max_element( languages.begin(), languages.end(), [](const Programming_language&amp; a, const Programming_language&amp; b) { return a.get_year() &lt; b.get_year(); } ); return it-&gt;get_year(); } Year first_year_of_decade(const Year&amp; year) // calculates out of year the first year of the decade // e.g. 1958 -&gt; 1950 { auto decade_year = year; while (decade_year % 10 != 0) { --decade_year; } return decade_year; } Year first_year_of_next_decade(const Year&amp; year) // calculates out of year the first year of the next decade // e.g. 1958 -&gt; 1960 { auto decade_year = year; while (decade_year % 10 != 0) { ++decade_year; } return decade_year; } std::string make_x_axis_label(const Year&amp; start_year, const Year&amp; end_year, int x_axis_length) { std::string label; constexpr auto offset = 5; constexpr auto sign_len = 4; constexpr auto letter_len = 7.0 * sign_len; const auto notch_len = x_axis_length / ((end_year - start_year)/offset); const auto remaining_len = notch_len - letter_len; const int count_of_space = static_cast&lt;int&gt;(remaining_len / sign_len); std::string space(count_of_space,' ' ); for (auto year = start_year; year &lt;= end_year; year += offset){ if (year != start_year) { label += space; } label += std::to_string(year); } return label; } std::vector&lt;Programming_language&gt; put_on_grid(const std::vector&lt;Programming_language&gt;&amp; languages,Grid grid,int font_size,double x_scale) { auto languages_on_grid = languages; for (auto&amp; language : languages_on_grid) { double length = Graph_lib::calculate_ellipse_width(language.get_name(), font_size); length /= x_scale; auto position = grid.occupy(language.get_year(), length); language.set_position(position); } return languages_on_grid; } Graph_lib::Color get_shuffled_color() { static int selection = 0; auto color = Graph_lib::Color::black; switch (selection) { case 0: color = Graph_lib::Color::red; break; case 1: color = Graph_lib::Color::blue; break; case 2: color = Graph_lib::Color::dark_green; break; case 3: color = Graph_lib::Color::magenta; break; case 4: color = Graph_lib::Color::dark_magenta; break; case 5: color = Graph_lib::Color::dark_yellow; break; case 6: color = Graph_lib::Color::dark_blue; break; case 7: color = Graph_lib::Color::black; break; default: color = Graph_lib::Color::red; selection = 0; } ++selection; return color; } } </code></pre> <p><b> main.cpp </b></p> <pre><code>#include "Programming_language_gui.h" int main() { return programming_language::gui_display_languages(); } </code></pre> <p>Now I would like to know the following.</p> <p>Is the Code easy to read / understandable? What would you do to improve readability? Any bad practices?</p> <p>Which stuff could get solved easier?</p> <p>How can the display of the languages be improved. As we can see in the screenshot above the arrows get placed quite messy. Is there a better algorithm to place the languages?</p> <p>I think the most painful parts in this program are the placement of the languages and the calculation of the arrows.</p>
[]
[ { "body": "<p>First of all, congratulations, the result looks really good and that's a lot of work for an exercise! I particularly like how you frequently used standard algorithms.</p>\n\n<p>That is also quite a lot of code to review! You'll excuse me if I don't review it all, actually a tiny part of it. But ra...
{ "AcceptedAnswerId": "203122", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T18:24:48.460", "Id": "203045", "Score": "10", "Tags": [ "c++", "graph", "c++17", "data-visualization", "fltk" ], "Title": "Displaying programming languages on a timeline" }
203045
<p>I wrote a solution to the leetcode problem <a href="https://leetcode.com/problems/sort-characters-by-frequency/description/" rel="noreferrer">Sort characters by frequency</a> and the solution passes 34/35 test cases. On the last test case, there is a "time limit exceeded" error with an input string of 100000+ "a" and "b" characters. <strong>How can the following code be optimized to handle an input of that size?</strong></p> <pre><code> def frequencySort(s): """ :type s: str :rtype: str """ freq = {} for i in s: if i in freq: freq[i] +=1 else: freq[i] = 1 output = "" newDict = sorted(freq.items(), key=lambda kv: kv[1],reverse = True) for k,v in newDict: for i in range(v): output += k return output </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-18T07:05:51.487", "Id": "475867", "Score": "0", "body": "The key issue is the line `output += k` --- this rebuilds the string for each additional character as strings are immutable in Python (see [Shlemiel the painter's algorithm](http...
[ { "body": "<p>The section: </p>\n\n<pre><code>for i in range(v):\n output += k\n</code></pre>\n\n<p>Can be rewritten as:</p>\n\n<pre><code>output += k*v\n</code></pre>\n\n<p>So that characters can be appended to the output in chunks this is much faster then doing it character by character</p>\n", "com...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T19:09:59.990", "Id": "203046", "Score": "5", "Tags": [ "python", "python-3.x", "programming-challenge", "sorting", "time-limit-exceeded" ], "Title": "Sort characters in a Python string by frequency" }
203046
<p>I wrote a JavaScript and XHTML webpage. I think the format of the output is not better or the validation process is not as it is supposed to be. How can I improve the code? How can I make it more efficient?</p> <p>There are two text boxes. First, it takes a sentence and returns the length. Second, it takes an integer and returns that number of classical Fibonacci numbers.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;titile&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; function getStrLen(){ var msgDiv = document.getElementById('textbox1'); document.getElementById('msg').textContent = msgDiv.value.split('').length; } var a = 0; var b = 0; var c = 1; var ONE = 1; function genFibonacci(times){ if(times &lt;=0){return;} a = b; b = c; c = a + b; document.getElementById('fibseq').textContent += a.toString() + (times &gt; ONE ? ", " : " "); genFibonacci(times - 1, false); } function outFib(){ genFibonacci(document.getElementById('fibText').value); } &lt;/script&gt; &lt;button id="lenClick" onclick="getStrLen()"&gt;String Length&lt;/button&gt; Enter a sentence or multiple ones: &lt;input type="text" id="textbox1"&gt;&lt;/input&gt; &lt;br/&gt; Number of characters in this sentence is: &lt;span id="msg"&gt; &lt;/span&gt; &lt;br/&gt; &lt;input type="text" id="fibText"&gt;&lt;/input&gt; &lt;button id="fibClick" onclick="outFib()"&gt;Generate Fibonacci Sequence&lt;/button&gt;&lt;div id="fibseq"&gt;&lt;/div&gt; &lt;/body&gt; &lt;html&gt; </code></pre>
[]
[ { "body": "<h1>Getting the length of a string</h1>\n\n<p>You split the string into characters and then you count the array's length. While this works, there's an even simpler way of doing it, using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length\" rel...
{ "AcceptedAnswerId": "203085", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T21:03:00.250", "Id": "203051", "Score": "1", "Tags": [ "javascript", "strings", "html5", "fibonacci-sequence" ], "Title": "Output string length and classical Fibonacci sequence in a web page" }
203051
<p>I'm trying to write a simple 'n' layered ANN in haskell for supervised learning, it will eventually have back prop and you'll be able to use it in a step by step fashion through a GUI which will graph the error function. This is for learning (so I'm not looking for suggestions on libraries that already solve this problem). In this review I'm mainly looking for feedback on how I've arranged my code and if there are better ways to represent a neural network in Haskell.</p> <p>The approach I'm trying to take is to separate the forward pass from the backward pass, so that the training can be controlled by the consumer (rather than having a network that is just a one shot IO which does forward -> back recursively until error &lt; x). The reason for this is that I can then separate the rendering of the networks state at any given pass (i.e. after each forward pass I can easily just render the current loss of the whole network by applying the cost function across the output vector).</p> <p>Here is the current code for a forward pass of the network. It takes a list of double (which is the input vector) and a list of matrix of double (where each element in the list is a weight matrix representing the weights of each connection on a given layer in the network). The activation function then creates an output vector by recursively applying a forwardPass function through each layer until the final layer 'n' has been evaluated.</p> <p>Here is the code for that:</p> <pre><code>module Training (randomWeights, activate, cost) where import Data.Matrix import System.Random activate :: [Double] -&gt; [Matrix Double] -&gt; Matrix Double activate i weights = forwardPass inputs weights where inputSize = length i inputs = fromList 1 inputSize i forwardPass inputs weights | length weights == 1 = squashedOutputs | otherwise = forwardPass (squashedOutputs) (tail weights) where squashedOutputs = mapPos (\(row, col) a -&gt; leakyRelu a) layerOutputs where layerOutputs = multStd2 inputs (head weights) leakyRelu a | a &gt; 0.0 = a | otherwise = 0.01 * a randomWeights :: (RandomGen g) =&gt; g -&gt; Int -&gt; Int -&gt; Matrix Double randomWeights generator inputSize outputSize = weights where weights = matrix inputSize outputSize (\(col, row) -&gt; (take 10000 $ randomRs (-1.0, 1.0) generator)!!(col * row)) </code></pre> <p>The randomWeights function is consumed in the main function of my program and is used to generate the list of matrix of double to be passed to the forwardPass (i.e. each layers weights). </p> <p>The main function looks like this:</p> <pre><code> main :: IO() main = do generator &lt;- newStdGen let expected = 0.0 let inputs = [0, 1] let inputWeights = randomWeights generator (length inputs) 3 let hiddenWeights = randomWeights generator 3 1 let outputWeights = randomWeights generator 1 1 let outputs = activate inputs [inputWeights, hiddenWeights, outputWeights] print inputs print outputs </code></pre> <p>So it a bit like a unit test (eventually I will wrap the activate/backprop loop into a structure that a user can control by a 'next' button on a GUI, but for now I simply want a solid forwardPass foundation to build off. </p> <p>Does all of this look like reasonable haskell, or are there some obvious improvements I can make?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T21:28:14.573", "Id": "391342", "Score": "0", "body": "Hey, thanks for tagging it with reinventing-the-wheel; no sarcasm, if I'd known that tag existed I'd have used it. I like to do that (reinventing-the-wheel) when learning new lan...
[ { "body": "<blockquote>\n <p><code>\\(col, row) -&gt; (take 10000 $ randomRs (-1.0, 1.0) generator)!!(col * row)</code></p>\n</blockquote>\n\n<p>Oh man you got me going \"no no no no no no\" like I long haven't :D. <code>take 10000</code> does nothing here. <code>col * row</code> is going to come out to the sa...
{ "AcceptedAnswerId": "203075", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T21:06:15.237", "Id": "203052", "Score": "2", "Tags": [ "haskell", "reinventing-the-wheel", "neural-network" ], "Title": "Haskell 'n' layered ANN forward pass" }
203052
<p>I am working on a project and wanted to have a quick look by you people if the schema or query needs some changes or does it totally needs to be changed.</p> <p>The project is about creating a ranking system for the badminton teams where the ranking will be based on the scoring rules in a tournament </p> <ul> <li>+2 Points/match would be awarded to the winning team.</li> <li>An Extra +1 Point would be awarded to the winning team if the match was a Quarter-finals.</li> <li>An Extra +2 Points would be awarded to the winning team if the match was a Semi-finals.</li> <li>An Extra +5 Points would be awarded to the winning team if the match was a Final.</li> <li>Winning all pool matches will add 4 points to your Team score.</li> <li>Winning more than 3 tournaments will add 15 points to your team.</li> </ul> <p>I started by creating the following tables</p> <p><strong>Players</strong></p> <pre><code>+----------+-------------------------------------+------+-----+-------------- | Field | Type | Null | Key | +----------+-------------------------------------+------+-----+-------------- | id | int(11) | NO | PRI | | name | varchar(250) | NO | | | image | text | YES | | | plays | enum('RH','LH') | NO | | | added_on | datetime | NO | | | status | enum('active','inactive','retired') | NO | | +----------+-------------------------------------+------+-----+-------------- </code></pre> <p><strong>Teams</strong></p> <pre><code>+------------+----------------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+----------------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(150) | NO | UNI | NULL | | | image | text | YES | | NULL | | | status | enum('active','in-active') | NO | | active | | | added_on | datetime | NO | | CURRENT_TIMESTAMP | | | updated_on | datetime | YES | | NULL | | +------------+----------------------------+------+-----+-------------------+----------------+ </code></pre> <p><strong>Player To Teams</strong></p> <pre><code>+-----------+---------------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+---------------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | player_id | int(11) | NO | MUL | NULL | | | team_id | int(11) | NO | | NULL | | | status | enum('active','inactive') | NO | | NULL | | | added_on | datetime | NO | | CURRENT_TIMESTAMP | | +-----------+---------------------------+------+-----+-------------------+----------------+ </code></pre> <p><strong>Tournaments</strong></p> <pre><code>+-------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(255) | NO | | NULL | | | year | int(4) | NO | | NULL | | +-------+--------------+------+-----+---------+----------------+ </code></pre> <p><strong>Matches</strong></p> <pre><code>+---------------+---------------------------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+---------------------------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | team_one | int(11) | NO | MUL | NULL | | | team_two | int(11) | NO | | NULL | | | winner_id | int(11) | NO | | NULL | | | tournament_id | int(11) | NO | MUL | 1 | | | added_on | datetime | NO | | CURRENT_TIMESTAMP | | | match_type | enum('pool','quarter','semi','final') | NO | | pool | | | sets | smallint(2) | NO | | 1 | | +---------------+---------------------------------------+------+-----+-------------------+----------------+ </code></pre> <p><strong>Match Score</strong></p> <pre><code>+----------+-------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | match_id | int(11) | NO | MUL | NULL | | | team_id | int(11) | NO | MUL | NULL | | | set_num | enum('1','2','3') | NO | | NULL | | | score | smallint(2) | NO | | NULL | | | added_on | datetime | NO | | CURRENT_TIMESTAMP | | +----------+-------------------+------+-----+-------------------+----------------+ </code></pre> <p><strong>Pools</strong></p> <pre><code>+---------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(10) | NO | UNI | NULL | | | tournament_id | int(11) | NO | MUL | NULL | | +---------------+-------------+------+-----+---------+----------------+ </code></pre> <p>One thing that you will notice that I have not saved rank scoring anywhere and I am calculating it on runtime using the following query</p> <pre><code>SELECT T.id, T.name, T.status, IFNULL(T.image,'no-image.png') as DP, (SELECT COUNT(*) FROM badminton_matches M WHERE ((M.team_one =T.id or M.team_two = T.id) and M.winner_id IS NOT NULL)) as played, (SELECT COUNT(*) FROM badminton_matches M WHERE M.winner_id=T.id) as won, (SELECT COUNT(*) FROM badminton_matches M WHERE ((M.team_one =T.id or M.team_two = T.id) AND (M.winner_id!=T.id))) as lost, ((SELECT (SUM(BMS.points_won)-SUM(BMS.points_lost)) FROM badminton_match_score BMS JOIN badminton_matches M ON (M.id=BMS.match_id) where M.team_one=T.id OR M.team_two=T.id and M.winner_id is not null)/(SELECT COUNT(*) FROM badminton_matches M WHERE ((M.team_one =T.id or M.team_two = T.id) and M.winner_id IS NOT NULL))) AS AVG_SCORE, ( ((SELECT COUNT(*) FROM badminton_matches M WHERE M.winner_id=T.id)*2) + (SELECT COUNT(*) FROM badminton_matches M WHERE (M.match_type='quarter' AND M.winner_id=T.id)) + ((SELECT COUNT(*) FROM badminton_matches M WHERE (M.match_type='semi' AND M.winner_id=T.id))*2) + ((SELECT COUNT(*) FROM badminton_matches M WHERE (M.match_type='final' AND M.winner_id=T.id))*5) ) as Points FROM badminton_teams T order by (Points) DESC, lost ASC, AVG_SCORE DESC </code></pre> <p>First </p> <ul> <li><p>is it right to calculate the scoring on runtime using query or </p></li> <li><p>should I save update it every time I save a match result in the database </p></li> </ul> <p>or </p> <ul> <li>should I schedule a cron job for this purpose </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T23:56:26.140", "Id": "203061", "Score": "1", "Tags": [ "sql", "mysql" ], "Title": "Implementing an In-house Badminton Ranking System" }
203061
<p>I was working on the following interview question:</p> <blockquote> <p>Given an array of integers, return a new array such that each element at index <code>i</code> of the new array is the product of all the numbers in the original array except the one at <code>i</code>.</p> <p>For example, if our input was <code>[1, 2, 3, 4, 5]</code>, the expected output would be <code>[120, 60, 40, 30, 24]</code>. If our input was <code>[3, 2, 1]</code>, the expected output would be <code>[2, 3, 6]</code>.</p> <p><strong>Follow-up: what if you can't use division?</strong></p> </blockquote> <p>I decided to do the followup question in Haskell:</p> <pre class="lang-hs prettyprint-override"><code>{-# LANGUAGE ViewPatterns, PatternSynonyms #-} import Control.Monad (join) import Control.Arrow ((***)) import Data.Sequence (Seq) import qualified Data.Sequence as Seq import Data.Monoid (Product(..), getProduct) mapTuple = join (***) pattern Empty &lt;- (Seq.viewl -&gt; Seq.EmptyL) pattern x :&lt; xs &lt;- (Seq.viewl -&gt; x Seq.:&lt; xs) data Tree a = Leaf a | Branch a (Tree a, Tree a) label :: Tree a -&gt; a label (Leaf a) = a label (Branch a _) = a {- Create a complete binary tree, such that each subtree contains the concat of all - elements under it. -} makeTree :: Monoid a =&gt; Seq a -&gt; Tree a makeTree Empty = undefined makeTree (label :&lt; Empty) = Leaf label makeTree s = let midpoint = Seq.length s `div` 2 in let subseq = Seq.splitAt midpoint s in let subtrees = mapTuple makeTree subseq in let subtreeLabels = mapTuple label subtrees in let label = uncurry mappend subtreeLabels in Branch label subtrees {- Zippers. -} data Crumb a = LeftCrumb a (Tree a) | RightCrumb a (Tree a) type Breadcrumbs a = [Crumb a] type Zipper a = (Tree a, Breadcrumbs a) goLeft :: Zipper a -&gt; Zipper a goLeft (Branch x (l, r), bs) = (l, LeftCrumb x r:bs) goLeft (Leaf _, _) = error "Nothing to go left into" goRight :: Zipper a -&gt; Zipper a goRight (Branch x (l, r), bs) = (r, RightCrumb x l:bs) goRight (Leaf _, _) = error "Nothing to go right into" -- Concat of all elements except the one corresponding to the given crumbs concatAllExcept :: Monoid a =&gt; Breadcrumbs a -&gt; a concatAllExcept = concatAllExceptRev . reverse where concatAllExceptRev [] = mempty concatAllExceptRev ((LeftCrumb _ subtree) : xs) = concatAllExceptRev xs &lt;&gt; label subtree concatAllExceptRev ((RightCrumb _ subtree) : xs) = label subtree &lt;&gt; concatAllExceptRev xs -- Return a list of zippers pointing to the leafs of the tree dfsList :: Tree a -&gt; [Zipper a] dfsList t = reverse $ dfsListHelper (t, []) [] where dfsListHelper zipper@(Leaf _, _) accum = zipper : accum dfsListHelper zipper@(Branch _ _, _) accum = -- Since this is a Branch node, both [goLeft] and [goRight] will work. let l = goLeft zipper r = goRight zipper in dfsListHelper r (dfsListHelper l accum) {- Produces a list such that the ith element is the concat of all elements in the - original list, excluding the ith element. -} concatAllExceptEach :: Monoid a =&gt; [a] -&gt; [a] concatAllExceptEach = map (concatAllExcept . snd) . dfsList . makeTree . Seq.fromList answer :: [Integer] -&gt; [Integer] answer = map getProduct . concatAllExceptEach . fmap Product main = do print $ answer [3, 10, 33, 4, 31, 31, 1, 7] print $ answer [1, 2, 3, 4, 5] print $ concatAllExceptEach ["A", "B", "C", "D"] </code></pre> <p>Algorithm runs in Θ(n log n) which I believe is optimal. New to Haskell so all feedback welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T04:26:08.933", "Id": "391364", "Score": "1", "body": "Linear time: `answer xs = zipWith (*) (scanl (*) 1 xs) (tail $ scanr (*) 1 xs)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T18:42:02.467", ...
[ { "body": "<p>Welcome! Here are my thoughts what could be improved:</p>\n\n<ol>\n<li><p>For top-level declarations, always do include types. I'm pretty sure in a few weeks it'll be difficult to realize what</p>\n\n<pre><code>mapTuple = join (***)\n</code></pre>\n\n<p>means without knowing that it's type is</p>\...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T01:11:56.087", "Id": "203064", "Score": "3", "Tags": [ "performance", "beginner", "haskell", "tree", "interview-questions" ], "Title": "Monoidal tree interview in Haskell" }
203064
<blockquote> <p>Implement an algorithm to find the kth to last element of a singly linked list.</p> </blockquote> <p>Any comments or feedback regarding this?</p> <p>I came up with another algorithm that uses <code>HashMap</code> to find the kth to the last element in a <code>LinkedList</code>.</p> <pre><code>public static int getKthToLastElement(LinkedListNode head, int k){ LinkedListNode n = head; if(head == null || k &lt; 0) return -1; int index = 0; HashMap&lt;Integer,Integer&gt; map = new HashMap&lt;Integer, Integer&gt;(); while (n != null){ map.put(index,n.data); index++; n = n.next; } if(k &gt; map.size() -1){ return -1; } return map.get(map.size() - 1 - k); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T14:51:01.490", "Id": "391457", "Score": "0", "body": "You could do this without using any extra data structures via recursion. You should try it as an exercise. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": ...
[ { "body": "<p>Your <code>if(head == null || k &lt; 0)</code> special case is unnecessary, since it is covered by the <code>if(k &gt; map.size() -1)</code> test. You should also <strong>never</strong> omit the \"optional\" braces for a multi-line block.</p>\n\n<p>Actually, the <code>if(k &gt; map.size() -1)</co...
{ "AcceptedAnswerId": "203069", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T01:33:21.853", "Id": "203066", "Score": "3", "Tags": [ "java", "algorithm", "linked-list", "hash-map" ], "Title": "Return Kth to Last: Implement an algorithm to find the kth to last element of a singly linked list" }
203066
<p>I would like to only allow lists where the first n elements are <code>True</code> and then all of the remaining elements are <code>False</code>. I want lists like these examples to return <code>True</code>:</p> <ul> <li><code>[]</code></li> <li><code>[True]</code></li> <li><code>[False]</code></li> <li><code>[False, False]</code></li> <li><code>[True, False]</code></li> <li><code>[True, False, False]</code></li> <li><code>[True, True, True, False]</code></li> </ul> <p>And lists like these to return <code>False</code>:</p> <ul> <li><code>[False, True]</code></li> <li><code>[True, False, True]</code></li> </ul> <p>That is, any list that can we written as <code>[True] * n + [False] * m</code> for <code>n</code>, <code>m</code> integers in the interval [0, infty).</p> <p>I am currently using a function called <code>check_true_then_false</code>, but I feel like there is probably a neater way of doing this. The code doesn't need to be fast, as this will only be run once (not inside a loop) and the lists will short (single digit lengths).</p> <pre><code>def check_true_then_false(x): n_trues = sum(x) should_be_true = x[:n_trues] # get the first n items should_be_false = x[n_trues:len(x)] # get the remaining items # return True only if all of the first n elements are True and the remaining # elements are all False return all(should_be_true) and not any(should_be_false) </code></pre> <p>Testing shows that it produces the correct output:</p> <pre><code>test_cases = [[True], [False], [True, False], [True, False, False], [True, True, True, False], [False, True], [True, False, True]] print([check_true_then_false(test_case) for test_case in test_cases]) # expected output: [True, True, True, True, True, False, False] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T03:41:36.143", "Id": "391359", "Score": "0", "body": "Sorry it didn't work out. Try again on SO. I have a concrete answer I'd like to post that I think would work for this site, but would also work for SO." }, { "ContentLice...
[ { "body": "<p>Your code works correctly under the assumption that the given list\ncontains only <code>True</code> or <code>False</code> elements. For other lists it can return\n“false positives”</p>\n\n<pre><code>&gt;&gt;&gt; check_true_then_false([1, 1, 0])\nTrue\n</code></pre>\n\n<p>or abort with a runtime er...
{ "AcceptedAnswerId": "203083", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T03:26:55.370", "Id": "203068", "Score": "8", "Tags": [ "python", "python-3.x" ], "Title": "Function to check that a Python list contains only True and then only False" }
203068
<p>I have written a simple <a href="https://en.wikipedia.org/wiki/Caesar_cipher" rel="nofollow noreferrer">Caesar Cipher</a> in Python in my efforts to learn a language that isn't C. It works much like any other Caesar implementation and takes various command line arguments to specify options such as the spacing of the output, whether to encrypt or decrypt the input, and whether or not to try and bruteforce the cipher.</p> <p>This is my first ever Python program so I'm primarily looking to learn some best practices for the language as well as remove any inefficiencies or redundancies in my code.</p> <p>Thanks!</p> <pre><code>import argparse import re def caesar(string, shift): output = '' for char in string: if char.isspace(): output += ' ' else: output += chr(((ord(char) - 65 + shift) % 26) + 65) return output def main(): parser = argparse.ArgumentParser(description = "Encrypt or decrpyt a string using the Caesar Cipher") parser.add_argument("--bruteforce", "--brute", "-b", help = "bruteforce mode", action = "store_true") parser.add_argument("--encrypt", "--enc", "-e", help = "encryption mode (default)", action = "store_true") parser.add_argument("--decrpyt", "--dec", "-d", help = "decryption mode", action = "store_true") parser.add_argument("--no-spacing", "--no-space", "-n", help = "no spacing in output (default)", action = "store_true") parser.add_argument("--preserve-spacing", "--preserve", "-p", help = "use same spacing as original string", action = "store_true") parser.add_argument("--shift", "-s", help = "value for the Caesar shift", type = int, choices = range(1, 26)) parser.add_argument("--spacing", "-x", help = "specify the spacing in output", type = int) args = parser.parse_args() if args.bruteforce: bruteforce = True else: bruteforce = False shift = args.shift if args.decrpyt: shift = -shift if args.preserve_spacing: regex = re.compile('[^A-Z\s]') else: regex = re.compile('[^A-Z]') string = regex.sub('', input().upper()) if args.spacing: string = ' '.join([string[i:i + args.spacing] for i in range(0, len(string), args.spacing)]) if bruteforce: for shift in range(1, 26): print("%d: %s" %(shift, caesar(string, -shift))) else: print(caesar(string, shift)) if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<h1>The Caesar function</h1>\n\n<p>First the parameter <code>string</code> should be renamed as it has the same name as the standard module <a href=\"https://docs.python.org/3.7/library/string.html\" rel=\"nofollow noreferrer\"><code>string</code></a>. Sure you don't use it, but it is a bad habit to ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T03:39:15.137", "Id": "203070", "Score": "2", "Tags": [ "python", "python-3.x", "caesar-cipher" ], "Title": "Caesar Cipher written in Python" }
203070
<p>Given a directed graph <strong>G</strong> of 20+ million edges and approximately 2 million unique nodes, can this function/process be made faster on a dataset of 40k edges? </p> <p>The current speed is at ~1.8 seconds per edge. </p> <pre><code>import pandas as pd import networkx as nx # main feature calculator def jacard_inbound(u,v): preds = G.predecessors(v) result = [jacard_coef(u,x) for x in preds] return sum(result), max(result), sum(result)/len(result) # jacquard's coefficient &amp; helper functions def jacard_coef(u,v): return common_friends(u,v)/total_friends(u,v) def total_friends(u,v): return len(set(Gamma(u)).union(Gamma(v))) def common_friends(u,v): return len(set(Gamma(u)).intersection(Gamma(v))) # to cache calculated results gamma_dict = dict() def Gamma(u): s = gamma_dict.get(u) if s is None: s = set(G.successors(u)).union(G.predecessors(u)) gamma_dict[u]=s return s </code></pre> <p>Running example: </p> <pre><code># sample graph G = nx.DiGraph() G.add_edges_from([(1,2), (1,3), (2,3), (3,4), (3,5), (7,1), (5,6), (8,2), (9,0)]) # sample edges dataset = pd.DataFrame(columns = ['source','target']) dataset['target'] = [3, 6, 2, 3] dataset['source'] = [2, 1, 8, 1] t = time.time() dataset['jacard_inbound'] = dataset[['source','target']].apply(lambda x: jacard_inbound(x['source'],x['target']), axis=1) print(time.time() - t) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T08:10:06.413", "Id": "391383", "Score": "0", "body": "Can you explain what the program is supposed to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T09:39:58.470", "Id": "391396", "Score"...
[ { "body": "<ol>\n<li><p>\"Jaccard coefficient\", not \"Jacard\" or \"Jacquard\": it's named after <a href=\"https://en.wikipedia.org/wiki/Paul_Jaccard\" rel=\"nofollow noreferrer\">Paul Jaccard</a>.</p></li>\n<li><p>There are no docstrings. What do these functions do? What do they return?</p></li>\n<li><p>The r...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T04:11:45.220", "Id": "203073", "Score": "2", "Tags": [ "python", "graph", "pandas" ], "Title": "Implementing a faster inbound neighbour similarity in Networkx" }
203073
<p>This script is run directly after a fresh install of Debian, to do:</p> <ul> <li>sets up syntax highlighting in <code>nano</code>,</li> <li>sets up <code>iptables</code>,</li> <li>sets up ssh,</li> <li>sets up custom <code>bashrc</code> files and <code>ls</code> colors,</li> <li>creates users on the system if needed,</li> <li>checks if user has a password set and sets it if not,</li> <li>installs <code>non-free firmware</code> and sets up <code>apt</code> with <code>virtualbox</code> deb file and <code>multimedia</code> deb.</li> </ul> <p>There was mention of <code>debconf</code> but I've never heard about that.</p> <p>Would you use <code>sudo</code> as I did to access other users on the system?</p> <p>Could you add some features to the program that are good practice for setting up new installs?</p> <p>Can you see a way for me to use <code>getops</code> to strengthen the program?</p> <p>Is there anything in the program that I don't need?</p> <pre><code>#!/bin/bash -x SCRIPTNAME=`basename "$0"` if [ "$#" -eq 0 ] then echo "No arguments supplied" echo "Usage: $SCRIPTNAME user1name user2name\(optional\) user3name\(optional\)" sleep 10 exit 27 fi sleep 5 echo "Setting up server.........." sleep 10 DIRBASHRCROOT="$HOME"/.bashrcroot DIRBASHRC="$HOME"/.bashrc #CURRENTDIR="./" BASHRC=.bashrc NANORC=.nanorc BASHRCROOT=.bashrcroot ROOT=root USER1="$1" USER2="$2" USER3="$3" USER_PROGRAMMER="" SOURCE=sources.list echo "Please select/provide the port-number for ssh in iptables and sshd_config:" read port PORT=$port ################# Make my variable global for all ########################3↓ echo "export CURRENTDIR=\"/tmp/svaka\"" &gt;&gt; /root/.bashrc touch /etc/profile.d/bashProgrammer.sh echo "export CURRENTDIR=\"/tmp/svaka\"" &gt;&gt; /etc/profile.d/bashProgrammer.sh . /root/.bashrc . /etc/profile . /etc/profile.d/bashProgrammer.sh ################ Users and access settings ##################### ############################### make all files writable, executable and readable in the working directory######### chmod 777 $CURRENTDIR/* if [ ! "$?" = 0 ] then echo "Couldnt give write, read and execute permission to config files in svaka, exiting now........" exit 127 fi ######################################################### checkIfUser() { for name in "$@" do if id -u "$name" #&gt;/dev/null 2&gt;&amp;1 then echo "User: $name exists....setting up now\!" sleep 5 else echo "User: "$name" does not exists....creating now\!" useradd -m -s /bin/bash "$name" #&gt;/dev/null 2&gt;&amp;1 sleep 5 fi done } checkIfUser $1 $2 $3 ################33 user passwords userPass() { for i in "$@" do if [ "$i" = root ] then continue fi if [[ $(passwd --status "$i" | awk '{print $2}') = NP ]] then echo "$i doesn't have a password." echo "Changing password for $i:" echo $i:$i"YOURSTRONGPASSWORDHERE12345Áá" | chpasswd if [ "$?" = 0 ] then echo "Password for user $i changed successfully" sleep 5 fi fi done } userPass $1 $2 $3 ################################################ setting up iptables ####################3 cat &lt;&lt; EOT &gt;&gt; /etc/iptables.test.rules *filter IPTABLES CODE HERE COMMIT EOT sleep 5 iptables-restore &lt; /etc/iptables.test.rules sleep 5 iptables-save &gt; /etc/iptables.up.rules sleep 3 printf "#!/bin/bash\n/sbin/iptables-restore &lt; /etc/iptables.up.rules" &gt; /etc/network/if-pre-up.d/iptables chmod +x /etc/network/if-pre-up.d/iptables sleep 6 ###################################################33 sshd_config cp -f "$CURRENTDIR/sshd_config" /etc/ssh/sshd_config sed -i "s/Port 34504/Port $PORT/g" /etc/ssh/sshd_config chmod 644 /etc/ssh/sshd_config /etc/init.d/ssh restart #################################################3333 Remove or comment out DVD/cd line from sources.list sed -i '/deb cdrom:\[Debian GNU\/Linux/s/^/#/' /etc/apt/sources.list ####################################################33 update system apt update &amp;&amp; apt upgrade -y ##########################################3 Disable login www ######### passwd -l www-data ############################################################### ############################# check if programs installed and/or install if [ ! -x /usr/bin/git ] || [ ! -x /usr/bin/wget ] || [ ! -x /usr/bin/curl ] || [ ! -x /usr/bin/gcc ] || [ ! -x /usr/bin/make ] then echo "Some tools with which to work with data not found installing now......................" apt install -y git wget curl gcc make fi #####################################################3 update sources.list cp -f $CURRENTDIR/$SOURCE /etc/apt/sources.list chmod 644 /etc/apt/sources.list wget http://www.deb-multimedia.org/pool/main/d/deb-multimedia-keyring/deb-multimedia-keyring_2016.8.1_all.deb dpkg -i deb-multimedia-keyring_2016.8.1_all.deb wget -q https://www.virtualbox.org/download/oracle_vbox_2016.asc -O- | sudo apt-key add - apt update &amp;&amp; apt upgrade -y apt install -y vlc vlc-data browser-plugin-vlc mplayer youtube-dl libdvdcss2 libdvdnav4 libdvdread4 smplayer mencoder sleep 5 apt update &amp;&amp; apt upgrade -y sleep 5 #################################### firmware apt install -y firmware-linux-nonfree firmware-linux sleep 5 ################ NANO SYNTAX-HIGHLIGHTING #####################3 if [ ! -d "$CURRENTDIR/nanorc" ] then if [ "$UID" != 0 ] then sudo -u "$ROOT" bash &lt;&lt;'EOF' sleep 5 git clone https://github.com/nanorc/nanorc.git sleep 5 cd nanorc make install-global sleep 5 cp -f "$CURRENTDIR/.nanorc" /etc/nanorc chown root:root /etc/nanorc chmod 644 /etc/nanorc if [ "$?" = 0 ] then echo "Implementing a custom nanorc file succeeded\!" else echo "Nano setup DID NOT SUCCEED\!" fi EOF else echo "Doing user: $USER....please, wait\!" git clone https://github.com/nanorc/nanorc.git sleep 5 cd nanorc sleep 5 make install-global sleep 5 cp -f "$CURRENTDIR/$NANORC" /etc/nanorc chown root:root /etc/nanorc chmod 644 /etc/nanorc if [ "$?" = 0 ] then echo "Implementing a custom nanorc file succeeded\!" else echo "Nano setup DID NOT SUCCEED\!" fi fi fi echo "Finished setting up nano\!" ################ LS_COLORS SETTINGS ############################# if [ "$UID" != 0 ] then echo "This program should be run as root, exiting\! now....." exit 1 # sudo -i -u "$ROOT" bash &lt;&lt;'EOF' # BASHRCROOT=.bashrcroot # cp "$CURRENTDIR/$BASHRCROOT" "$HOME"/.bashrc # wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors # echo 'eval $(dircolors -b $HOME/.dircolors)' &gt;&gt; "$HOME"/.bashrc # . "$HOME"/.bashrc #EOF else cp -f "$CURRENTDIR/$BASHRCROOT" "$HOME"/.bashrc chown root:root "$HOME"/.bashrc chmod 644 "$HOME"/.bashrc sleep 5 wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors sleep 5 echo 'eval $(dircolors -b $HOME/.dircolors)' &gt;&gt; "$HOME"/.bashrc sleep 5 . "$HOME"/.bashrc fi for user in "$@" do if [ "$user" = root ] then continue fi sudo -i -u "$user" user="$user" bash &lt;&lt;'EOF' sleep 5 cp -f $CURRENTDIR/.bashrc "$HOME"/.bashrc chown $user:$user "$HOME"/.bashrc sleep 5 chmod 644 "$HOME"/.bashrc sleep 5 wget https://raw.github.com/trapd00r/LS_COLORS/master/LS_COLORS -O "$HOME"/.dircolors sleep 5 echo 'eval $(dircolors -b $HOME/.dircolors)' &gt;&gt; "$HOME"/.bashrc . "$HOME"/.bashrc EOF done echo "Finished setting up your system\!" echo rm -rf /tmp/svaka </code></pre> <p>Here's a question about this code on unix/linux <a href="https://unix.stackexchange.com/questions/466312/getting-access-to-a-variable-inside-a-sudo-clause-in-a-script-with-eof/466317#466317">stackexchange</a></p>
[]
[ { "body": "<blockquote>\n <p>Welcome to Code Review!</p>\n</blockquote>\n\n<p>It is a good practice if you start verifying your shell scripts <a href=\"https://github.com/koalaman/shellcheck\" rel=\"nofollow noreferrer\">against shellcheck</a>. Currently, it lists quite a few issues:</p>\n\n<pre><code>Line 3:\...
{ "AcceptedAnswerId": "203516", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T07:21:11.707", "Id": "203077", "Score": "5", "Tags": [ "bash", "linux", "shell", "installer" ], "Title": "Bash script to setup new Debian installs" }
203077
<p>I'm struggling if this is the correct way to implement an MVC-like pattern for small websites. I have separate <em>controllers</em> and <em>models</em>, my main concern is the <em>view</em> part, did I understand it correctly?</p> <p><strong>Folders:</strong></p> <pre><code>app/ - controllers/ - homepage.php - models/ - homepage.php - template.php </code></pre> <p><strong>App/Template.php</strong></p> <pre><code>namespace App; class Template { public static $templateFolder = __DIR__ . '/../html/templates/'; public static $defaultParts = [ 'header' =&gt; 'parts/header', 'footer' =&gt; 'parts/footer' ]; public static $headerDefaults = [ 'meta_title' =&gt; '-' ]; public static function render( $templateName, $data = [] ) { $content = !empty( $data['content'] ) ? $data['content'] : []; $objects = !empty( $data['objects'] ) ? $data['objects'] : []; $pageName = !empty( $data['name'] ) ? $data['name'] : null; $header = self::show($parts['header'], $pageName, !empty( $content['header'] ) ? $content['header'] : self::$headerDefaults); $footer = self::show($parts['footer'], $pageName, !empty( $content['footer'] ) ? $content['footer'] : []); $body = self::show($templateName, $pageName, !empty( $content['body'] ) ? $content['body'] : [], $objects); return $header.$body.$footer; } public static function show( $templateName, $pageName, $data = [], $objects = [] ) { if ( file_exists( self::$templateFolder . $templateName.'.tpl' ) ) { if ( !empty($objects) ) extract( $objects, EXTR_SKIP ); ob_start(); include self::$templateFolder . $templateName . '.tpl'; $content = ob_get_contents(); ob_end_clean(); return $content; } return self::notFound(); } public static function notFound( $full = false ) { if ( $full ) return self::render('not_found', [ 'content' =&gt; [ 'header' =&gt; [ 'meta_title' =&gt; 'Страница не найдена' ] ] ]); ob_start(); include self::$templateFolder . 'not_found.tpl'; $content = ob_get_contents(); ob_end_clean(); return $content; } } </code></pre> <p><strong>App/Controllers/Homepage.php</strong></p> <pre><code>namespace Controllers; class Homepage { public $templates = [ 'default' =&gt; 'public/homepage' ]; public function response($data) { if (!empty($data['method']) &amp;&amp; $data['method'] == 'GET') { return $this-&gt;getResponse($data); } else { return $this-&gt;postResponse($data); } return $data; } public function getResponse($data) { return \App\Template::render($this-&gt;templates['default'], [ 'name' =&gt; 'homepage', 'content' =&gt; [ 'body' =&gt; \Models\Hompage::getInstance()-&gt;mainpage(), 'footer' =&gt; [], 'header' =&gt; [ 'page_class' =&gt; 'main-page', 'styles' =&gt; ['/css/mainpage.css'] ], ] ]); } public function postResponse($data) { if (!empty($data['name'])) { $name = $data['name']; if (method_exists($this, $name)) return $this-&gt;$name($data); } return 'undefined command'; } } </code></pre> <p><strong>App/Models/Homepage.php</strong></p> <pre><code>namespace Models; class Homepage extends \App\PDOWrap { static private $instance = null; public function __construct() { parent::__construct(); } static public function getInstance() { if ( self::$instance == null ) self::$instance = new self(); return self::$instance; } public function all() { $this-&gt;query('SELECT * FROM table'); return $this-&gt;resultset(); } public function mainpage() { $this-&gt;query('SELECT * FROM table INNER JOIN tabl2 ...'); return $this-&gt;resultset(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T23:01:45.443", "Id": "391530", "Score": "0", "body": "Welcome to Code Review! Your code looks good, I added bit of formatting - in general please try and give each post a descriptive title of _what the code does_, not particularly t...
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T07:35:39.577", "Id": "203078", "Score": "1", "Tags": [ "php", "mvc" ], "Title": "Small website with MVC" }
203078
<p>I have made this custom image carousel, using HTML5, jQuery and CSS. My aim was to make it really <em>lightweight</em> but with (just) enough features: "bullets", auto-advance, responsiveness.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var $elm = $('.slider'), $slidesContainer = $elm.find('.slides-container'), slides = $slidesContainer.children('a'), slidesCount = slides.length, slideHeight = $(slides[0]).find('img').outerHeight(false), animationspeed = 1500, animationInterval = 7000; var shuffle = function(slides) { var j, x, i; for (i = slides.length - 1; i &gt; 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = slides[i]; slides[i] = slides[j]; slides[j] = x; } return slides; } shuffle(slides); // Set (initial) z-index for each slide var setZindex = function() { for (var i = 0; i &lt; slidesCount; i++) { $(slides[i]).css('z-index', slidesCount - i); } }; setZindex(); var setActiveSlide = function() { $(slides).removeClass('active'); $(slides[activeIdx]).addClass('active'); }; var advanceFunc = function() { if ($('.slider-nav li.activeSlide').index() + 1 != $('.slider-nav li').length) { $('.slider-nav li.activeSlide').next().find('a').trigger('click'); } else { $('.slider-nav li:first').find('a').trigger('click'); } } var autoAdvance = setInterval(advanceFunc, animationInterval); //Set slide height $(slides).css('height', slideHeight); // Append bullets if (slidesCount &gt; 1) { /* Prepend the slider navigation to the slider if there are at least 2 slides */ $elm.prepend('&lt;ul class="slider-nav"&gt;&lt;/ul&gt;'); // make a bullet for each slide for (var i = 0; i &lt; slidesCount; i++) { var bullets = '&lt;li&gt;&lt;a href="#"&gt;' + i + '&lt;/a&gt;&lt;/li&gt;'; if (i == 0) { // active bullet var bullets = '&lt;li class="activeSlide"&gt;&lt;a href="#"&gt;' + i + '&lt;/a&gt;&lt;/li&gt;'; // active slide $(slides[0]).addClass('active'); } $('.slider-nav').append(bullets); } }; var Queue = function() { var lastPromise = null; this.add = function(callable) { var methodDeferred = $.Deferred(); var queueDeferred = this.setup(); // execute next queue method queueDeferred.done(function() { // call actual method and wrap output in deferred callable().then(methodDeferred.resolve) }); lastPromise = methodDeferred.promise(); }; this.setup = function() { var queueDeferred = $.Deferred(); // when the previous method returns, resolve this one $.when(lastPromise).always(function() { queueDeferred.resolve(); }); return queueDeferred.promise(); } }; var queue = new Queue(); var slideUpDown = function(previousIdx, activeIdx) { queue.add(function() { return new Promise(function(resolve, reject) { // set top property for all the slides $(slides).not(slides[previousIdx]).css('top', slideHeight); // then animate to the next slide $(slides[activeIdx]).animate({ 'top': 0 }, animationspeed); $(slides[previousIdx]).animate({ 'top': "-100%" }, animationspeed, 'swing', resolve); }) }) }; var previousIdx = '0' // First slide $('.slider-nav a').on('click', function(event) { event.preventDefault(); activeIdx = $(this).text(); // Disable clicling on an active item if ($(slides[activeIdx]).hasClass("active")) { return false; } $('.slider-nav a').closest('li').removeClass('activeSlide'); $(this).closest('li').addClass('activeSlide'); // Reset autoadvance if user clicks bullet if (event.originalEvent !== undefined) { clearInterval(autoAdvance); autoAdvance = setInterval(advanceFunc, animationInterval); } setActiveSlide(); slideUpDown(previousIdx, activeIdx); previousIdx = activeIdx });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body * { box-sizing: border-box; } .container { max-width: 1200px; margin: 0 auto; } .slider { width: 100%; height: 300px; position: relative; overflow: hidden; } .slider .slider-nav { text-align: center; position: absolute; padding: 0; margin: 0; left: 10px; right: 10px; bottom: 2px; z-index: 10; } .slider .slider-nav li { display: inline-block; width: 20px; height: 4px; margin: 0 1px; text-indent: -9999px; overflow: hidden; background-color: rgba(255, 255, 255, .5); } .slider .slider-nav a { display: block; height: 4px; line-height: 4px; } .slider .slider-nav li.activeSlide { background: #fff; } .slider .slider-nav li.activeSlide a { display: none; } .slider .slider-container { width: 100%; text-align: center; } .slider .slides-container a { height: 300px; display: block; position: absolute; top: 0; left: 0; right: 0; } .slider .slides-container img { transform: translateX(-50%); margin-left: 50%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;div class="slider"&gt; &lt;div class="slides-container"&gt; &lt;a href="#"&gt; &lt;img src="https://i.stack.imgur.com/P1Di6.jpg"&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src="https://i.stack.imgur.com/nR2uJ.jpg"&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src="https://i.stack.imgur.com/Zynhv.jpg"&gt; &lt;/a&gt; &lt;a href="#"&gt; &lt;img src="https://i.stack.imgur.com/A9BgN.jpg"&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>It works fine but I am certain it can be optimized: the same result can be achieved with <em>less code</em>. I am not thinking of a complete rewrite, but of ditching redundant and useless code.</p> <p>The carousel's current architecture requires the slides to have <em>z-indexes</em> which I wish I could get rid of. What would be a good <em>alternative</em> to that?</p> <p>See a jsFiddle <strong><a href="https://jsfiddle.net/Ajax30/vk0cLw6b/embedded/result/" rel="nofollow noreferrer">HERE</a></strong>.</p> <p>Please help me make it better. Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T20:48:22.287", "Id": "391646", "Score": "1", "body": "Is the queue with promises supposed to prevent the slides from moving too quickly or some other purpose?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018...
[ { "body": "<h2>General Feedback</h2>\n\n<p>The carousel appears to work acceptably. The code is a bit scattered. Consider the variable <code>activeIdx</code>. It appears to be set in the click handler and referenced in the function <code>setActiveSlide()</code> as a global variable - not as a parameter, but in ...
{ "AcceptedAnswerId": "203885", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T09:04:07.880", "Id": "203084", "Score": "3", "Tags": [ "javascript", "jquery", "css", "image", "html5" ], "Title": "jQuery image carousel" }
203084
<p>While learning Rust for the past couple of weeks, I set out to use the type-system to build a static State Machine implementation in Rust.</p> <p>The goals:</p> <ul> <li>program in idiomatic Rust</li> <li>no runtime overhead</li> <li>use traits for flexibility</li> <li>optionally use macro's for ease of use</li> <li>keep it simple</li> </ul> <p>I believe I managed to achieve all, except for maybe the third point. The end-result is a macro that generates a new struct for each state machine, so there's no overarching trait to easily generate your own state machine without the included macro.</p> <p>I'm curious:</p> <ul> <li>If I approached this in the right way</li> <li>What I could have done differently</li> <li>If I wanted to rely more heavily on the trait system (while keeping the zero-runtime cost) how I would go about doing that</li> </ul> <p>My next extension to this would be to implement some kind of enum-based type on top of this, to make it easy to match against the current state, as right now that's not yet possible.</p> <p>Code can be viewed <a href="https://github.com/rusty-rockets/sm/blob/e9ef152c8d03a48ef5c31a30bcb4f8e364b6ad37/src/lib.rs#L495-L607" rel="nofollow noreferrer">on GitHub</a>, or below:</p> <pre class="lang-rust prettyprint-override"><code>#[macro_export] macro_rules! sm { ( $($name:ident { States { $($state:ident),+ $(,)* } $($event:ident { $($($from:ident),+ =&gt; $to:ident)+ })* })+ ) =&gt; { use $crate::{AsEnum, Machine as M, Transition}; $( #[allow(non_snake_case)] pub mod $name { use $crate::{AsEnum, Event, Machine as M, State, Transition}; #[derive(PartialEq, Eq, Debug)] pub struct Machine&lt;S: State&gt;(pub S); impl&lt;S&gt; M for Machine&lt;S&gt; where S: State { type State = S; fn state(&amp;self) -&gt; S { self.0.clone() } } impl&lt;S&gt; Machine&lt;S&gt; where S: State { pub fn new(state: S) -&gt; Self { Machine(state) } } $( #[derive(Copy, Clone, Eq, Debug)] pub struct $state; impl State for $state {} impl PartialEq&lt;$state&gt; for $state { fn eq(&amp;self, _: &amp; $state) -&gt; bool { true } } )* #[derive(Debug)] pub enum States { $($state(Machine&lt;$state&gt;)),* } $( impl AsEnum&lt;$state&gt; for Machine&lt;$state&gt; { type Enum = States; fn as_enum(self) -&gt; Self::Enum { States::$state(self) } } )* sm!{@recurse ($($state),*), ()} $( #[derive(PartialEq, Eq, Debug)] pub struct $event; impl Event for $event {} $( $( impl Transition&lt;Machine&lt;$to&gt;, $event&gt; for Machine&lt;$from&gt; { fn transition(self, _: $event) -&gt; Machine&lt;$to&gt; { Machine::new($to) } } )* )* )* } )* }; (@recurse ($state:ident, $($other:ident),+), ($($old:ident),*)) =&gt; { $( impl PartialEq&lt;$other&gt; for $state { fn eq(&amp;self, _: &amp; $other) -&gt; bool { false } } )* $( impl PartialEq&lt;$old&gt; for $state { fn eq(&amp;self, _: &amp; $old) -&gt; bool { false } } )* sm!{@recurse ($($other),*), ($($old,)* $state)} }; (@recurse ($state:ident), ($($old:ident),*)) =&gt; { $( impl PartialEq&lt;$old&gt; for $state { fn eq(&amp;self, _: &amp; $old) -&gt; bool { false } } )* }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T13:03:08.627", "Id": "391437", "Score": "0", "body": "I just realised that while all my tests are green, that's because they only test the \"happy path\". You can't actually do any conditional expression on the current `state`, sinc...
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T09:57:51.950", "Id": "203088", "Score": "3", "Tags": [ "beginner", "rust", "state-machine" ], "Title": "static macro-based State Machine implementation" }
203088
<p>I have made a small application that displays a <em>posts</em> JSON in the form of cards, with the help of AngularJS and Twitter Bootstrap 4.</p> <p>The application has an interface for <em>pagination</em> and there are about 100 posts displayed on each page.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var root = 'https://jsonplaceholder.typicode.com'; // Create an Angular module named "postsApp" var app = angular.module("postsApp", []); // Create controller for the "postsApp" module app.controller("postsCtrl", ["$scope", "$http", "$filter", function($scope, $http, $filter) { var url = root + "/posts"; $scope.postList = []; $scope.search = ""; $scope.filterList = function() { var oldList = $scope.postList || []; $scope.postList = $filter('filter')($scope.posts, $scope.search); if (oldList.length != $scope.postList.length) { $scope.pageNum = 1; $scope.startAt = 0; }; $scope.itemsCount = $scope.postList.length; $scope.pageMax = Math.ceil($scope.itemsCount / $scope.perPage); }; $http.get(url) .then(function(data) { // posts arary $scope.posts = data.data; $scope.filterList(); // Paginate $scope.pageNum = 1; $scope.perPage = 24; $scope.startAt = 0; $scope.filterList(); $scope.currentPage = function(index) { $scope.pageNum = index + 1; $scope.startAt = index * $scope.perPage; }; $scope.prevPage = function() { if ($scope.pageNum &gt; 1) { $scope.pageNum = $scope.pageNum - 1; $scope.startAt = ($scope.pageNum - 1) * $scope.perPage; } }; $scope.nextPage = function() { if ($scope.pageNum &lt; $scope.pageMax) { $scope.pageNum = $scope.pageNum + 1; $scope.startAt = ($scope.pageNum - 1) * $scope.perPage; } }; }); }]);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.posts-grid { margin-top: 25px; display: flex; flex-wrap: wrap; } .posts-grid&gt;[class*='col-'] { display: flex; flex-direction: column; margin-bottom: 25px; } .posts-grid .post { background: #fff; border-top: 1px solid #d5d5d5; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.11); } .posts-grid .text { padding: 8px; } .posts-grid .card-title { font-size: 1.25rem; margin-bottom: 8px; text-transform: capitalize; } .posts-grid .read-more { padding: 0 8px 8px 8px; } .posts-grid .text-muted { margin-bottom: 8px; } .posts-grid .thumbnail img { display: block; width: 100%; height: auto; } .posts-grid p { text-align: justify; } .posts-grid .post { flex-grow: 1; display: flex; flex-direction: column; } .posts-grid .read-more { margin-top: auto; } .pagination&gt;li&gt;a, .pagination&gt;li&gt;a:hover, .pagination&gt;li&gt;span { color: #585858; line-height: 1; padding: 6px 12px; text-decoration: none; } .pagination&gt;.active&gt;a, .pagination&gt;.active&gt;span, .pagination&gt;.active&gt;a:hover, .pagination&gt;.active&gt;span:hover, .pagination&gt;.active&gt;a:focus, .pagination&gt;.active&gt;span:focus { background-color: #007bff; border-color: #2b7c2b; color: #fff; } @media (max-width: 767px) { .container { max-width: 100%; } } @media (max-width: 575px) { .container { max-width: 100%; padding-left: 0; padding-right: 0; } .posts-grid&gt;[class*='col-'] { padding-left: 5px; padding-right: 5px; } }</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;link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.js"&gt;&lt;/script&gt; &lt;nav class="navbar navbar-expand-md bg-dark navbar-dark sticky-top"&gt; &lt;!-- Brand --&gt; &lt;a class="navbar-brand" href="#"&gt;My Blog&lt;/a&gt; &lt;!-- Toggler/collapsibe Button --&gt; &lt;button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"&gt; &lt;span class="navbar-toggler-icon"&gt;&lt;/span&gt; &lt;/button&gt; &lt;!-- Navbar links --&gt; &lt;div class="collapse navbar-collapse" id="collapsibleNavbar"&gt; &lt;ul class="navbar-nav ml-auto"&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link active" href="#"&gt;Contacts&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link" href="#"&gt;About us&lt;/a&gt; &lt;/li&gt; &lt;li class="nav-item"&gt; &lt;a class="nav-link btn btn-outline-primary" href="#"&gt;Login&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/nav&gt; &lt;div data-ng-app="postsApp"&gt; &lt;div class="container" data-ng-controller="postsCtrl"&gt; &lt;div class="row"&gt; &lt;div class="col-sm-9 mx-auto"&gt; &lt;div class="form-group search-box mt-3 px-3"&gt; &lt;input type="text" class="form-control" id="search" placeholder="Search post" data-ng-model="search" ng-change="filterList()"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="posts-grid" ng-if="postList.length &gt; 0"&gt; &lt;div class="col-xs-12 col-sm-6 col-lg-4 col-xl-3" data-ng-repeat="post in postList | limitTo : perPage : startAt"&gt; &lt;div class="post"&gt; &lt;div class="thumbnail"&gt; &lt;img src="//lorempixel.com/450/300" /&gt; &lt;/div&gt; &lt;div class="text"&gt; &lt;h3 class="card-title"&gt;{{post.title}}&lt;/h3&gt; &lt;p class="text-muted"&gt;{{post.body}}&lt;/p&gt; &lt;/div&gt; &lt;div class="read-more"&gt; &lt;a class="btn btn-block btn-sm btn-primary" href="#"&gt;Read more&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;p ng-if="postList.length &lt;= 0" class="text-center"&gt;There are no posts&lt;/p&gt; &lt;div ng-if="pageMax &gt; 1"&gt; &lt;ul class="pagination pagination-sm justify-content-center"&gt; &lt;li class="page-item"&gt;&lt;a href="#" ng-click="prevPage()"&gt;&lt;i class="fa fa-chevron-left"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;li ng-repeat="n in [].constructor(pageMax) track by $index" ng-class="{true: 'active'}[$index == pageNum - 1]"&gt; &lt;a href="#" ng-click="currentPage($index)"&gt;{{$index+1}}&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#" ng-click="nextPage()"&gt;&lt;i class="fa fa-chevron-right"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function($) { $('.pagination &gt; li &gt; a').click(function() { $("html, body").animate({ scrollTop: 0 }, 500); return false; }); }); &lt;/script&gt;</code></pre> </div> </div> </p> <p>A few questions ware born in my mind recently and I did not find the answer, hence my topic here:</p> <ol> <li>What if there ware 10 or 100 times as many posts, would the application have a performance problem (e.g. with page load)?</li> <li>Is there a better way to paginate the application; one that would load as many items from <em>posts.json</em> as there are displayed on <em>one page</em> (24 items), instead of the entire JSON file?</li> <li>How would you <strong>optimize</strong> this application, on the front end?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-12-10T21:31:53.577", "Id": "404694", "Score": "0", "body": "Note: this post appears to be [cross-posted on SO](https://stackoverflow.com/q/51566197/1575353) and also has an accepted answer there" }, { "ContentLicense": "CC BY-SA 4...
[ { "body": "<blockquote>\n <ol>\n <li>What if there ware 10 or 100 times as many posts, would the application have a performance (page load) problem?</li>\n </ol>\n</blockquote>\n\n<p>Try it with <a href=\"http://phpfiddle.org/main/code/2dmb-2574\" rel=\"nofollow noreferrer\">10 times as many posts</a>. I kno...
{ "AcceptedAnswerId": "209227", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T10:08:26.330", "Id": "203089", "Score": "2", "Tags": [ "javascript", "performance", "angular.js", "ajax", "pagination" ], "Title": "Paginated AngularJS posts application" }
203089
<p>For some time now I have maintained (and written) <a href="https://github.com/RobThree/IdGen" rel="noreferrer">IdGen</a>. It's inspired by <a href="https://github.com/twitter/snowflake" rel="noreferrer">Twitter's Snowflake project</a> and it's intended use is to generate (roughly) incremental id's in a distributed scenario with multiple machines/processes/threads guaranteeing unique id's (no collisions). The way IdGen works is described in the <a href="https://github.com/RobThree/IdGen/blob/master/README.md" rel="noreferrer">README</a>. But the algorithm, in general, works like this: it generates 64 bit id's (63 actually, to avoid the MSB and sorting issues on some systems). It does this by "partitioning" the 64 bits into a timestamp part, a "generator id" part and a sequence part.</p> <p>A "generator" can be a machine or thread or process for example. The sequence is incremented as long as the timestamp part is equal to the previous timestamp of the last generated ID. Whenever the timestamp increments the sequence is reset to 0. My specific implementation allows the user of the library to configure how much bits he/she wants to use for each of the 3 parts that make up an id but that is not relevant for my questions.</p> <p>My question today is about the <a href="https://github.com/RobThree/IdGen/blob/306ba56bd12981313747c8009776582a8f6b65db/IdGen/IdGenerator.cs#L180" rel="noreferrer"><code>CreateId()</code></a> method.</p> <pre><code>/// &lt;summary&gt; /// Creates a new Id. /// &lt;/summary&gt; /// &lt;returns&gt;Returns an Id based on the &lt;see cref="IdGenerator"/&gt;'s epoch, generatorid and sequence.&lt;/returns&gt; /// &lt;exception cref="InvalidSystemClockException"&gt;Thrown when clock going backwards is detected.&lt;/exception&gt; /// &lt;exception cref="SequenceOverflowException"&gt;Thrown when sequence overflows.&lt;/exception&gt; public long CreateId() { lock (_genlock) { // Determine "timeslot" and make sure it's &gt;= last timeslot (if any) var ticks = GetTicks(); var timestamp = ticks &amp; MASK_TIME; if (timestamp &lt; _lastgen || ticks &lt; 0) throw new InvalidSystemClockException($"Clock moved backwards or wrapped around. Refusing to generate id for {_lastgen - timestamp} ticks"); // If we're in the same "timeslot" as previous time we generated an Id, up the sequence number if (timestamp == _lastgen) { if (_sequence &lt; MASK_SEQUENCE) _sequence++; else throw new SequenceOverflowException("Sequence overflow. Refusing to generate id for rest of tick"); } else // If we're in a new(er) "timeslot", so we can reset the sequence and store the new(er) "timeslot" { _sequence = 0; _lastgen = timestamp; } unchecked { // Build id by shifting all bits into their place return (timestamp &lt;&lt; SHIFT_TIME) + (_generatorId &lt;&lt; SHIFT_GENERATOR) + _sequence; } } </code></pre> <p>Code not posted here is <code>GetTicks()</code> which, basically, returns a timestamp as integer but it's implementation is irrelevant.</p> <p>My questions specifically are about if this code does what it's supposed to do in a multi-threaded scenario and about optimization.</p> <p>First thing I do is take a lock and do all the work within that lock. There are two instance variables (<code>_sequence</code> and <code>_lastgen</code>) that are modified within this method. The <code>_generatorid</code> is only read. Besides implementing this method in a <a href="https://en.wikipedia.org/wiki/Non-blocking_algorithm" rel="noreferrer">lock-free</a> fashion (which I might do, sometime), I'm wondering if using <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.increment?view=netframework-4.7.2" rel="noreferrer"><code>Interlocked.Increment</code></a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked.compareexchange?view=netframework-4.7.2" rel="noreferrer"><code>Interlocked.CompareExchange</code></a> could help me make this code perform better. I could move some parts of the code within the lock outside of it but I don't think that would improve performance much (if at all). Another idea might be using another lock like a <code>ReaderWriterLockSlim</code> or <code>Monitor</code>?</p> <p>I also wonder if there's ways I didn't think of myself to optimize this code besides the lock without sacrificing too much readability or the general idea.</p> <p>And lastly, I wonder if there are any glaring bugs in here that I may have overlooked. Since this library is becoming more and more used I'd hate for it to have a bug in it's most important piece of code.</p> <p>Feedback is much appreciated.</p> <hr> <p>As per request, the entire class is as follows. Please keep in mind I'm not looking for feedback on the rest; I really want to focus on the <code>CreateId()</code> method and multithreading.</p> <pre><code>#if !NETSTANDARD2_0 &amp;&amp; !NETCOREAPP2_0 using IdGen.Configuration; #endif using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Runtime.CompilerServices; namespace IdGen { /// &lt;summary&gt; /// Generates Id's inspired by Twitter's (late) Snowflake project. /// &lt;/summary&gt; public class IdGenerator : IIdGenerator&lt;long&gt; { /// &lt;summary&gt; /// Returns the default epoch. /// &lt;/summary&gt; public static readonly DateTime DefaultEpoch = new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc); private static readonly ITimeSource defaulttimesource = new DefaultTimeSource(DefaultEpoch); private static readonly ConcurrentDictionary&lt;string, IdGenerator&gt; _namedgenerators = new ConcurrentDictionary&lt;string, IdGenerator&gt;(); private int _sequence = 0; private long _lastgen = -1; private readonly long _generatorId; private readonly long MASK_SEQUENCE; private readonly long MASK_TIME; private readonly long MASK_GENERATOR; private readonly int SHIFT_TIME; private readonly int SHIFT_GENERATOR; // Object to lock() on while generating Id's private readonly object _genlock = new object(); /// &lt;summary&gt; /// Gets the Id of the generator. /// &lt;/summary&gt; public int Id { get { return (int)_generatorId; } } /// &lt;summary&gt; /// Gets the epoch for the &lt;see cref="IdGenerator"/&gt;. /// &lt;/summary&gt; public DateTimeOffset Epoch { get { return TimeSource.Epoch; } } /// &lt;summary&gt; /// Gets the &lt;see cref="MaskConfig"/&gt; for the &lt;see cref="IdGenerator"/&gt;. /// &lt;/summary&gt; public MaskConfig MaskConfig { get; private set; } /// &lt;summary&gt; /// Gets the &lt;see cref="ITimeSource"/&gt; for the &lt;see cref="IdGenerator"/&gt;. /// &lt;/summary&gt; public ITimeSource TimeSource { get; private set; } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="IdGenerator"/&gt; class, 2015-01-01 0:00:00Z is used as default /// epoch and the &lt;see cref="P:IdGen.MaskConfig.Default"/&gt; value is used for the &lt;see cref="MaskConfig"/&gt;. The /// &lt;see cref="DefaultTimeSource"/&gt; is used to retrieve timestamp information. /// &lt;/summary&gt; /// &lt;param name="generatorId"&gt;The Id of the generator.&lt;/param&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt;Thrown when GeneratorId exceeds maximum value.&lt;/exception&gt; public IdGenerator(int generatorId) : this(generatorId, DefaultEpoch) { } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="IdGenerator"/&gt; class. The &lt;see cref="P:IdGen.MaskConfig.Default"/&gt; /// value is used for the &lt;see cref="MaskConfig"/&gt;. The &lt;see cref="DefaultTimeSource"/&gt; is used to retrieve /// timestamp information. /// &lt;/summary&gt; /// &lt;param name="generatorId"&gt;The Id of the generator.&lt;/param&gt; /// &lt;param name="epoch"&gt;The Epoch of the generator.&lt;/param&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt; /// Thrown when GeneratorId exceeds maximum value or epoch in future. /// &lt;/exception&gt; public IdGenerator(int generatorId, DateTimeOffset epoch) : this(generatorId, epoch, MaskConfig.Default) { } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="IdGenerator"/&gt; class. The &lt;see cref="DefaultTimeSource"/&gt; is /// used to retrieve timestamp information. /// &lt;/summary&gt; /// &lt;param name="generatorId"&gt;The Id of the generator.&lt;/param&gt; /// &lt;param name="maskConfig"&gt;The &lt;see cref="MaskConfig"/&gt; of the generator.&lt;/param&gt; /// &lt;exception cref="ArgumentNullException"&gt;Thrown when maskConfig is null.&lt;/exception&gt; /// &lt;exception cref="InvalidOperationException"&gt;Thrown when maskConfig defines a non-63 bit bitmask.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt; /// Thrown when GeneratorId or Sequence masks are &gt;31 bit, GeneratorId exceeds maximum value or epoch in future. /// &lt;/exception&gt; public IdGenerator(int generatorId, MaskConfig maskConfig) : this(generatorId, maskConfig, new DefaultTimeSource(DefaultEpoch)) { } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="IdGenerator"/&gt; class. The &lt;see cref="DefaultTimeSource"/&gt; is /// used to retrieve timestamp information. /// &lt;/summary&gt; /// &lt;param name="generatorId"&gt;The Id of the generator.&lt;/param&gt; /// &lt;param name="epoch"&gt;The Epoch of the generator.&lt;/param&gt; /// &lt;param name="maskConfig"&gt;The &lt;see cref="MaskConfig"/&gt; of the generator.&lt;/param&gt; /// &lt;exception cref="ArgumentNullException"&gt;Thrown when maskConfig is null.&lt;/exception&gt; /// &lt;exception cref="InvalidOperationException"&gt;Thrown when maskConfig defines a non-63 bit bitmask.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt; /// Thrown when GeneratorId or Sequence masks are &gt;31 bit, GeneratorId exceeds maximum value or epoch in future. /// &lt;/exception&gt; public IdGenerator(int generatorId, DateTimeOffset epoch, MaskConfig maskConfig) : this(generatorId, maskConfig, new DefaultTimeSource(epoch)) { } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="IdGenerator"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="generatorId"&gt;The Id of the generator.&lt;/param&gt; /// &lt;param name="timeSource"&gt;The time-source to use when acquiring time data.&lt;/param&gt; /// &lt;exception cref="ArgumentNullException"&gt;Thrown when either maskConfig or timeSource is null.&lt;/exception&gt; /// &lt;exception cref="InvalidOperationException"&gt;Thrown when maskConfig defines a non-63 bit bitmask.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt; /// Thrown when GeneratorId or Sequence masks are &gt;31 bit, GeneratorId exceeds maximum value or epoch in future. /// &lt;/exception&gt; public IdGenerator(int generatorId, ITimeSource timeSource) : this(generatorId, MaskConfig.Default, timeSource) { } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="IdGenerator"/&gt; class. /// &lt;/summary&gt; /// &lt;param name="generatorId"&gt;The Id of the generator.&lt;/param&gt; /// &lt;param name="maskConfig"&gt;The &lt;see cref="MaskConfig"/&gt; of the generator.&lt;/param&gt; /// &lt;param name="timeSource"&gt;The time-source to use when acquiring time data.&lt;/param&gt; /// &lt;exception cref="ArgumentNullException"&gt;Thrown when either maskConfig or timeSource is null.&lt;/exception&gt; /// &lt;exception cref="InvalidOperationException"&gt;Thrown when maskConfig defines a non-63 bit bitmask.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt; /// Thrown when GeneratorId or Sequence masks are &gt;31 bit, GeneratorId exceeds maximum value or epoch in future. /// &lt;/exception&gt; public IdGenerator(int generatorId, MaskConfig maskConfig, ITimeSource timeSource) { if (maskConfig == null) throw new ArgumentNullException("maskConfig"); #pragma warning disable IDE0016 if (timeSource == null) throw new ArgumentNullException("timeSource"); #pragma warning restore IDE0016 if (maskConfig.TotalBits != 63) throw new InvalidOperationException("Number of bits used to generate Id's is not equal to 63"); if (maskConfig.GeneratorIdBits &gt; 31) throw new ArgumentOutOfRangeException("GeneratorId cannot have more than 31 bits"); if (maskConfig.SequenceBits &gt; 31) throw new ArgumentOutOfRangeException("Sequence cannot have more than 31 bits"); // Precalculate some values MASK_TIME = GetMask(maskConfig.TimestampBits); MASK_GENERATOR = GetMask(maskConfig.GeneratorIdBits); MASK_SEQUENCE = GetMask(maskConfig.SequenceBits); if (generatorId &lt; 0 || generatorId &gt; MASK_GENERATOR) throw new ArgumentOutOfRangeException($"GeneratorId must be between 0 and {MASK_GENERATOR} (inclusive)."); SHIFT_TIME = maskConfig.GeneratorIdBits + maskConfig.SequenceBits; SHIFT_GENERATOR = maskConfig.SequenceBits; // Store instance specific values MaskConfig = maskConfig; TimeSource = timeSource; _generatorId = generatorId; } /// &lt;summary&gt; /// Creates a new Id. /// &lt;/summary&gt; /// &lt;returns&gt;Returns an Id based on the &lt;see cref="IdGenerator"/&gt;'s epoch, generatorid and sequence.&lt;/returns&gt; /// &lt;exception cref="InvalidSystemClockException"&gt;Thrown when clock going backwards is detected.&lt;/exception&gt; /// &lt;exception cref="SequenceOverflowException"&gt;Thrown when sequence overflows.&lt;/exception&gt; public long CreateId() { lock (_genlock) { // Determine "timeslot" and make sure it's &gt;= last timeslot (if any) var ticks = GetTicks(); var timestamp = ticks &amp; MASK_TIME; if (timestamp &lt; _lastgen || ticks &lt; 0) throw new InvalidSystemClockException($"Clock moved backwards or wrapped around. Refusing to generate id for {_lastgen - timestamp} ticks"); // If we're in the same "timeslot" as previous time we generated an Id, up the sequence number if (timestamp == _lastgen) { if (_sequence &lt; MASK_SEQUENCE) _sequence++; else throw new SequenceOverflowException("Sequence overflow. Refusing to generate id for rest of tick"); } else // If we're in a new(er) "timeslot", so we can reset the sequence and store the new(er) "timeslot" { _sequence = 0; _lastgen = timestamp; } unchecked { // Build id by shifting all bits into their place return (timestamp &lt;&lt; SHIFT_TIME) + (_generatorId &lt;&lt; SHIFT_GENERATOR) + _sequence; } } } /// &lt;summary&gt; /// Returns information about an Id such as the sequence number, generator id and date/time the Id was generated /// based on the current mask config of the generator. /// &lt;/summary&gt; /// &lt;param name="id"&gt;The Id to extract information from.&lt;/param&gt; /// &lt;returns&gt;Returns an &lt;see cref="ID" /&gt; that contains information about the 'decoded' Id.&lt;/returns&gt; /// &lt;remarks&gt; /// IMPORTANT: note that this method relies on the mask config and timesource; if the id was generated with a /// diffferent mask config and/or timesource than the current one the 'decoded' ID will NOT contain correct /// information. /// &lt;/remarks&gt; public ID FromId(long id) { // Deconstruct Id by unshifting the bits into the proper parts return ID.Create( (int)(id &amp; MASK_SEQUENCE), (int)((id &gt;&gt; SHIFT_GENERATOR) &amp; MASK_GENERATOR), TimeSource.Epoch.Add(TimeSpan.FromTicks(((id &gt;&gt; SHIFT_TIME) &amp; MASK_TIME) * TimeSource.TickDuration.Ticks)) ); } #if !NETSTANDARD2_0 &amp;&amp; !NETCOREAPP2_0 /// &lt;summary&gt; /// Returns an instance of an &lt;see cref="IdGenerator"/&gt; based on the values in the corresponding idGenerator /// element in the idGenSection of the configuration file. The &lt;see cref="DefaultTimeSource"/&gt; is used to /// retrieve timestamp information. /// &lt;/summary&gt; /// &lt;param name="name"&gt;The name of the &lt;see cref="IdGenerator"/&gt; in the idGenSection.&lt;/param&gt; /// &lt;returns&gt;An instance of an &lt;see cref="IdGenerator"/&gt; based on the values in the corresponding idGenerator /// element in the idGenSection of the configuration file.&lt;/returns&gt; /// &lt;remarks&gt; /// When the &lt;see cref="IdGenerator"/&gt; doesn't exist it is created; any consequent calls to this method with /// the same name will return the same instance. /// &lt;/remarks&gt; public static IdGenerator GetFromConfig(string name) { var result = _namedgenerators.GetOrAdd(name, (n) =&gt; { var idgenerators = (ConfigurationManager.GetSection(IdGeneratorsSection.SectionName) as IdGeneratorsSection).IdGenerators; var idgen = idgenerators.OfType&lt;IdGeneratorElement&gt;().FirstOrDefault(e =&gt; e.Name.Equals(n)); if (idgen != null) { var ts = idgen.TickDuration == TimeSpan.Zero ? defaulttimesource : new DefaultTimeSource(idgen.Epoch, idgen.TickDuration); return new IdGenerator(idgen.Id, new MaskConfig(idgen.TimestampBits, idgen.GeneratorIdBits, idgen.SequenceBits), ts); } throw new KeyNotFoundException(); }); return result; } #endif /// &lt;summary&gt; /// Gets the number of ticks since the &lt;see cref="ITimeSource"/&gt;'s epoch. /// &lt;/summary&gt; /// &lt;returns&gt;Returns the number of ticks since the &lt;see cref="ITimeSource"/&gt;'s epoch.&lt;/returns&gt; [MethodImpl(MethodImplOptions.AggressiveInlining)] private long GetTicks() { return TimeSource.GetTicks(); } /// &lt;summary&gt; /// Returns a bitmask masking out the desired number of bits; a bitmask of 2 returns 000...000011, a bitmask of /// 5 returns 000...011111. /// &lt;/summary&gt; /// &lt;param name="bits"&gt;The number of bits to mask.&lt;/param&gt; /// &lt;returns&gt;Returns the desired bitmask.&lt;/returns&gt; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static long GetMask(byte bits) { return (1L &lt;&lt; bits) - 1; } /// &lt;summary&gt; /// Returns a 'never ending' stream of Id's. /// &lt;/summary&gt; /// &lt;returns&gt;A 'never ending' stream of Id's.&lt;/returns&gt; private IEnumerable&lt;long&gt; IdStream() { while (true) yield return CreateId(); } /// &lt;summary&gt; /// Returns an enumerator that iterates over Id's. /// &lt;/summary&gt; /// &lt;returns&gt;An &lt;see cref="IEnumerator&amp;lt;T&amp;gt;"/&gt; object that can be used to iterate over Id's.&lt;/returns&gt; public IEnumerator&lt;long&gt; GetEnumerator() { return IdStream().GetEnumerator(); } /// &lt;summary&gt; /// Returns an enumerator that iterates over Id's. /// &lt;/summary&gt; /// &lt;returns&gt;An &lt;see cref="IEnumerator"/&gt; object that can be used to iterate over Id's.&lt;/returns&gt; IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T16:16:07.547", "Id": "391726", "Score": "0", "body": "You need to include more code because currently there are many undefined variables. It'd be great if you added the entire class." }, { "ContentLicense": "CC BY-SA 4.0", ...
[ { "body": "<p>Since your lock only needs to protect the member variables you mutate, you can scope it to just that if/else block where you make your modifications. You do use <code>_sequence</code> one additional time when generating the return value, but that could use a local copy acquired while the lock is ...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T10:46:33.883", "Id": "203091", "Score": "7", "Tags": [ "c#", "algorithm", "multithreading", "locking", "lock-free" ], "Title": "Snowflake Id implementation" }
203091
<p>Due to another module coupled to my function, I can only receive the input to my part in the form of a JSON object structured roughly like this:</p> <pre><code>[{'id':0, 'y':4, 'value':25},{'id':0, 'y':2, 'value':254}] </code></pre> <p>Note that I do know that the data will arrive in <em>exactly that format</em>. Now, I need to cast this to lists such that I can pass it to the constructor of <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html" rel="nofollow noreferrer"><code>scipy.sparse.coo_matrix()</code></a>. Since I have frequent incoming calls, I want to perform this cast as quickly as possible, which is why I am concerned with the optimization of this operation. Below are three different approaches that come up with this type of question. Note that the casting itself has been frequently addressed on Stackoverflow, even with respect to performance in some cases (mostly in terms of list comprehension), but I could not find anything that would give me an optimal solution.</p> <p>To quickly address the three different methods I use:</p> <ol> <li>evaluate each line as a tuple of the dictionary values. Comparable in speed with something like <code>[[el['id'], el['y'], el['values']] for el in x]</code>.</li> <li>Let <code>pandas</code> do the casting for you. Extremly slow.</li> <li>Cast three separate lists. Since the allocation of lists in list comprehensions is way slower (compare <code>[[el['id']] for el in x]</code> to <code>[el['id'] for el in x]</code>), this seems to be the currently best-performing solution.</li> </ol> <p>According to the articles I found, list comprehensions outperform any python-native method using <code>.append()</code>, but I might add an example and timing for that later.</p> <p>The benchmarks are as follows:</p> <pre><code>import timeit as ti # 2.107 seconds print(ti.timeit("z = [tuple(el.values()) for el in x]", setup="import random; x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000", number=100)) # 8.93 seconds print(ti.timeit("z = pd.DataFrame(x)", setup="import pandas as pd; import random; x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000", number=100)) # 0.717 seconds print(ti.timeit("z1 = [el['id'] for el in x]; z2 = [el['y'] for el in x]; z3 = [el['value'] for el in x]", setup="import random; x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000", number=100)) </code></pre> <p>I also include the "raw code" for the three snippets:</p> <pre><code>import random import pandas as pd if __name__ == "__main__": # ignore the fact that this actually isn't random for individual values x = [{'id':random.randint(0,5),'y':random.randint(0,5), 'value':random.randint(0,500)}]*60000 # first method z1 = [tuple(el.values()) for el in x] # second method z2 = pd.DataFrame(x) # third method z_3a = [el['id'] for el in x] z_3b = [el['y'] for el in x] z_3c = [el['value'] for el in x] </code></pre> <p>The question is whether there is any significant improvement on this (maybe by using a specialized library I don't know of, or any trick with numpy, etc.) to <em>easily</em> improve the speed on this. I'm currently assuming that, following the 80/20 principle, it is unlikely I'll get more performance out of this without spending a lot more effort on it...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T12:25:29.847", "Id": "391413", "Score": "1", "body": "Hi, it looks like you're asking for a comparative review, however it's hard to tell this from the code that you've posted. Would you be willing to post the three different method...
[ { "body": "<ul>\n<li><p><strike>Does the <code>scipy.sparse.coo_matrix()</code> function accept three different lists as parameters?</strike></p>\n\n<p><strike>Maybe I'm missing something but your \"fastest\" method is not actually the fastest, since you'd still need some conversion to parse it to the function ...
{ "AcceptedAnswerId": "203169", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T12:08:05.623", "Id": "203095", "Score": "2", "Tags": [ "python", "performance", "pandas", "scipy" ], "Title": "Convert list of dictionaries to iterable list" }
203095
<p>I am not very experienced in Entity Framework, I previously used ADO.Net and Dapper for data persistence. For now, I only read Microsoft docs and watched a few video tutorials. I tried to stick to well accepted advice and have built a generic repository infrastructure with the help of from here and there. </p> <h3>IEntity</h3> <pre><code>public interface IEntity { object Id { get; set; } string CreatedBy { get; set; } DateTime CreatedOn { get; set; } string ModifiedBy { get; set; } DateTime? ModifiedOn { get; set; } } public interface IEntity&lt;T&gt; : IEntity { new T Id { get; set; } } </code></pre> <h3>BaseEntity</h3> <pre><code>public abstract class BaseEntity&lt;T&gt; : IEntity&lt;T&gt; { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public T Id { get; set; } object IEntity.Id { get { return Id; } set { } } public string CreatedBy { get; set; } private DateTime? createdOn; [DataType(DataType.DateTime)] public DateTime CreatedOn { get { return createdOn ?? DateTime.UtcNow; } set { createdOn = value; } } public string ModifiedBy { get; set; } [DataType(DataType.DateTime)] public DateTime? ModifiedOn { get; set; } } </code></pre> <h3>User Entity</h3> <pre><code>public class User : BaseEntity&lt;int&gt; { public string FullName { get; set; } public string Email { get; set; } public UserType UserType { get; set; } public string Password { get; set; } public virtual ICollection&lt;Comment&gt; Comments { get; set; } public virtual ICollection&lt;Post&gt; Posts { get; set; } } </code></pre> <h3>IRepository</h3> <pre><code>public interface IRepository&lt;TEntity&gt; where TEntity: IEntity { IEnumerable&lt;TEntity&gt; GetAll(Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = null, int? skip = null, int? take = null); TEntity GetFirst(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = null); TEntity GetById(object id); TEntity GetOne(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, string includeProperties = null); void Create(TEntity entity, string createdBy = null); void Update(TEntity entity, string modifiedBy = null); void Delete(TEntity entity); void Delete(object id); void Save(); } </code></pre> <h3>EFRepository</h3> <pre><code>public class EFRepository&lt;TEntity&gt; : IRepository&lt;TEntity&gt; where TEntity : class, IEntity { private DbContext _context; public EFRepository(BlogContext context) { _context = context; } protected virtual IEnumerable&lt;TEntity&gt; GetQueryable( Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = null, int? skip = null, int? take = null) { includeProperties = includeProperties ?? string.Empty; IQueryable&lt;TEntity&gt; query = _context.Set&lt;TEntity&gt;(); if (filter != null) { query = query.Where(filter); } foreach (var includeProperty in includeProperties.Split (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { query = query.Include(includeProperty); } if (orderBy != null) { query = orderBy(query); } if (skip.HasValue) { query = query.Skip(skip.Value); } if (take.HasValue) { query = query.Take(take.Value); } return query.AsEnumerable(); } public IEnumerable&lt;TEntity&gt; GetAll(Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = null, int? skip = null, int? take = null) { return GetQueryable(orderBy: orderBy, includeProperties: includeProperties, skip: skip, take: take); } public TEntity GetById(object id) { return _context.Set&lt;TEntity&gt;().Find(id); } public TEntity GetFirst(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null, string includeProperties = null) { return GetQueryable(filter: filter, orderBy: orderBy, includeProperties: includeProperties).FirstOrDefault(); } public TEntity GetOne(Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null, string includeProperties = null) { return GetQueryable(filter: filter, includeProperties: includeProperties).SingleOrDefault(); } public void Save() { try { _context.SaveChanges(); } catch (Exception e) { } } public void Create(TEntity entity, string createdBy = null) { entity.CreatedOn = DateTime.UtcNow; entity.CreatedBy = createdBy; _context.Add&lt;TEntity&gt;(entity); } public void Update(TEntity entity, string modifiedBy = null) { entity.CreatedOn = DateTime.UtcNow; entity.CreatedBy = modifiedBy; _context.Set&lt;TEntity&gt;().Attach(entity); _context.Entry(entity).State = EntityState.Modified; } public void Delete(TEntity entity) { var dbSet = _context.Set&lt;TEntity&gt;(); if (_context.Entry(entity).State == EntityState.Detached) dbSet.Attach(entity); dbSet.Remove(entity); } public void Delete(object id) { TEntity entity = _context.Set&lt;TEntity&gt;().Find(id); Delete(entity); } } </code></pre> <h3>IService</h3> <pre><code>public interface IService { IRepository&lt;T&gt; GetRepository&lt;T&gt;(DbContext context) where T : class, IEntity; } </code></pre> <h3>BaseService</h3> <pre><code>public abstract class BaseService : IService { public BaseService(BlogContext context, ILogger&lt;BaseService&gt; logger) { _context = context; _logger = logger; } protected DbContext _context { get; set; } protected readonly ILogger&lt;BaseService&gt; _logger; public IRepository&lt;T&gt; GetRepository&lt;T&gt;(DbContext context) where T : class, IEntity { return new EFRepository&lt;T&gt;((BlogContext)context); } public IRepository&lt;T&gt; GetRepository&lt;T&gt;() where T : class, IEntity { return GetRepository&lt;T&gt;(_context); } } </code></pre> <h3>IUserService</h3> <pre><code>public interface IAuthorService { bool DeleteAuthorWithEntireStuff(int userId); } </code></pre> <h3>UserService</h3> <pre><code>public class UserService : BaseService, IAuthorService { public UserService(BlogContext context, ILogger&lt;UserService&gt; logger) : base(context, logger) { } public bool DeleteAuthorWithEntireStuff(int id) { try { var userRepo = GetRepository&lt;User&gt;(); var commentRepo = GetRepository&lt;Comment&gt;(); var postRepo = GetRepository&lt;Post&gt;(); var user = userRepo.GetAll().Where(u =&gt; u.Id == id).FirstOrDefault(); if (user != null) { var commentList = commentRepo.GetAll().Where(c =&gt; c.UserId == id).ToList(); var postList = postRepo.GetAll().Where(p =&gt; p.AuthorId == id).ToList(); foreach (var item in commentList) commentRepo.Delete(item); foreach (var item in postList) postRepo.Delete(item); userRepo.Delete(user); _context.SaveChanges(); } return true; } catch (Exception) { throw; } } } </code></pre> <h3>And finally controller</h3> <pre><code>public class UserController : Controller { private readonly IRepository&lt;User&gt; _repository; private readonly IUserService _authorService; public UserController(IRepository&lt;User&gt; repository, IUserService authorService) { _repository = repository; _authorService = authorService; } [HttpPost] public IActionResult Create([FromBody]User model) { try { _repository.Create(model); _repository.Save(); return Ok(model); } catch(Exception ex) { return BadRequest(ex); } } [HttpPost] [Route("DeletUserEntirely")] public IActionResult DeleteUserEntirely([FromBody]User model) { try { if (_authorService.DeleteUserEntirely(model.Id)) return Ok(); else return BadRequest(); } catch (Exception ex) { return BadRequest(ex); } } } </code></pre> <p>As you see in the UserService code when I need to run multiple commands in one transaction, I make use of the <a href="https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-implemenation-entity-framework-core#using-a-custom-repository-versus-using-ef-dbcontext-directly" rel="nofollow noreferrer">ef's unit of work</a> (<code>_context.SaveChanges()</code>). </p> <p>I did not create any extra unit of work classes as suggested at <a href="https://stackoverflow.com/a/49429628/2289430">few places</a> or wrap my repos in transaction scope. As discussed <a href="https://github.com/dotnet-architecture/eShopOnWeb/issues/46" rel="nofollow noreferrer">here</a>, some people defend unit of work implementations for transaction integrity that I do not still get it why while ef implementing uow pattern already.</p> <p>I haven't tested above code so much but till now it seems ok. </p> <p>Btw, I used <a href="https://codereview.stackexchange.com/users/62690/chris-pratt">Chris Pratt's</a> <a href="https://cpratt.co/truly-generic-repository/" rel="nofollow noreferrer">Generic Repository</a> approach. Any problems with this approach, especially with the perspective of transactions in generic repository use entity framework? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-14T13:47:35.000", "Id": "392798", "Score": "3", "body": "The repository-pattern is like a virus. It's spreading everywhere and causes only harm ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-13T15:38:1...
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T12:13:36.227", "Id": "203096", "Score": "1", "Tags": [ "c#", "entity-framework", "repository", "transactions" ], "Title": "Transaction integrity in asp.net core with entity framework and generic repository" }
203096
<p>I have 2 geoPandas frames and want to calculate the distance and the nearest point (see functions below) from the geoSeries <code>geometry</code> from dataframe 1 (containing 156055 rows with unique POINT geometries) as to a geoSeries <code>geometry</code> in dataframe 2 (75 rows POINTS). </p> <p>Question: <strong>How can the following code be optimized so as to make it quicker?</strong> As an example, I would love some code that uses the <strong>dask</strong> distributed dataframes <a href="https://dask.readthedocs.io/en/latest/dataframe-api.html#dask.dataframe.Series.map_partitions" rel="nofollow noreferrer">map_partitions</a> solution to apply the below functions on a partitioned part of a (sub)-dataframe so as to speed things up. Optimized vector-based cython code would also be a solution etc.. </p> <p>A peak in both dataframes:</p> <p>df1:</p> <p><a href="https://i.stack.imgur.com/J9Ysu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J9Ysu.png" alt="enter image description here"></a></p> <p>df2:</p> <p><a href="https://i.stack.imgur.com/GpCYd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GpCYd.png" alt="enter image description here"></a></p> <p>In the <code>ah</code> frame (df2) there are 75 points, around which I place a buffer of 1000 meters. In each buffer I calculate the distance (using the points of df1 representing households) and nearest point. </p> <p>My code so far works but, as said, is slow:</p> <pre><code>import pandas as pd import geopandas as gpd from shapely import wkt, wkb from shapely.geometry import Polygon, Point, LinearRing from shapely.ops import nearest_points from tqdm import tqdm, tqdm_notebook # crs crs= {'init': 'epsg:28992'} def calculate_distance(row, dest_geom, src_col='geometry', target_col='distance'): """ Calculates distance between single Point geometry and GeoDF with Point geometries. Parameters ---------- dest_geom : Point geometry to which distances will be calculated to src_col : column with Point objects from where the distances will be calculated from. target_col : name of target column where the result will be stored. """ # calculate distances dist = row[src_col].distance(dest_geom) # to km dist_km = dist/1000 # Assign the distance to the original data row[target_col] = dist_km return row def find_nearest_point(row, geom_union, df1, df2, geom1_col='geometry', geom2_col='geometry', src_column=None): """Find nearest point,return corresponding value from specified column Parameters ---------- geom_union = variable with unary union of points from second frame. df1 = dataframe 1 containing geometry column (points) df2 = dataframe 2 containing geometry column (points) geom1_col = geometry column name from df1 geom2_col = geometry column name from df2 src_column = columns from df2 to be retrieved based on nearest match """ # Find closest geometry nearest = df2[geom2_col] == nearest_points(row[geom1_col], geom_union)[1] # Get corresponding value from df2 (based on geometry match) value = df2[nearest][src_column].get_values()[0] return value </code></pre> <p>Here i apply the functions with a loop:</p> <pre><code>n=len(ah) test = [] for i, row in enumerate(tqdm_notebook(list(ah['buffer'][:n]), desc='distance_calc')): sub_df = df.loc[(df.geometry.within(ah['buffer'][i])), :] sub_df = (sub_df.apply(calculateDistance, dest_geom= ah['geometry'][i], target_col= 'distance', axis=1)) print ('shape sub_df {} = {}'.format(i, sub_df.shape)) indices = (sub_df.apply(nearest, geom_union=ah.unary_union, df1=sub_df, df2=ah, geom1_col='geometry', src_column='zaak_id', axis=1)) indices_frame = indices.to_frame() sub_df = pd.concat([sub_df, indices_frame], axis=1) test.append(sub_df) test = pd.concat(test, axis=0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T14:41:58.437", "Id": "391454", "Score": "0", "body": "what if a review of your code points out that the performance could be increased without the use of `dask distributed dataframes map_partitions` ? would that still be acceptable...
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T12:32:45.787", "Id": "203098", "Score": "3", "Tags": [ "python", "performance", "pandas", "computational-geometry", "geospatial" ], "Title": "Function to calculate distances and nearest points between 2 GeoPandas dataframes" }
203098
<p>This is actually a <a href="https://www.hackerrank.com/" rel="noreferrer">hackerrank</a> interview question I have already solved but I need guidance on how to optimize it for the </p> <ol> <li>Time</li> <li>Space</li> </ol> <blockquote> <p>Given an array of integers, your task is to count the number of duplicate array elements. Duplicate is defined as two or more identical elements. For example, in the array [1, 2, 2, 3, 3, 3], the two twos are one duplicate and so are the three threes.</p> <p><strong>Function Description</strong> </p> <p>Complete the function <code>countDuplicates</code> in the editor below. The function must return an integer denoting the number of non-unique (duplicate) values in the numbers array.</p> <p><code>countDuplicates</code> has the following parameter(s):</p> <p><code>numbers[numbers[0],...numbers[n-1]]</code>: an array of integers to process</p> <p><strong>Constraints</strong></p> <p>1 ≤ n ≤ 1000<br> 1 ≤ numbers[i] ≤ 1000, 0 ≤ i &lt; n</p> <p>Sample Input: <code>[1, 3, 1, 4, 5, 6, 3, 2]</code><br> Sample Output: <code>2</code><br> Explanation: The integers 1 and 3 both occur more than once, so we return 2 as our answer.</p> </blockquote> <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>function countDuplicates(original) { let counts = {}, duplicate = 0; original.forEach(function(x) { counts[x] = (counts[x] || 0) + 1; }); for (var key in counts) { if (counts.hasOwnProperty(key)) { counts[key] &gt; 1 ? duplicate++ : duplicate; } } return duplicate; }</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T14:25:04.350", "Id": "391452", "Score": "1", "body": "The code is perfect, can´t do better than O(n) time. You could however use an array instead of an object to count, as you know the numbers only go up to 1000." } ]
[ { "body": "<h2>Reduce time</h2>\n<p>You can improve the function's time complexity at the expense of memory by tracking the duplicates in a separate <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a>. This will reduce the number o...
{ "AcceptedAnswerId": "203116", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T13:26:36.463", "Id": "203102", "Score": "7", "Tags": [ "javascript", "performance", "interview-questions", "memory-optimization" ], "Title": "Count duplicates in a JavaScript array" }
203102
<h1>I want to find a more efficient solution to the following problem:</h1> <p>My dataset is about online games. Each player may have multiple plays (rows in the df). Each play has its corresponding timestamp. However, some events are lacking their id (session identifier). I need an efficient method to fill the NaN of the id columns, using information from the other two columns. </p> <p>This is the dataset: </p> <pre><code>d = {'player': ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '4'], 'date': ['2018-01-01 00:17:01', '2018-01-01 00:17:05','2018-01-01 00:19:05', '2018-01-01 00:21:07', '2018-01-01 00:22:09', '2018-01-01 00:22:17', '2018-01-01 00:25:09', '2018-01-01 00:25:11', '2018-01-01 00:27:28', '2018-01-01 00:29:29', '2018-01-01 00:30:35', '2018-02-01 00:31:16', '2018-02-01 00:35:22', '2018-02-01 00:38:16', '2018-02-01 00:38:20', '2018-02-01 00:55:15', '2018-01-03 00:55:22', '2018-01-03 00:58:16', '2018-01-03 00:58:21', '2018-03-01 01:00:35', '2018-03-01 01:20:16', '2018-03-01 01:31:16', '2018-03-01 02:44:21'], 'id': [np.nan, np.nan, 'a', 'a', 'b', np.nan, 'b', 'c', 'c', 'c', 'c', 'd', 'd', 'e', 'e', np.nan, 'f', 'f', 'g', np.nan, 'f', 'g', 'h']} #create dataframe df = pd.DataFrame(data=d) df player date id 0 1 2018-01-01 00:17:01 NaN 1 1 2018-01-01 00:17:05 NaN 2 1 2018-01-01 00:19:05 a 3 1 2018-01-01 00:21:07 a 4 1 2018-01-01 00:22:09 b 5 1 2018-01-01 00:22:17 NaN 6 1 2018-01-01 00:25:09 b 7 1 2018-01-01 00:25:11 c 8 1 2018-01-01 00:27:28 c 9 1 2018-01-01 00:29:29 c 10 1 2018-01-01 00:30:35 c 11 2 2018-02-01 00:31:16 d 12 2 2018-02-01 00:35:22 d 13 2 2018-02-01 00:38:16 e 14 2 2018-02-01 00:38:20 e 15 2 2018-02-01 00:55:15 NaN 16 3 2018-01-03 00:55:22 f 17 3 2018-01-03 00:58:16 f 18 3 2018-01-03 00:58:21 g 19 3 2018-03-01 01:00:35 NaN 20 3 2018-03-01 01:20:16 f 21 3 2018-03-01 01:31:16 g 22 4 2018-03-01 02:44:21 h </code></pre> <h1>This was my line of reasoning:</h1> <h2><strong>1. Groupby player and id</strong></h2> <p>computing the first and last date for each play.</p> <pre><code>my_agg = df.groupby(['player', 'id']).date.agg([min, max]) my_agg min max player id 1 a 2018-01-01 00:19:05 2018-01-01 00:21:07 b 2018-01-01 00:22:09 2018-01-01 00:25:09 c 2018-01-01 00:25:11 2018-01-01 00:30:35 2 d 2018-02-01 00:31:16 2018-02-01 00:35:22 e 2018-02-01 00:38:16 2018-02-01 00:38:20 3 f 2018-01-03 00:55:22 2018-03-01 01:20:16 g 2018-01-03 00:58:21 2018-03-01 01:31:16 4 h 2018-03-01 02:44:21 2018-03-01 02:44:21 </code></pre> <h2><strong>2. Create a function</strong></h2> <p>that compares the timestamp of the play to every id available, and see whether or not it falls within range. Basically, if it falls within range of a single session of play id, I want to fill the NaN with the id label. If it is not within range of any session id, I want to fill the NaN with 0. If it is within range of multiple sessions (theoretically it should not be), it fills the missing value with -99.</p> <pre><code>#define a function to sort the missing values def check_function(time): #compare every date event with the range of the sessions. current_sessions = group.loc[(group['min']&lt;time) &amp; (group['max']&gt;time)] #store length, that is the number of matches. count = len(current_sessions) #How many matches are there for any missing id value? # if 0 the event lies outside all the possible ranges if count == 0: return 0 #if &gt;1, it is impossible to say to which session the event belongs if count &gt; 1: return -99 #in this case the event belongs clearly to just one session return current_sessions.index[0][1] </code></pre> <h2><strong>3. Apply the function player by player</strong></h2> <p>And store the results to create a new dataframe, with the desired output.</p> <pre><code>grouped = my_agg.groupby(level=0) final = pd.DataFrame() for name, group in grouped: mv_per_player = df.loc[df['player'] == name] mv_per_player.loc[mv_per_player.id.isnull(),'id'] = mv_per_player.loc[mv_per_player.id.isnull(),'date'].apply(check_function) final = final.append(mv_per_player) final player date id 0 1 2018-01-01 00:17:01 0 1 1 2018-01-01 00:17:05 0 2 1 2018-01-01 00:19:05 a 3 1 2018-01-01 00:21:07 a 4 1 2018-01-01 00:22:09 b 5 1 2018-01-01 00:22:17 b 6 1 2018-01-01 00:25:09 b 7 1 2018-01-01 00:25:11 c 8 1 2018-01-01 00:27:28 c 9 1 2018-01-01 00:29:29 c 10 1 2018-01-01 00:30:35 c 11 2 2018-02-01 00:31:16 d 12 2 2018-02-01 00:35:22 d 13 2 2018-02-01 00:38:16 e 14 2 2018-02-01 00:38:20 e 15 2 2018-02-01 00:55:15 0 16 3 2018-01-03 00:55:22 f 17 3 2018-01-03 00:58:16 f 18 3 2018-01-03 00:58:21 g 19 3 2018-03-01 01:00:35 -99 20 3 2018-03-01 01:20:16 f 21 3 2018-03-01 01:31:16 g 22 4 2018-03-01 02:44:21 h </code></pre> <h1>Conclusion</h1> <p>This process works, but is there a way to make the process more efficient and faster? I think the bottleneck is the for loop, but I cannot find an alternative solution. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T13:41:46.583", "Id": "203103", "Score": "2", "Tags": [ "python", "performance", "pandas" ], "Title": "Pandas: missing value imputation" }
203103
<p>I was wondering if there was a better way to implement my cli parser.</p> <p><strong>For context:</strong> I need to pass to my script either a file in one of two formats or two files in a specific format.</p> <p>It may be easier to understand like this:</p> <p><code>file.ext1 OR file.ext2 OR (file_1.ext2 AND file_2.ext2)</code></p> <hr> <p>I've used python argparse <code>add_mutually_exclusive_group</code> successfully and it looks like this:</p> <pre><code>import argparse parser = argparse.ArgumentParser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument( "--ext1", type = __existant_file, metavar = "FILE", help = "input file (format ext1)" ) group.add_argument( "--ext2", type = __existant_file, metavar = "FILE", help = "input file (format ext2)" ) group.add_argument( "--paired", nargs = 2, type = __existant_file, metavar = ("MATE_1", "MATE_2"), help = "input file (two files format ext2)" ) args = parser.parse_args() print(args) if args.ext1 is not None: file = args.ext1 elif args.ext2 is not None: file = args2.ext2 else: file = args.paired[0] file2 = args.paired[1] </code></pre> <p>Which is used as:</p> <pre><code>python script.py --ext1 file OR python script.py --ext2 file OR python script.py --paired file_1 file_2 </code></pre> <p>Which is working but not really smooth. Do you have any lead of how I can improve the CLI parser ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T14:03:52.733", "Id": "391446", "Score": "0", "body": "@Graipher Well, I do believe this is exactly what I asked, my code is working but I'd like improvement. Maybe it's not clear tho, I'll rewrite a bit" }, { "ContentLicense...
[ { "body": "<p>Okay, I found a better way</p>\n\n<pre><code>import argparse\nparser = argparse.ArgumentParser()\n\nclass RequiredLen(argparse.Action):\n def __call__(self, parser, args, values, option_string=None):\n if not 1 &lt;= len(values) &lt;= 2:\n msg = f\"argument {self.d...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T13:57:05.217", "Id": "203104", "Score": "3", "Tags": [ "python", "console" ], "Title": "Python CLI-Parser improvement for \"one of those options\"" }
203104
<p>I'm using angular 6 and ngx-translate. This is my switch language function</p> <pre><code> switchLanguage(language: string) { this.translate.use(language); if (language !== 'ar' &amp;&amp; document.getElementsByTagName('html')[0].hasAttribute('dir')) { document.getElementsByTagName('html')[0].removeAttribute('dir'); } else if (language === 'ar' &amp;&amp; !document.getElementsByTagName('html')[0].hasAttribute('dir')) { document.getElementsByTagName('html')[0].setAttribute('dir', 'rtl'); } // if this line worth it? if (language !== JSON.parse(localStorage.getItem('lang'))) { localStorage.setItem('lang', JSON.stringify(language)); } } </code></pre> <p>I'm asking about this line in particular</p> <pre><code>if (language !== JSON.parse(localStorage.getItem('lang'))) </code></pre> <p>If I don't use it, it means that if the language is english and you switch it to english, the localStorage is going to be updated. If I use it however, it means that, every time you switch a language, it's going to read localstorage to check its value before updating.</p> <p>Is the cost of just setting the language better than the cost of checking it first?</p> <p>This method is getting called whenever you switch the language and in <code>app.ts</code> constructor, so basically on every page load. Is there a better way to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T14:48:27.457", "Id": "391455", "Score": "0", "body": "Lack of context: Please update your question with the HTML being used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T14:53:12.110", "Id": "3...
[ { "body": "<p>The rewrite of LocalStorage is normal practice because of a rewrite time ~equal check time. </p>\n\n<p>You can change the code.</p>\n\n<pre><code>localStorage.setItem('lang', language);\n</code></pre>\n\n<p>By the way <code>JSON.parse</code> and <code>JSON.stringify</code> is unnecessary actions ...
{ "AcceptedAnswerId": "203110", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T13:59:20.090", "Id": "203105", "Score": "1", "Tags": [ "typescript", "i18n", "angular-2+", "browser-storage" ], "Title": "Language switcher, consulting browser's localStorage" }
203105
<p>The title is a bit of a mouthful, so here's a quick example:</p> <p>You've got an array, maybe just the digits 1-3, and you want to get the sum of product of all size-2 combinations of the array. Those combinations are (1,2), (1,3), and (2,3), so the answer I'm looking for is this:</p> <p>$$1\cdot2+1\cdot3+2\cdot3=11$$</p> <p>Except now, the array is about 3-4 orders of magnitude in size, and the problem is kinda intractable beyond size-2 combinations.</p> <p>Here's the code I have made to do the task:</p> <pre><code>import numpy as np from itertools import combinations as comb #A is the target array, in this case, a random array of 1000 elements. #B is a iterator of length-2 tuples which should act as indices for reading A. n = 2 A = np.random.rand(1000) B = comb(range(1000),n) print np.sum(np.array([np.prod(A[i,]) for i in B])) </code></pre> <p>The code is fairly condensed, but is kinda simple. It first makes an iterator object containing all the unique combinations of the indices of A, and then uses those tuples in an (ab)use of numpy's array slicing notation to get reference those indices, find the product there, and then sum it all together.</p> <p>The greatest weakness of this code, I would guess, is the list comprehension, since it doesn't make use of numpy functions. As it stands, the code runs fast enough for size-2 combinations, but falls flat for anything higher. I would like it to at least be tractable for size-3 combinations, but as it stands, this code doesn't make the cut.</p> <p>Any suggestions or things to look into would be greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T20:17:17.520", "Id": "391506", "Score": "0", "body": "This is a notoriously non-trivial problem. Start [here](https://math.stackexchange.com/questions/30807/algorithms-for-computing-an-elementary-symmetric-polynomial)" } ]
[ { "body": "<p>Some suggestions to <em>simplify</em> the code:</p>\n\n<ul>\n<li>Instead of creating all possible combinations of <em>indices</em> and using these\nas subscript into the list, <code>comb(A, n)</code> can be used directly to get all n-element combinations.</li>\n<li>There is no need to create an in...
{ "AcceptedAnswerId": "203119", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T14:56:07.007", "Id": "203109", "Score": "2", "Tags": [ "python", "numpy", "python-2.x" ], "Title": "Code to find the sum of the product of all size-n combinations of an array" }
203109
<p>This code builds on the code in <a href="https://codereview.stackexchange.com/q/200495/120114">the previous iteration</a>. All of the following tests should work:</p> <pre><code>let myTree = Tree.from({a:{b:{k:2}}}); myTree.a.b; // { k: 2 } myTree.a === myTree.a.b.__parent__; // true // adding properties myTree.c = {d:{l:5}}; // {d: {l: 5}} myTree.c.__parent__ === myTree; // true myTree.a.b.__parent__ = myTree.c; // {d: {l: 5}} myTree.c.b.k; // 2 myTree.a.b; // undefined // moving branches to other trees. let anotherTree = new Tree(); myTree.a.l = 3; myTree.a.l; // 3 myTree.a.__parent__ = anotherTree; anotherTree.a; // {l: 3} myTree.a; // undefined anotherTree.a.__parent__ === anotherTree; // true </code></pre> <p>It also introduces the <code>Fragment</code> class, which behaves both like a tree and a branch in the fact that it can be assigned to both and have child properties.</p> <p>Upon an object or primitive being assigned, it is immediately converted to a branch or a leaf, respectively.</p> <p>All leaves are dynamically inherited.</p> <p>Code:</p> <pre><code>const [Tree, Fragment] = ( function(){ const LeafCache = Object.create( null ), genLeaf = ( CLASS ) =&gt; { return LeafCache[CLASS.name] || LeafCache[CLASS.name] = eval( `class Leaf extends ${CLASS.name} { constructor(val) { super(val); } }; Leaf.prototype.__isleaf__ = true; Leaf` ); }, TARGET = Symbol( '__target__' ), HANDLER = Symbol( '__handler__' ), PROXY = Symbol( '__proxy__' ), ISTREE = Symbol( '__istree__' ), { assign, defineProperty, entries, setPrototypeOf } = Object, { hasOwnProperty } = {}, convert = ( obj ) =&gt; { let res = obj instanceof Branch ? obj : new Branch( obj ); for( const key in obj ) { const value = obj[key]; if( hasOwnProperty.call( obj, key ) ) { if( '__isfragment__' !== key ) { if( typeof value === 'object' ) { res[key] = convert( value ); Object.defineProperty( res[key], '__parent__', { value: res[PROXY], configurable: false, protected: false } ); } else { let val; res[key] = new Proxy( val = new ( genLeaf( value.constructor ) )( value ), genHandler( val ) ); } } } } return res; }, getKey = ( obj, val ) =&gt; { for( const key in obj ) { const value = obj[key]; if( value[TARGET] === val ) { return key; } } }; let genHandler = ( _target ) =&gt; { return ( function(){ let res; const _raw = __raw__.bind( _target ), _keys = { '__raw__': _raw, [ISTREE]: true, [TARGET]: _target, get [PROXY]() { return res.proxy; }, get [HANDLER]() { return res; } }; res = { set: ( target, prop, value ) =&gt; { if( prop === '__parent__' ) { if( _keys[PROXY] instanceof Fragment ) { throw TypeError( 'Cannot set __parent__ on fragments.' ); } else if( typeof value === 'object' &amp;&amp; value[ISTREE] ) { const key = getKey( target.__parent__, target ); if( target.__parent__[key] ) { delete target.__parent__[key]; } value[key] = target; return value; } else { throw TypeError( 'Cannot assign __parent__ to a non-tree value' ); } } if( typeof value === 'object' &amp;&amp; value.constructor.name !== 'Leaf' ) { value = convert( value ); if( value[PROXY] instanceof Tree ) { throw TypeError( 'Cannot have a tree as a child of another tree.' ); } value = convert( value ); defineProperty( value, '__parent__', { value: _keys[PROXY], configurable: false, writable: true } ); } else if ( typeof value !== 'object' ) { let val; value = new Proxy( val = new ( genLeaf( value.constructor ) )( value ), genHandler( val ) ); } target[prop] = value; return value; }, get: ( target, prop ) =&gt; { if( prop === 'toJSON' ) { return _raw; } if( [HANDLER, PROXY, '__raw__', ISTREE, TARGET].includes( prop ) ) { return _keys[prop]; } return target[prop]; } }; return res; } )(); }; /** * Get the raw value of the tree, without all that proxy stuff. * @returns {Object} The raw object. Please not that objects will not be the same instances. * @memberof Tree# */ function __raw__() { let res = setPrototypeOf( {}, this.__proto__ ); for( const key in this ) { if( key.slice( 0, 2 ) === key.slice( -2 ) &amp;&amp; key.slice( -2 ) === '__' ) { continue; } else { const value = this[key]; if( hasOwnProperty.call( this, key ) ) { res[key] = typeof value === 'object' ? __raw__.call( value[TARGET] ) : value; } } } return res; } /** * A class that enables navigation from child properties to parent. WIP - currently figuring out how to make new properties. * For all purposes this functions as intended, but it doesn't print well in the console. It even perserves prototypes. * @property {(Branch|Leaf)} * Properties. */ class Tree { /** * Constructs a new Tree instance. * @constructs Tree */ constructor() { return Tree.from( {} ); } /** * Attempt to create a tree from an existing object. * @param {Object} obj The object to convert to a tree. * @throws {TypeError} You probably passed it a primitive. * @returns {Tree} The resulting tree. */ static from( obj ) { const self = {}, res = new Proxy( setPrototypeOf( self, obj.__proto__ ), genHandler( self ) ); defineProperty( res[HANDLER], 'proxy', { value: res, configurable: false, protected: true } ); if( typeof obj !== 'object' ) { throw TypeError( 'Tree expects an object' ); } else { for( const key in obj ) { const value = obj[key]; let val; res[key] = typeof value === 'object' ? convert( value ) : new Proxy( val = new ( genLeaf( value.constructor ) )( value ), genHandler( val ) ); console.log( res[key][TARGET] ); } } defineProperty( res, '__istree__', { value: true, configurable: false, protected: true } ); return res; } static [Symbol.hasInstance]( obj ) { return obj[ISTREE] &amp;&amp; obj.__istree__ || false; } } /** * A class that behaves similar to a tree and similar to a branch. It can be added to a tree like a branch. * @class */ class Fragment { /** * Construct a new fragment. * @constructs Fragment */ constructor() { return Fragment.from( {} ); } /** * Attempt to make a fragment from an existing object. * @param {Object} obj The object to use. * @returns {Fragment} The resulting fragment. */ static from( obj ) { const self = {}, res = new Proxy( setPrototypeOf( self, obj.__proto__ ), genHandler( self ) ); defineProperty( res[HANDLER], 'proxy', { value: res, configurable: false, protected: true } ); if( typeof obj !== 'object' ) { throw TypeError( 'Tree expects an object' ); } else { for( let key in obj ) { let value = obj[key]; res[key] = typeof value === 'object' ? convert( value ) : value; } } defineProperty( res, '__isfragment__', { value: true, configurable: false, protected: true } ); return res; } static [Symbol.hasInstance]( obj ) { return obj[ISTREE] &amp;&amp; obj.__isfragment__ || false; } } class Branch { constructor( obj ) { let self = {}, res = new Proxy( setPrototypeOf( self, obj.__proto__ ), genHandler( self ) ); defineProperty( res[HANDLER], 'proxy', { value: res, configurable: false, protected: true } ); defineProperty( res, '__isbranch__', { value: true, configurable: false, protected: true } ); return res; } static [Symbol.hasInstance]( obj ) { return obj[ISTREE] &amp;&amp; obj.__isbranch__ || false; } } return [Tree, Fragment]; } )(); /** * A class that shows that an item is a terminal node. Parent properties cannot be accessed by this node. * @alias Brance * @class Leaf * @extends Primitive */ /** * A class that simply shows that it is an inner object of a Tree. * @alias Branch * @class Branch * @property {(Tree|Branch)} __parent__ The parent element. This can be changed to move the object to another tree or branch. */ </code></pre> <p><sub>This is an iterative review. Previous iteration: <a href="https://codereview.stackexchange.com/q/200495/168361">Traversing the parent-child relationship between objects</a></sub></p>
[]
[ { "body": "<h2>Errors</h2>\n\n<p>I tried this both in jsFiddle (with and without JS 1.7 and Babel) as well as NodeJS but saw a few errors. The first one was:</p>\n\n<blockquote>\n<pre><code> return LeafCache[CLASS.name] || LeafCache[CLASS.name] = eval( `class Leaf extends ${CLASS.name} {\n ^^^^^^^^^^^...
{ "AcceptedAnswerId": "204423", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T15:09:12.753", "Id": "203111", "Score": "1", "Tags": [ "javascript", "object-oriented", "tree", "ecmascript-6" ], "Title": "Traversing the Parent-child relationship between objects: Part 2" }
203111
<p>Basically, this code splits a string into substrings based on a token. The <code>printf</code> call is just a placeholder for something useful for each substring and can be substituted for something else, like a spell checker, profanity checker, etc...</p> <p>With the input <code>("The quick brown fox jumps over the lazy dog", 44, ' ')</code> the output is:</p> <pre><code>Processed: The Processed: quick Processed: brown Processed: fox Processed: jumps Processed: over Processed: the Processed: lazy Processed: dog </code></pre> <p>Code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;sal.h&gt; /** * Splits a string into substrings delimited by a token. * Returns the number of substrings found in the string. */ size_t __cdecl splitstring( _In_reads_or_z_(len) char *str, _In_ size_t len, _In_ char token ) { char *temp = malloc(len + 1), *p = str, *q = str; memset(temp, 0, len); size_t i, cnt = 0; if (!temp) { _wperror(L"malloc"); exit(EXIT_FAILURE); } for (i = 0; i &lt; len + 1; i++) { if (str[i] == token || str[i] == '\0') { q = &amp;str[i]; strncpy_s(temp, len, p, q - p); printf("Processed: %s\n", temp); memset(temp, 0, len); cnt++; } // Useful property of boolean expressions in C: they are always either 1 or 0 // Adjust p to point either to the next space or the next letter depending on if // it's the first word being processed. p = q + (p != &amp;str[0]); if (!*p) break; } free(temp); temp = NULL; return cnt; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T15:47:55.090", "Id": "391470", "Score": "0", "body": "What's `<sal.h>`? That's not a standard library header - does it belong to some library? I'm guessing, given `__cdecl` that it might be [tag:winapi] or the like?" }, { ...
[ { "body": "<h1>Check allocated pointers <em>before</em> using them</h1>\n<p>It's good that we have a <code>if (!temp)</code> check, but unfortunately we used <code>temp</code> as argument to <code>memset()</code> before we did the check, so it's too late!</p>\n<p>We could (and should) use <code>calloc()</code> ...
{ "AcceptedAnswerId": "203120", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T15:38:05.710", "Id": "203115", "Score": "2", "Tags": [ "c", "strings" ], "Title": "Split a string based on a delimiter in C" }
203115
<p><strong>EDIT:</strong> Link to the github, </p> <p><a href="https://github.com/Evanml2030/Excel-SpaceInvader" rel="nofollow noreferrer">https://github.com/Evanml2030/Excel-SpaceInvader</a></p> <p><strong>THE README (APPLIES HERE TOO):</strong></p> <p>VBA version of a classic game</p> <p>Yes, I know that "Missile" is repeatedly written as "Missle".</p> <p>It will not run unless you change the pathways to images that will be uploaded into form controls. You can find these inside Ship.cls, MissleFactory, AlienFactory, CometFactory, StarFactory</p> <p>Obviously needs some basic refactoring, finished over weekend and haven't had time to fix up. Will do if not during week, then definitely this weekend. I am thinking of implementing an ShipWeapons interface, to allow of different sort of weapons. Maybe "heat seeking" style missile or something. Also shields? More types of spaceObjects. And I was thinking of making some spaceObjects indestructible. Maybe make some spaceObjects, i.e. the sun, increase in size momentarily after being struck.</p> <p>Etc Etc.</p> <p><strong>MAIN:</strong></p> <p>There are a ton of modules and classes here but I will try my best to keep this organized. </p> <p>The following classes have, Attribute VB_PredeclaredId = True: MissleCntrlsCol, MissleCount, MissleObjectsDataCol, Ship, SpaceObjectsCntrlsCol, SpaceObjectCount, SpaceObjectsDataCol</p> <p>Also please note that you must change the pathway to image in each of the factories as well as inside the ship class initializer.</p> <p><a href="https://i.stack.imgur.com/GtKWF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GtKWF.png" alt="enter image description here"></a></p> <blockquote> <p><strong>Userform Code:</strong></p> </blockquote> <p>Really want to try and follow the MVP model here, keeping userform dumb.</p> <pre><code>Option Explicit Private Sub UserForm_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) Dim passVal As Long Select Case KeyCode Case "37", "39", "32" passVal = CInt(KeyCode) GameLogic.HandleSendKeys Me, passVal End Select End Sub </code></pre> <blockquote> <p><strong>Modules:</strong></p> </blockquote> <p><strong>GameLogic</strong></p> <pre><code>Option Explicit Private Declare PtrSafe Function timeGetTime Lib "winmm.dll" () As Long Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr) Sub RunGame() Dim newBoard As GameBoard Dim shipObj As ship Dim ShipCntrl As Control Dim startTime As Long Dim endTime As Long Dim x As Long Set newBoard = New GameBoard newBoard.Show vbModeless ScaleItems.MaxSize = 60 Set ShipCntrl = SHLoadShipOntoGameBoard.LoadShipOntoBoard(newBoard) startTime = timeGetTime Do While x &lt; 100 endTime = timeGetTime If (endTime - startTime) &gt; 2000 Then startTime = endTime SOLoadSpaceObjectOntoGameBoard.LoadSpaceObjectOntoBoard newBoard End If CollisionsMissleSpaceObject.HandleMissleSpaceObjectCollisions newBoard If CollisionsShipSpaceObject.HandleShipSpaceObjectCollisions(newBoard) Then Exit Do SOMoveSpaceObjects.MoveSpaceObjects newBoard MMoveMissles.MoveMissleObjects newBoard DoEvents Sleep 25 Loop End Sub Public Sub HandleSendKeys(ByRef board As GameBoard, ByRef caseNum As Long) Select Case caseNum Case "37" SHMoveShip.moveShipLeft board Case "39" SHMoveShip.moveShipRight board Case "32" MLoadMissleObjectOntoBoard.LoadMissleObjectOntoBoard board MissleCount.IncrementMissleCount ChangeBoardLabelMissleCount board End Select End Sub Private Sub ChangeBoardLabelMissleCount(ByRef board As GameBoard) board.MissleCount.Caption = CStr(25 - MissleCount.Count) End Sub </code></pre> <p><strong>CollisionsMissleSpaceObject:</strong></p> <pre><code>Option Explicit Sub HandleMissleSpaceObjectCollisions(ByRef board As GameBoard) Dim spaceObject As ISpaceObject Dim spaceObjectCntrl As Control Dim missle As missle Dim missleCntrl As Control Dim indexMissle As Long Dim indexSpaceObject As Long For indexMissle = MissleObjectsDataCol.Count To 1 Step -1 Set missle = MissleObjectsDataCol.Item(indexMissle) Set missleCntrl = MissleCntrlsCol.Item(indexMissle) For indexSpaceObject = SpaceObjectDataCol.Count To 1 Step -1 Set spaceObject = SpaceObjectDataCol.Item(indexSpaceObject) Set spaceObjectCntrl = SpaceObjectCntrlsCol.Item(indexSpaceObject) If CheckIfCollided(missle, spaceObject) Then MDestroyMissleObject.DestroyMissleObject board, missle, indexMissle SODestroySpaceObject.DestroySpaceObject board, spaceObject, indexSpaceObject End If Next indexSpaceObject Next indexMissle End Sub Private Function CheckIfCollided(ByRef missle As missle, ByRef spaceObject As ISpaceObject) As Boolean Dim hOverlap As Boolean Dim vOverlap As Boolean hOverlap = (missle.left - spaceObject.width &lt; spaceObject.left) And (spaceObject.left &lt; missle.left + missle.width) vOverlap = (missle.top - spaceObject.height &lt; spaceObject.top) And (spaceObject.top &lt; missle.top + missle.height) CheckIfCollided = hOverlap And vOverlap End Function </code></pre> <p><strong>CollisionsShipSpaceObject:</strong></p> <pre><code>Option Explicit Function HandleShipSpaceObjectCollisions(ByRef board As GameBoard) As Boolean Dim spaceObject As ISpaceObject Dim spaceObjectCntrl As Control Dim indexSpaceObject As Long For indexSpaceObject = SpaceObjectDataCol.Count To 1 Step -1 Set spaceObject = SpaceObjectDataCol.Item(indexSpaceObject) Set spaceObjectCntrl = SpaceObjectCntrlsCol.Item(indexSpaceObject) If CheckIfCollided(spaceObject) Then HandleShipSpaceObjectCollisions = True End If Next indexSpaceObject End Function Private Function CheckIfCollided(ByRef spaceObject As ISpaceObject) As Boolean Dim hOverlap As Boolean Dim vOverlap As Boolean hOverlap = (ship.left - spaceObject.width &lt; spaceObject.left) And (spaceObject.left &lt; ship.left + ship.width) vOverlap = (ship.top - spaceObject.height &lt; spaceObject.top) And (spaceObject.top &lt; ship.top + ship.height) CheckIfCollided = hOverlap And vOverlap End Function </code></pre> <p><strong>DestroyMissleObject:</strong></p> <pre><code>Option Explicit Sub DestroyMissleObject(ByRef board As GameBoard, ByRef missleObject As missle, ByRef index As Long) board.Controls.Remove missleObject.ImageName MissleObjectsDataCol.Remove index MissleCntrlsCol.Remove index End Sub </code></pre> <p><strong>LoadMissleObjectOntoBoard:</strong></p> <pre><code>Option Explicit Sub LoadMissleObjectOntoBoard(ByRef board As GameBoard) Dim missleObject As missle Dim cntrl As Control Set missleObject = MMissleFactory.NewMissle Set cntrl = AddMissleObjectImgControlToBoard(board, missleObject) InitalizeMissleObjectImgControl cntrl, missleObject AddMissleObjectToDataCol missleObject AddMissleObjectCntrlToCntrlsCol cntrl End Sub Private Function AddMissleObjectImgControlToBoard(ByRef board As GameBoard, ByRef missleObject As Object) As Control Set AddMissleObjectImgControlToBoard = board.Controls.Add("Forms.Image.1", missleObject.ImageName) End Function Private Sub InitalizeMissleObjectImgControl(ByRef cntrl As Control, ByRef missleObject As missle) With cntrl .left = missleObject.left .top = missleObject.top .height = missleObject.height .width = missleObject.width .Picture = LoadPicture(missleObject.ImgPathWay) .PictureSizeMode = 1 End With End Sub Private Sub AddMissleObjectToDataCol(ByRef missleObject As missle) MissleObjectsDataCol.Add missleObject End Sub Private Sub AddMissleObjectCntrlToCntrlsCol(ByRef cntrl As Control) MissleCntrlsCol.Add cntrl End Sub </code></pre> <p><strong>MMissleFactory:</strong></p> <pre><code>Option Explicit Public Function NewMissle() As missle Dim width As Long Dim height As Long width = ScaleItems.MaxSize / 2 height = ScaleItems.MaxSize / 2.15 IncrementMissleCount With New missle .ImgPathWay = "Z:\Desktop Storage\EXCEL &amp; C# PRACTICE\SpaceInvaders\laserBeam.jpg" .SetInitialLeft ((ship.width - width) / 2) + ship.left .SetInitialTop ship.top - height .height = height .width = width .ImageName = "Missle" &amp; CStr(MissleCount.Count) Set NewMissle = .Self End With End Function Private Sub IncrementMissleCount() MissleCount.IncrementMissleCount End Sub </code></pre> <p><strong>MMoveMissles:</strong></p> <pre><code>Option Explicit Sub MoveMissleObjects(ByRef board As GameBoard) Dim missleObject As missle Dim missleObjectCntrl As Control Dim index As Long For index = MissleObjectsDataCol.Count To 1 Step -1 Set missleObject = MissleObjectsDataCol.Item(index) Set missleObjectCntrl = MissleCntrlsCol.Item(index) If MissleObjectOutOfBounds(board, missleObject) Then MDestroyMissleObject.DestroyMissleObject board, missleObject, index Set missleObject = Nothing Set missleObjectCntrl = Nothing Else MoveMissleObject missleObject, missleObjectCntrl End If Next index End Sub Private Function MissleObjectOutOfBounds(ByRef board As GameBoard, ByRef missleObject As missle) As Boolean If missleObject.top = 0 Then MissleObjectOutOfBounds = True Else MissleObjectOutOfBounds = False End If End Function Private Sub MoveMissleObject(ByRef missleObject As missle, ByRef missleObjectCntrl As Control) missleObject.top = missleObject.top - 1 missleObjectCntrl.top = missleObject.top End Sub </code></pre> <p><strong>SHLoadShipOntoGameBoard:</strong></p> <pre><code>Public Function moveShipLeft(ByRef board As GameBoard) Dim ShipCntrl As Control Set ShipCntrl = board.Controls(ship.ImageName) If ship.left &gt; 0 Then ship.left = ship.left - 5 ShipCntrl.left = ship.left End If End Function Function moveShipRight(ByRef board As GameBoard) Dim ShipCntrl As Control Set ShipCntrl = board.Controls(ship.ImageName) If ship.left + ship.width &lt; board.width Then ship.left = ship.left + 5 ShipCntrl.left = ship.left Else End If End Function </code></pre> <p><strong>SOAlienFactory:</strong></p> <pre><code>Option Explicit Public Function NewAlien(ByRef board As GameBoard) As SpaceObjectAlien Dim width As Long Dim height As Long width = ScaleItems.MaxSize / 1.5 height = ScaleItems.MaxSize / 1.5 IncrementSpaceObjectCount With New SpaceObjectAlien .ImgPathWay = "Z:\Desktop Storage\EXCEL &amp; C# PRACTICE\SpaceInvaders\alienShip.jpg" .SetInitialLeft Application.WorksheetFunction.RandBetween(0, board.width - width) .SetInitialTop 0 .height = height .width = width .ImageName = "SpaceObject" &amp; CStr(SpaceObjectCount.Count) Set NewAlien = .Self End With End Function Private Sub IncrementSpaceObjectCount() SpaceObjectCount.IncrementCount End Sub </code></pre> <p><strong>SOCometFactory:</strong></p> <pre><code>Option Explicit Public Function NewComet(ByRef board As GameBoard) As SpaceObjectComet Dim width As Long Dim height As Long width = ScaleItems.MaxSize / 1.75 height = ScaleItems.MaxSize / 1.75 IncrementSpaceObjectCount With New SpaceObjectComet .ImgPathWay = "Z:\Desktop Storage\EXCEL &amp; C# PRACTICE\SpaceInvaders\regComet.jpg" .SetInitialLeft Application.WorksheetFunction.RandBetween(0, board.width - width) .SetInitialTop 0 .width = width .height = height .ImageName = "SpaceObject" &amp; CStr(SpaceObjectCount.Count) Set NewComet = .Self End With End Function Private Sub IncrementSpaceObjectCount() SpaceObjectCount.IncrementCount End Sub </code></pre> <p><strong>SOStarFactory:</strong></p> <pre><code>Option Explicit Public Function NewStar(ByRef board As GameBoard) As SpaceObjectStar Dim width As Long Dim height As Long width = ScaleItems.MaxSize height = ScaleItems.MaxSize IncrementSpaceObjectCount With New SpaceObjectStar .ImgPathWay = "Z:\Desktop Storage\EXCEL &amp; C# PRACTICE\SpaceInvaders\yellowStar.jpg" .SetInitialLeft Application.WorksheetFunction.RandBetween(0, board.width - width) .SetInitialTop 0 .width = width .height = height .ImageName = "SpaceObject" &amp; CStr(SpaceObjectCount.Count) Set NewStar = .Self End With End Function Private Sub IncrementSpaceObjectCount() SpaceObjectCount.IncrementCount End Sub </code></pre> <p><strong>SODestroySpaceObject:</strong></p> <pre><code>Option Explicit Sub DestroySpaceObject(ByRef board As GameBoard, ByRef spaceObject As ISpaceObject, ByRef index As Long) board.Controls.Remove spaceObject.ImageName SpaceObjectDataCol.Remove index SpaceObjectCntrlsCol.Remove index End Sub </code></pre> <p><strong>LoadSpaceObjectOntoBoard:</strong></p> <pre><code>Option Explicit Sub DestroySpaceObject(ByRef board As GameBoard, ByRef spaceObject As ISpaceObject, ByRef index As Long) board.Controls.Remove spaceObject.ImageName SpaceObjectDataCol.Remove index SpaceObjectCntrlsCol.Remove index End Sub </code></pre> <p><strong>SOMOveSpaceObjects:</strong></p> <pre><code>Option Explicit Sub MoveSpaceObjects(ByRef board As GameBoard) Dim spaceObject As ISpaceObject Dim spaceObjectCntrl As Control Dim index As Long For index = SpaceObjectDataCol.Count To 1 Step -1 Set spaceObject = SpaceObjectDataCol.Item(index) Set spaceObjectCntrl = SpaceObjectCntrlsCol.Item(index) If SpaceObjectOutOfBounds(board, spaceObject) Then SODestroySpaceObject.DestroySpaceObject board, spaceObject, index Set spaceObject = Nothing Set spaceObjectCntrl = Nothing Else MoveSpaceObject spaceObject, spaceObjectCntrl End If Next index End Sub Private Function SpaceObjectOutOfBounds(ByRef board As GameBoard, ByRef spaceObject As ISpaceObject) As Boolean If spaceObject.top + spaceObject.height &gt; board.height Then SpaceObjectOutOfBounds = True Else SpaceObjectOutOfBounds = False End If End Function Private Sub MoveSpaceObject(ByRef spaceObject As ISpaceObject, ByRef spaceObjectCntrl As Control) spaceObject.top = spaceObject.top + 1 spaceObjectCntrl.top = spaceObject.top End Sub </code></pre> <blockquote> <p><strong>CLASS MODULES:</strong></p> </blockquote> <p><strong>ISpaceObject:</strong></p> <pre><code>Option Explicit Public Property Let left(ByRef changeLeft As Long) End Property Public Property Get left() As Long End Property Public Property Let top(ByRef changeTop As Long) End Property Public Property Get top() As Long End Property Public Property Get ImageName() As String End Property Public Property Get width() As Long End Property Public Property Get height() As Long End Property Public Property Get ImagePathway() As String End Property </code></pre> <p><strong>Missle:</strong></p> <pre><code>Option Explicit Private Type MissleData left As Long top As Long ImgPathWay As String ImageName As String width As Long height As Long End Type Private this As MissleData Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Get Self() As missle Set Self = Me End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Property Let left(ByRef changeLeft As Long) this.left = changeLeft End Property Public Property Get left() As Long left = this.left End Property Public Property Let top(ByRef changeTop As Long) this.top = changeTop End Property Public Property Get top() As Long top = this.top End Property </code></pre> <p><strong>MissleCntrlsCol:</strong></p> <pre><code>Option Explicit Private MissleObjectsCntrls As Collection Private Sub Class_Initialize() Set MissleObjectsCntrls = New Collection End Sub Private Sub Class_Terminate() Set MissleObjectsCntrls = Nothing End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = MissleObjectsCntrls.[_NewEnum] End Property Public Sub Add(obj As Control) MissleObjectsCntrls.Add obj End Sub Public Sub Remove(index As Variant) MissleObjectsCntrls.Remove index End Sub Public Property Get Item(index As Variant) As Control Set Item = MissleObjectsCntrls.Item(index) End Property Property Get Count() As Long Count = MissleObjectsCntrls.Count End Property Public Sub Clear() Set MissleObjectsCntrls = New Collection End Sub </code></pre> <p><strong>MissleCount:</strong></p> <pre><code>Option Explicit Private pcount As Long Public Property Get Count() As Long Count = pcount End Property Public Property Let Count(ByRef value As Long) pcount = value End Property Public Sub IncrementMissleCount() pcount = pcount + 1 End Sub </code></pre> <p><strong>MissleObjectsDataCol:</strong></p> <pre><code>Option Explicit Private MissleObjectsData As Collection Private Sub Class_Initialize() Set MissleObjectsData = New Collection End Sub Private Sub Class_Terminate() Set MissleObjectsData = Nothing End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = MissleObjectsData.[_NewEnum] End Property Public Sub Add(obj As missle) MissleObjectsData.Add obj End Sub Public Sub Remove(index As Variant) MissleObjectsData.Remove index End Sub Public Property Get Item(index As Variant) As missle Set Item = MissleObjectsData.Item(index) End Property Property Get Count() As Long Count = MissleObjectsData.Count End Property Public Sub Clear() Set MissleObjectsData = New Collection End Sub </code></pre> <p><strong>ScaleItems:</strong></p> <pre><code>Option Explicit Private plargestSize As Long Public Property Get MaxSize() As Long MaxSize = plargestSize End Property Public Property Let MaxSize(ByRef value As Long) plargestSize = value End Property </code></pre> <p><strong>Ship:</strong></p> <pre><code>Option Explicit Private Type ShipData left As Long top As Long ImgPathWay As String ImageName As String width As Long height As Long Name As String End Type Private this As ShipData Private Sub Class_Initialize() this.ImgPathWay = "Z:\Desktop Storage\EXCEL &amp; C# PRACTICE\SpaceInvaders\spaceShip.jpg" SetInitialLeft GameBoard.width / 2 SetInitialTop GameBoard.height - (GameBoard.height / 8.5) this.width = ScaleItems.MaxSize this.height = ScaleItems.MaxSize this.ImageName = "Ship" End Sub Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Get Self() As SpaceObjectComet Set Self = Me End Property Public Property Let left(ByRef left As Long) this.left = left End Property Public Property Get left() As Long left = this.left End Property Public Property Let top(ByRef top As Long) this.height = height End Property Public Property Get top() As Long top = this.top End Property Public Property Let ImageName(ByRef ImageName As String) this.ImageName = height End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property </code></pre> <p><strong>Ship:</strong></p> <pre><code>Option Explicit Private Type ShipData left As Long top As Long ImgPathWay As String ImageName As String width As Long height As Long Name As String End Type Private this As ShipData Private Sub Class_Initialize() this.ImgPathWay = "Z:\Desktop Storage\EXCEL &amp; C# PRACTICE\SpaceInvaders\spaceShip.jpg" SetInitialLeft GameBoard.width / 2 SetInitialTop GameBoard.height - (GameBoard.height / 8.5) this.width = ScaleItems.MaxSize this.height = ScaleItems.MaxSize this.ImageName = "Ship" End Sub Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Get Self() As SpaceObjectComet Set Self = Me End Property Public Property Let left(ByRef left As Long) this.left = left End Property Public Property Get left() As Long left = this.left End Property Public Property Let top(ByRef top As Long) this.height = height End Property Public Property Get top() As Long top = this.top End Property Public Property Let ImageName(ByRef ImageName As String) this.ImageName = height End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property </code></pre> <p><strong>SpaceObjectAlien:</strong></p> <pre><code>Option Explicit Implements ISpaceObject Private Type AlienData left As Long top As Long ImgPathWay As String ImageName As String width As Long height As Long End Type Private this As AlienData Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Get Self() As SpaceObjectAlien Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Get ISpaceObject_ImageName() As String this.ImageName = ISpaceObject_ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property </code></pre> <p><strong>SpaceObjectCntrlsCol:</strong></p> <pre><code>Option Explicit Private SpaceObjectsCntrls As Collection Private Sub Class_Initialize() Set SpaceObjectsCntrls = New Collection End Sub Private Sub Class_Terminate() Set SpaceObjectsCntrls = Nothing End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = SpaceObjectsCntrls.[_NewEnum] End Property Public Sub Add(obj As Control) SpaceObjectsCntrls.Add obj End Sub Public Sub Remove(index As Variant) SpaceObjectsCntrls.Remove index End Sub Public Property Get Item(index As Variant) As Control Set Item = SpaceObjectsCntrls.Item(index) End Property Property Get Count() As Long Count = SpaceObjectsCntrls.Count End Property Public Sub Clear() Set SpaceObjectsCntrls = New Collection End Sub </code></pre> <p><strong>SpaceObjectComet:</strong></p> <pre><code>Option Explicit Implements ISpaceObject Private Type CometData left As Long top As Long ImgPathWay As String ImageName As String width As Long height As Long End Type Private this As CometData Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Get Self() As SpaceObjectComet Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Get ISpaceObject_ImageName() As String ISpaceObject_ImageName = this.ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property </code></pre> <p><strong>SpaceObjectCount:</strong></p> <pre><code>Option Explicit Private pcount As Long Public Property Get Count() As Long Count = pcount End Property Public Property Let Count(ByRef value As Long) pcount = value End Property Public Sub IncrementCount() pcount = pcount + 1 End Sub </code></pre> <p><strong>SpaceObjectDataCol:</strong></p> <pre><code>Option Explicit Private SpaceObjectsData As Collection Private Sub Class_Initialize() Set SpaceObjectsData = New Collection End Sub Private Sub Class_Terminate() Set SpaceObjectsData = Nothing End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = SpaceObjectsData.[_NewEnum] End Property Public Sub Add(obj As ISpaceObject) SpaceObjectsData.Add obj End Sub Public Sub Remove(index As Variant) SpaceObjectsData.Remove index End Sub Public Property Get Item(index As Variant) As ISpaceObject Set Item = SpaceObjectsData.Item(index) End Property Property Get Count() As Long Count = SpaceObjectsData.Count End Property Public Sub Clear() Set SpaceObjectsData = New Collection End Sub </code></pre> <p>SpaceObjectStar:</p> <pre><code>Option Explicit Implements ISpaceObject Private Type StarData left As Long top As Long ImgPathWay As String ImageName As String width As Long height As Long End Type Private this As StarData Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Get Self() As SpaceObjectStar Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Let ISpaceObject_ImageName(ByRef imageNameValue As String) this.ImageName = imageNameValue End Property Private Property Get ISpaceObject_ImageName() As String ISpaceObject_ImageName = this.ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property </code></pre> <p><a href="https://i.stack.imgur.com/t7Vw0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t7Vw0.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/7QDYp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7QDYp.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/2sioE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2sioE.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T17:57:40.600", "Id": "391485", "Score": "1", "body": "Do you have the full source code on GitHub or some other location that would make it easier to view the code in its native habitat?" }, { "ContentLicense": "CC BY-SA 4.0"...
[ { "body": "<h2>Architecture</h2>\n\n<p>I'll let other reviewers do more of the heavy lifting here, but there were a couple things that immediately stood out.</p>\n\n<hr>\n\n<p>I'm not sure I understand the purpose of wrapping the <code>Collection</code>'s in their own classes. You aren't adding any functionalit...
{ "AcceptedAnswerId": "203218", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T17:38:44.080", "Id": "203123", "Score": "8", "Tags": [ "beginner", "object-oriented", "game", "vba", "excel" ], "Title": "Space Invader Style Game Written In VBA" }
203123
<p><a href="http://www.fltk.org/" rel="nofollow noreferrer">FLTK</a> (pronounced "fulltick") is a cross-platform <a href="/questions/tagged/c%2b%2b" class="post-tag" title="show questions tagged &#39;c++&#39;" rel="tag">c++</a> <a href="/questions/tagged/gui" class="post-tag" title="show questions tagged &#39;gui&#39;" rel="tag">gui</a> toolkit for <a href="/questions/tagged/unix" class="post-tag" title="show questions tagged &#39;unix&#39;" rel="tag">unix</a>/<a href="/questions/tagged/linux" class="post-tag" title="show questions tagged &#39;linux&#39;" rel="tag">linux</a> (<a href="/questions/tagged/x11" class="post-tag" title="show questions tagged &#39;x11&#39;" rel="tag">x11</a>), Microsoft <a href="/questions/tagged/windows" class="post-tag" title="show questions tagged &#39;windows&#39;" rel="tag">windows</a>, and <a href="/questions/tagged/macos" class="post-tag" title="show questions tagged &#39;macos&#39;" rel="tag">macos</a>. FLTK provides modern GUI functionality without the bloat and supports 3D graphics via <a href="/questions/tagged/opengl" class="post-tag" title="show questions tagged &#39;opengl&#39;" rel="tag">opengl</a> and its built-in GLUT emulation.</p> <p>FLTK is designed to be small and modular enough to be statically linked, but works fine as a shared library. FLTK also includes an excellent UI builder called FLUID that can be used to create applications in minutes.</p> <p>FLTK is provided under the terms of the GNU Library Public License, Version 2 with exceptions that allow for static linking.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T17:52:59.567", "Id": "203126", "Score": "0", "Tags": null, "Title": null }
203126
FLTK is a cross-platform C++ GUI toolkit that supports 3D graphics.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T17:52:59.567", "Id": "203127", "Score": "0", "Tags": null, "Title": null }
203127
<p>I'm trying to figure out a way to make my code more readable and maintainable. While rewriting some ugly spaghetti code, I stumbled across this:</p> <pre><code>if($header !== null &amp;&amp; $fieldValue === null) { $errorMessage = $message . ': row ' . $row . ', header "' . $header . "\"\n"; } elseif($header === null &amp;&amp; $fieldValue !== null) { $errorMessage = $message . ': row ' . $row . ', field value "' . $fieldValue . "\"\n"; } elseif($header === null &amp;&amp; $fieldValue === null &amp;&amp; $row === null) { $errorMessage = $message . "\n"; } elseif($header !== null &amp;&amp; $fieldValue !== null) { $errorMessage = $message . ': row ' . $row . ', header "' . $header . '", value "' . $fieldValue . "\"\n"; } </code></pre> <p>It must be possible to make this more efficient, but how? Do I use a switch statement? Please enlighten me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T20:38:00.530", "Id": "391510", "Score": "2", "body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the titl...
[ { "body": "<p>Try something like this</p>\n\n<pre><code>&lt;?php\n\nfunction buildErrorMessage($message, $row = null, $header = null, $fieldValue = null) {\n\n if ($row) {\n $message .= \": row {$row}\";\n }\n\n if ($header) {\n $message .= \", header {$header}\";\n }\n\n if ($fie...
{ "AcceptedAnswerId": "203139", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T19:51:36.677", "Id": "203136", "Score": "0", "Tags": [ "php", "strings" ], "Title": "Prevent multiple ifelse statements in php" }
203136
<p>I did this <a href="https://codepen.io/edgarordonez/pen/dqRWLg" rel="nofollow noreferrer">Codepen</a> to combine all the columns from one matrix in JS.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const matrix = [ ['a', 'a', 'a'], ['b', 'b', 'b'], ['c', 'c', 'c'] ]; const combineMatrixColumns = (matrix) =&gt; { const biggest = matrix.reduce((acc, arr) =&gt; acc.length &lt; arr.length ? arr : acc, []); return biggest.reduce((acc, item, index) =&gt; { matrix.forEach(item =&gt; item[index] ? acc = [...acc, item[index]] : null) return acc; }, []) }; const result = combineMatrixColumns(matrix) console.log(result)</code></pre> </div> </div> </p> <p>For this input, the expected output as a single array with each column combined:</p> <pre><code>["a", "b", "c", "a", "b", "c", "a", "b", "c"] </code></pre> <p>My question is: You know a better approach to do it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-14T12:40:08.340", "Id": "392776", "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 y...
[ { "body": "<p>You can simply use two nested for loops for this, which makes it implementation much more simpler.Plus this helps you to avoid creating a map or performing concatenation operations. The below code is based on the logic of transposing the matrix. </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" ...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T19:26:43.730", "Id": "203146", "Score": "-1", "Tags": [ "javascript", "matrix", "ecmascript-6" ], "Title": "Combine Matrix Columns JavaScript" }
203146
<p>A long time ago I <a href="https://codereview.stackexchange.com/questions/168815/walking-git-history">implemented some code to walk the git commit graph</a>. I recently updated the accompanying analytics part of the code base to follow file moves/renames in order to get a more accurate count of the number of times a particular file was committed.</p> <p>Here's the original implementation of the commit count function. It naively stops tracking the number of commits after a file was renamed.(<em>Not</em> for review, just here for historical context.)</p> <blockquote> <pre><code>public static IEnumerable&lt;PathCount&gt; CountFileChanges(IEnumerable&lt;(Commit, TreeEntryChanges)&gt; diffs) { return diffs .GroupBy&lt;(Commit Commit, TreeEntryChanges Diff), string&gt;(c =&gt; c.Diff.Path) .Select(x =&gt; new PathCount(x.Key, x.Count())) .OrderByDescending(s =&gt; s.Count); } </code></pre> </blockquote> <p>This is my first implementation that correctly aggregates the commit counts for a file, regardless of renames.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using LibGit2Sharp; namespace GitNStats.Core { public delegate bool DiffFilterPredicate((Commit Commit, TreeEntryChanges TreeEntryChanges) diff); public static class Analysis { public static IEnumerable&lt;PathCount&gt; CountFileChanges(IEnumerable&lt;(Commit, TreeEntryChanges)&gt; diffs) { return diffs.Aggregate&lt;(Commit Commit, TreeEntryChanges Diff), Dictionary&lt;string, int&gt;&gt;( new Dictionary&lt;string, int&gt;(), //filename, count (acc, x) =&gt; { /* OldPath == NewPath when file was created or removed, so this it's okay to just always use OldPath */ acc[x.Diff.Path] = acc.GetOrDefault(x.Diff.OldPath, 0) + 1; if (x.Diff.Status == ChangeKind.Renamed) { acc.Remove(x.Diff.OldPath); } return acc; } ) .Select(x =&gt; new PathCount(x.Key, x.Value)) .OrderByDescending(s =&gt; s.Count); } } static class DictionaryExtensions { public static V GetOrDefault&lt;K,V&gt;(this Dictionary&lt;K,V&gt; dictionary, K key, V defaultValue) { return dictionary.TryGetValue(key, out V value) ? value : defaultValue; } } } </code></pre> <p>I was unhappy with this because I'm directly modifying the state of the accumulator in the fold (<code>Aggregate</code>) operation, so I implemented the immutable version below.</p> <pre><code>public static IEnumerable&lt;PathCount&gt; CountFileChanges(IEnumerable&lt;(Commit, TreeEntryChanges)&gt; diffs) { // Union must take an IEnumerable IEnumerable&lt;KeyValuePair&lt;K, V&gt;&gt; KeyValuePairEnumerable&lt;K, V&gt;(K key, V value) =&gt; Enumerable.Repeat(new KeyValuePair&lt;K, V&gt;(key, value), 1); IEnumerable&lt;KeyValuePair&lt;string, int&gt;&gt; IncrementedPathCount(Dictionary&lt;string, int&gt; pathcounts, string currentPath, string lastPath) =&gt; KeyValuePairEnumerable(currentPath, pathcounts.GetOrDefault(lastPath, 0) + 1); bool NotRenamed(KeyValuePair&lt;string, int&gt; kv, TreeEntryChanges diff) =&gt; diff.Status != ChangeKind.Renamed || (diff.Status == ChangeKind.Renamed &amp;&amp; kv.Key != diff.OldPath); return diffs.Aggregate&lt;(Commit Commit, TreeEntryChanges Diff), Dictionary&lt;string, int&gt;&gt;( new Dictionary&lt;string, int&gt;(), //filename, count (acc, x) =&gt; acc.Where(kv =&gt; kv.Key != x.Diff.Path) //All records except the current one .Union(IncrementedPathCount(acc, x.Diff.Path, x.Diff.OldPath)) //Plus the current one, renamed if applicable .Where(kv =&gt; NotRenamed(kv, x.Diff)) //Strip away obsolete file names .ToDictionary(kv =&gt; kv.Key, kv =&gt; kv.Value) ) .Select(x =&gt; new PathCount(x.Key, x.Value)) .OrderByDescending(s =&gt; s.Count); } </code></pre> <p>But I honestly don't know if the second, more functional implementation is any better. It is now immutable, but I think I might have just muddied the waters and made the code harder to follow. The first version was stateful, but perhaps more simple and easy to follow. Thoughts?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T10:04:23.353", "Id": "391589", "Score": "0", "body": "So you're basically running a `git log --follow | wc -l` for every file in your working tree? That seems like a good way to kill time :)" }, { "ContentLicense": "CC BY-SA...
[ { "body": "<p>I was going to say that this shouldn't be done in C#, but then after some thought last night, I came up with a really dirty idea.</p>\n\n<p>You're basically trying to get the count of things that happened with a file, right? So if it was renamed, that's a thing, if it was created/removed, that's a...
{ "AcceptedAnswerId": "203185", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T23:46:25.660", "Id": "203149", "Score": "11", "Tags": [ "c#", "functional-programming", "comparative-review", "git" ], "Title": "Counting times a file was committed to Git" }
203149
<p>In a recent project I worked on we faced some issues due to an excess of parallelization (thousands of threads were created and the overall result was a degradation of performance and several spikes in CPU usage).</p> <p>What we needed to solve this problem was a way to apply an asynchronous operation to each item of a sequence in a parallel fashion, with the possibility of specifying a maximum degree of parallelism.</p> <p>By looking at <a href="https://stackoverflow.com/questions/15136542/parallel-foreach-with-asynchronous-lambda">this Stack Overflow question</a> I jumped into <a href="https://blogs.msdn.microsoft.com/pfxteam/2012/03/05/implementing-a-simple-foreachasync-part-2/" rel="noreferrer">Stephan Toub's ForEachAsync</a>. Starting from there I implemented the following extension methods:</p> <pre><code>using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Linq; namespace Lib.Concurrency.Extensions { /// &lt;summary&gt; /// Extension methods for enumerables /// &lt;/summary&gt; public static class EnumerableExtensions { /// &lt;summary&gt; /// Executes an asynchronous operation for each item inside a source sequence. These operations are run concurrently in a parallel fashion. The invokation returns a task which completes when all of the asynchronous operations (one for each item inside the source sequence) complete. It is possible to constrain the maximum number of parallel operations. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the items inside &lt;paramref name="source"/&gt;&lt;/typeparam&gt; /// &lt;param name="source"&gt;The source sequence&lt;/param&gt; /// &lt;param name="maxDegreeOfParallelism"&gt;The maximum number of operations that are able to run in parallel&lt;/param&gt; /// &lt;param name="operation"&gt;The asynchronous operation to be executed for each item inside &lt;paramref name="source"/&gt;&lt;/param&gt; /// &lt;returns&gt;A task which completes when all of the asynchronous operations (one for each item inside &lt;paramref name="source"/&gt;) complete&lt;/returns&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="source"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="operation"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt;&lt;paramrefname="maxDegreeOfParallelism"/&gt; is less than or equal to zero&lt;/exception&gt; public static Task ForEachAsync&lt;T&gt;( this IEnumerable&lt;T&gt; source, int maxDegreeOfParallelism, Func&lt;T, Task&gt; operation) { if (source == null) throw new ArgumentNullException(nameof(source)); if (operation == null) throw new ArgumentNullException(nameof(operation)); EnsureValidMaxDegreeOfParallelism(maxDegreeOfParallelism); var tasks = from partition in Partitioner.Create(source).GetPartitions(maxDegreeOfParallelism) select Task.Run(async () =&gt; { using (partition) { while (partition.MoveNext()) { await operation(partition.Current).ConfigureAwait(false); } } }); return Task.WhenAll(tasks); } /// &lt;summary&gt; /// Executes an asynchronous operation for each item inside a source sequence. These operations are run concurrently in a parallel fashion. The invokation returns a task whose result is a sequence containing the results of all the asynchronous operations (in source sequence order). It is possible to constrain the maximum number of parallel operations. /// &lt;/summary&gt; /// &lt;typeparam name="TSource"&gt;The type of the items inside the source sequence&lt;/typeparam&gt; /// &lt;typeparam name="TResult"&gt;The type of the object produced by invoking &lt;paramref name="operation"/&gt; on any item of &lt;paramref name="source"/&gt;&lt;/typeparam&gt; /// &lt;param name="source"&gt;The source sequence&lt;/param&gt; /// &lt;param name="maxDegreeOfParallelism"&gt;The maximum number of operations that are able to run in parallel&lt;/param&gt; /// &lt;param name="operation"&gt;The asynchronous operation to be executed for each item inside &lt;paramref name="source"/&gt;. This operation will produce a result of type &lt;typeparamref name="TResult"/&gt;&lt;/param&gt; /// &lt;returns&gt;A task which completes when all of the asynchronous operations (one for each item inside &lt;paramref name="source"/&gt;) complete. This task will produce a sequence of objects of type &lt;typeparamref name="TResult"/&gt; which are the results (in source sequence order) of applying &lt;paramref name="operation"/&gt; to all items in &lt;paramref name="source"/&gt;&lt;/returns&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="source"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="operation"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt;&lt;paramref name="maxDegreeOfParallelism"/&gt; is less than or equal to zero.&lt;/exception&gt; public static async Task&lt;IEnumerable&lt;TResult&gt;&gt; ForEachAsync&lt;TSource, TResult&gt;( this IEnumerable&lt;TSource&gt; source, int maxDegreeOfParallelism, Func&lt;TSource, Task&lt;TResult&gt;&gt; operation) { if (source == null) throw new ArgumentNullException(nameof(source)); if (operation == null) throw new ArgumentNullException(nameof(operation)); EnsureValidMaxDegreeOfParallelism(maxDegreeOfParallelism); var resultsByPositionInSource = new ConcurrentDictionary&lt;long, TResult&gt;(); var tasks = from partition in Partitioner.Create(source).GetOrderablePartitions(maxDegreeOfParallelism) select Task.Run(async () =&gt; { using (partition) { while (partition.MoveNext()) { var positionInSource = partition.Current.Key; var item = partition.Current.Value; var result = await operation(item).ConfigureAwait(false); resultsByPositionInSource.TryAdd(positionInSource, result); } } }); await Task.WhenAll(tasks).ConfigureAwait(false); return Enumerable.Range(0, resultsByPositionInSource.Count) .Select(position =&gt; resultsByPositionInSource[position]); } private static void EnsureValidMaxDegreeOfParallelism(int maxDegreeOfParallelism) { if (maxDegreeOfParallelism &lt;= 0) { throw new ArgumentOutOfRangeException( nameof(maxDegreeOfParallelism), $"Invalid value for the maximum degree of parallelism: {maxDegreeOfParallelism}. The maximum degree of parallelism must be a positive integer."); } } } } </code></pre> <p>Can you spot any error or issue with this code? Any suggestion to improve this implementation is welcome (I have already planned new overloads to offer support for cancellation).</p> <p><strong>Update ( 10th September 2018 )</strong></p> <p>After some testing with the version of the code showed above we decided to opt for a different implementation based on <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphoreslim?view=netframework-4.7.2" rel="noreferrer">SemaphoreSlim class</a>.</p> <p>The issue we found with the previously posted version is due to the fact that <strong>fixed a maximum degree of parallelism of n, then exactly n partitions will be created and then exactly n tasks will be created.</strong></p> <p>The desired behavior is different: if the maximum degree of parallelism is set to n, then the number of parallel tasks should be <strong>less then or equal to n</strong>. For instance given a sequence of m items, with m &lt; n, <strong>then we expect m parallel operations</strong>. This was not possible with the implementation showed above. </p> <p>Here is the final version of the code (support for cancellation is still missing): </p> <pre><code>using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Linq; using System.Threading; namespace Deltatre.Utils.Concurrency.Extensions { /// &lt;summary&gt; /// Extension methods for enumerables /// &lt;/summary&gt; public static class EnumerableExtensions { /// &lt;summary&gt; /// Executes an asynchronous operation for each item inside a source sequence. These operations are run concurrently in a parallel fashion. The invokation returns a task which completes when all of the asynchronous operations (one for each item inside the source sequence) complete. It is possible to constrain the maximum number of parallel operations. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the items inside &lt;paramref name="source"/&gt;&lt;/typeparam&gt; /// &lt;param name="source"&gt;The source sequence&lt;/param&gt; /// &lt;param name="operation"&gt;The asynchronous operation to be executed for each item inside &lt;paramref name="source"/&gt;&lt;/param&gt; /// &lt;param name="maxDegreeOfParallelism"&gt;The maximum number of operations that are able to run in parallel. If null, no limits will be set for the maximum number of parallel operations (same behaviour as Task.WhenAll)&lt;/param&gt; /// &lt;returns&gt;A task which completes when all of the asynchronous operations (one for each item inside &lt;paramref name="source"/&gt;) complete&lt;/returns&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="source"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="operation"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt;&lt;paramref name="maxDegreeOfParallelism"/&gt; is less than or equal to zero.&lt;/exception&gt; public static Task ForEachAsync&lt;T&gt;( this IEnumerable&lt;T&gt; source, Func&lt;T, Task&gt; operation, int? maxDegreeOfParallelism = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (operation == null) throw new ArgumentNullException(nameof(operation)); EnsureValidMaxDegreeOfParallelism(maxDegreeOfParallelism); return (maxDegreeOfParallelism == null) ? ApplyOperationToAllItems(source, operation) : ApplyOperationToAllItemsWithConstrainedParallelism(source, operation, maxDegreeOfParallelism.Value); } private static Task ApplyOperationToAllItems&lt;T&gt;( IEnumerable&lt;T&gt; items, Func&lt;T, Task&gt; operation) { var tasks = items.Select(operation); return Task.WhenAll(tasks); } private static async Task ApplyOperationToAllItemsWithConstrainedParallelism&lt;T&gt;( IEnumerable&lt;T&gt; items, Func&lt;T, Task&gt; operation, int maxDegreeOfParallelism) { using (var throttler = new SemaphoreSlim(maxDegreeOfParallelism)) { var tasks = new List&lt;Task&gt;(); foreach (var item in items) { await throttler.WaitAsync().ConfigureAwait(false); #pragma warning disable IDE0039 // Use local function Func&lt;Task&gt; bodyOfNewTask = async () =&gt; #pragma warning restore IDE0039 // Use local function { try { await operation(item).ConfigureAwait(false); } finally { throttler.Release(); } }; tasks.Add(Task.Run(bodyOfNewTask)); } await Task.WhenAll(tasks).ConfigureAwait(false); } } /// &lt;summary&gt; /// Executes an asynchronous operation for each item inside a source sequence. These operations are run concurrently in a parallel fashion. The invokation returns a task whose result is a sequence containing the results of all the asynchronous operations (in source sequence order). It is possible to constrain the maximum number of parallel operations. /// &lt;/summary&gt; /// &lt;typeparam name="TSource"&gt;The type of the items inside the source sequence&lt;/typeparam&gt; /// &lt;typeparam name="TResult"&gt;The type of the object produced by invoking &lt;paramref name="operation"/&gt; on any item of &lt;paramref name="source"/&gt;&lt;/typeparam&gt; /// &lt;param name="source"&gt;The source sequence&lt;/param&gt; /// &lt;param name="operation"&gt;The asynchronous operation to be executed for each item inside &lt;paramref name="source"/&gt;. This operation will produce a result of type &lt;typeparamref name="TResult"/&gt;&lt;/param&gt; /// &lt;param name="maxDegreeOfParallelism"&gt;The maximum number of operations that are able to run in parallel. If null, no limits will be set for the maximum number of parallel operations (same behaviour as Task.WhenAll)&lt;/param&gt; /// &lt;returns&gt;A task which completes when all of the asynchronous operations (one for each item inside &lt;paramref name="source"/&gt;) complete. This task will produce a sequence of objects of type &lt;typeparamref name="TResult"/&gt; which are the results (in source sequence order) of applying &lt;paramref name="operation"/&gt; to all items in &lt;paramref name="source"/&gt;&lt;/returns&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="source"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="operation"/&gt; is &lt;c&gt;null&lt;/c&gt;.&lt;/exception&gt; /// &lt;exception cref="ArgumentOutOfRangeException"&gt;&lt;paramref name="maxDegreeOfParallelism"/&gt; is less than or equal to zero.&lt;/exception&gt; public static Task&lt;TResult[]&gt; ForEachAsync&lt;TSource, TResult&gt;( this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, Task&lt;TResult&gt;&gt; operation, int? maxDegreeOfParallelism = null) { if (source == null) throw new ArgumentNullException(nameof(source)); if (operation == null) throw new ArgumentNullException(nameof(operation)); EnsureValidMaxDegreeOfParallelism(maxDegreeOfParallelism); return (maxDegreeOfParallelism == null) ? ApplyOperationToAllItems(source, operation) : ApplyOperationToAllItemsWithConstrainedParallelism(source, operation, maxDegreeOfParallelism.Value); } private static Task&lt;TResult[]&gt; ApplyOperationToAllItems&lt;TItem, TResult&gt;( IEnumerable&lt;TItem&gt; items, Func&lt;TItem, Task&lt;TResult&gt;&gt; operation) { var tasks = items.Select(operation); return Task.WhenAll(tasks); } private static async Task&lt;TResult[]&gt; ApplyOperationToAllItemsWithConstrainedParallelism&lt;TItem, TResult&gt;( IEnumerable&lt;TItem&gt; items, Func&lt;TItem, Task&lt;TResult&gt;&gt; operation, int maxDegreeOfParallelism) { var resultsByPositionInSource = new ConcurrentDictionary&lt;long, TResult&gt;(); using (var throttler = new SemaphoreSlim(maxDegreeOfParallelism)) { var tasks = new List&lt;Task&gt;(); foreach (var itemWithIndex in items.Select((item, index) =&gt; new { item, index })) { await throttler.WaitAsync().ConfigureAwait(false); #pragma warning disable IDE0039 // Use local function Func&lt;Task&gt; bodyOfNewTask = async () =&gt; #pragma warning restore IDE0039 // Use local function { try { var item = itemWithIndex.item; var positionInSource = itemWithIndex.index; var result = await operation(item).ConfigureAwait(false); resultsByPositionInSource.TryAdd(positionInSource, result); } finally { throttler.Release(); } }; tasks.Add(Task.Run(bodyOfNewTask)); } await Task.WhenAll(tasks).ConfigureAwait(false); } return Enumerable .Range(0, resultsByPositionInSource.Count) .Select(position =&gt; resultsByPositionInSource[position]) .ToArray(); } private static void EnsureValidMaxDegreeOfParallelism(int? maxDegreeOfParallelism) { if (maxDegreeOfParallelism &lt;= 0) { throw new ArgumentOutOfRangeException( nameof(maxDegreeOfParallelism), $"Invalid value for the maximum degree of parallelism: {maxDegreeOfParallelism}. The maximum degree of parallelism must be a positive integer."); } } } } </code></pre>
[]
[ { "body": "<p>I see one big problem and one smaller problem with this code.</p>\n\n<p>The big problem is the complete lack of handling of exceptions. If just one of the tasks fails, there's no way to get the results of any of the rest of the tasks, because an <code>AggregateException</code> is going to be throw...
{ "AcceptedAnswerId": "212326", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-04T23:56:46.797", "Id": "203150", "Score": "6", "Tags": [ "c#", ".net", "concurrency", "async-await", "task-parallel-library" ], "Title": "ForEachAsync extension method (a way to run an async operation on each item of a sequence in parallel)" }
203150
<p>Does what it says in the title. I just finished this and wanted to share with someone.</p> <p>Looking for possible optimizations, bugs (most of it is tested to work) or any constructive criticism.</p> <pre><code>template&lt;typename P&gt; struct alignas(P) [[gnu::packed, gnu::may_alias]] pixel : public P { template&lt;typename&gt; friend struct pixel; using T = std::conditional_t&lt;std::is_integral_v&lt;typename P::T&gt;, unsigned, typename P::T&gt;; template&lt;std::size_t N, typename VT&gt; using V [[gnu::vector_size(N * sizeof(VT)), gnu::may_alias]] = VT; constexpr pixel() noexcept = default; template&lt;typename U = P, typename PT = typename U::T, std::enable_if_t&lt;pixel&lt;U&gt;::has_alpha(), bool&gt; = { }&gt; constexpr pixel(T cr, T cg, T cb, T ca) noexcept : P { static_cast&lt;PT&gt;(cb), static_cast&lt;PT&gt;(cg), static_cast&lt;PT&gt;(cr), static_cast&lt;PT&gt;(ca) } { } template&lt;typename U = P, typename PT = typename U::T, std::enable_if_t&lt;pixel&lt;U&gt;::has_alpha(), bool&gt; = { } &gt; constexpr pixel(T cr, T cg, T cb) noexcept : P { static_cast&lt;PT&gt;(cb), static_cast&lt;PT&gt;(cg), static_cast&lt;PT&gt;(cr), U::ax } { } template&lt;typename U = P, typename PT = typename U::T, std::enable_if_t&lt;not pixel&lt;U&gt;::has_alpha(), bool&gt; = { } &gt; constexpr pixel(T cr, T cg, T cb, T) noexcept : P { static_cast&lt;PT&gt;(cb), static_cast&lt;PT&gt;(cg), static_cast&lt;PT&gt;(cr) } { } template&lt;typename U = P, typename PT = typename U::T, std::enable_if_t&lt;not pixel&lt;U&gt;::has_alpha(), bool&gt; = { } &gt; constexpr pixel(T cr, T cg, T cb) noexcept : P { static_cast&lt;PT&gt;(cb), static_cast&lt;PT&gt;(cg), static_cast&lt;PT&gt;(cr) } { } constexpr pixel(const pixel&amp; p) noexcept = default; constexpr pixel(pixel&amp;&amp; p) noexcept = default; constexpr pixel&amp; operator=(const pixel&amp;) noexcept = default; constexpr pixel&amp; operator=(pixel&amp;&amp;) noexcept = default; template &lt;typename U&gt; constexpr operator pixel&lt;U&gt;() const noexcept { return cast_to&lt;U&gt;(); } static constexpr bool has_alpha() { return P::ax &gt; 0; } template&lt;typename U&gt; constexpr pixel&amp; blend(const pixel&lt;U&gt;&amp; other) { if constexpr (not pixel&lt;U&gt;::has_alpha()) { *this = other.template cast_to&lt;P&gt;(); } else if constexpr (sse and (std::is_floating_point_v&lt;typename P::T&gt; or std::is_floating_point_v&lt;typename U::T&gt;)) { *this = m128(m128_blend&lt;U&gt;(m128(), other.m128())); if constexpr (std::is_integral_v&lt;typename U::T&gt;) _mm_empty(); } else if constexpr (mmx and std::is_integral_v&lt;typename P::T&gt; and std::is_integral_v&lt;typename U::T&gt;) { *this = m64(m64_blend&lt;U&gt;(m64(), other.m64())); } else { using VT = std::conditional_t&lt;std::is_floating_point_v&lt;typename P::T&gt; or std::is_floating_point_v&lt;typename U::T&gt;, float, std::uint32_t&gt;; V&lt;4, VT&gt; src = other.template vector&lt;VT&gt;(); V&lt;4, VT&gt; dst = vector&lt;VT&gt;(); *this = vector&lt;VT&gt;(vector_blend&lt;U, VT&gt;(dst, src)); } return *this; } template&lt;typename U&gt; constexpr pixel&amp; blend_straight(const pixel&lt;U&gt;&amp; other) { if constexpr (not pixel&lt;U&gt;::has_alpha()) { *this = other.template cast_to&lt;P&gt;(); } else if constexpr (sse and (std::is_floating_point_v&lt;typename P::T&gt; or std::is_floating_point_v&lt;typename U::T&gt;)) { *this = m128(m128_blend&lt;U&gt;(m128_premul(m128()), m128_premul(other.m128()))); if constexpr (std::is_integral_v&lt;typename U::T&gt;) _mm_empty(); } else if constexpr (mmx and std::is_integral_v&lt;typename P::T&gt; and std::is_integral_v&lt;typename U::T&gt;) { *this = m64(m64_blend&lt;U&gt;(m64_premul(m64()), m64_premul(other.m64()))); } else { using VT = std::conditional_t&lt;std::is_floating_point_v&lt;typename P::T&gt; or std::is_floating_point_v&lt;typename U::T&gt;, float, std::uint32_t&gt;; V&lt;4, VT&gt; src = vector_premul&lt;VT&gt;(other.template vector&lt;VT&gt;()); V&lt;4, VT&gt; dst = vector_premul&lt;VT&gt;(vector&lt;VT&gt;()); *this = vector&lt;VT&gt;(vector_blend&lt;U, VT&gt;(dst, src)); } return *this; } constexpr pixel&amp; premultiply_alpha() { if constexpr (not has_alpha()) return *this; if constexpr (sse and std::is_floating_point_v&lt;typename P::T&gt;) *this = m128(m128_premul(m128())); else if constexpr (mmx and not std::is_floating_point_v&lt;typename P::T&gt;) *this = m64(m64_premul(m64())); else { using VT = std::conditional_t&lt;std::is_floating_point_v&lt;typename P::T&gt;, float, std::uint8_t&gt;; *this = vector&lt;VT&gt;(vector_premul&lt;VT&gt;(vector&lt;VT&gt;())); } return *this; } private: template &lt;typename U&gt; constexpr pixel&lt;U&gt; cast_to() const { constexpr bool not_constexpr = true;// not is_constexpr(this-&gt;b); if constexpr (not_constexpr and sse and (std::is_floating_point_v&lt;typename P::T&gt; or std::is_floating_point_v&lt;typename U::T&gt;)) { auto result = pixel&lt;U&gt;::m128(m128_cast_to&lt;U&gt;(m128())); if constexpr (std::is_integral_v&lt;typename P::T&gt;) _mm_empty(); return result; } else if constexpr (not_constexpr and mmx and (sse or (std::is_integral_v&lt;typename P::T&gt; and std::is_integral_v&lt;typename U::T&gt;))) { return pixel&lt;U&gt;::m64(m64_cast_to&lt;U&gt;(m64())); } else { using VT = std::conditional_t&lt;std::is_floating_point_v&lt;typename P::T&gt; or std::is_floating_point_v&lt;typename U::T&gt;, float, std::uint32_t&gt;; return pixel&lt;U&gt;::template vector&lt;VT&gt;(vector_cast_to&lt;U, VT&gt;(vector&lt;VT&gt;())); } } static constexpr pixel m64(auto value) noexcept // V4HI { static_assert(not std::is_floating_point_v&lt;typename P::T&gt;); auto v = _mm_packs_pu16(value, _mm_setzero_si64()); if constexpr (byte_aligned()) { auto v2 = _mm_cvtsi64_si32(v); pixel result { *reinterpret_cast&lt;pixel*&gt;(&amp;v2) }; _mm_empty(); return result; } else { auto v2 = reinterpret_cast&lt;V&lt;8, byte&gt;&amp;&gt;(v); pixel result { v2[2], v2[1], v2[0], v2[3] }; _mm_empty(); return result; } } constexpr __m64 m64() const noexcept // V4HI { static_assert(not std::is_floating_point_v&lt;typename P::T&gt;); __m64 v; if constexpr (byte_aligned()) v = _mm_cvtsi32_si64(*reinterpret_cast&lt;const int*&gt;(this)); else if constexpr (has_alpha()) v = _mm_setr_pi8(this-&gt;b, this-&gt;g, this-&gt;r, this-&gt;a, 0, 0, 0, 0); else v = _mm_setr_pi8(this-&gt;b, this-&gt;g, this-&gt;r, 0, 0, 0, 0, 0); auto r = _mm_unpacklo_pi8(v, _mm_setzero_si64()); return r; } static constexpr pixel m128(__m128 value) noexcept // V4SF { if constexpr (std::is_floating_point_v&lt;typename P::T&gt;) return *reinterpret_cast&lt;pixel*&gt;(&amp;value); else return m64(_mm_cvtps_pi16(value)); } constexpr __m128 m128() const noexcept // V4SF { if constexpr (std::is_floating_point_v&lt;typename P::T&gt;) return *reinterpret_cast&lt;const __m128*&gt;(this); else return _mm_cvtpu16_ps(m64()); } template&lt;typename VT = std::uint16_t&gt; static constexpr pixel vector(V&lt;4, VT&gt; src) noexcept { if constexpr ((std::is_same_v&lt;VT, float&gt; and std::is_same_v&lt;T, float&gt;) or (sizeof(VT) == 1 and byte_aligned())) { return *reinterpret_cast&lt;pixel*&gt;(&amp;src); } return pixel { static_cast&lt;T&gt;(src[2]), static_cast&lt;T&gt;(src[1]), static_cast&lt;T&gt;(src[0]), static_cast&lt;T&gt;(src[3]) }; } template&lt;typename VT = std::uint16_t&gt; constexpr V&lt;4, VT&gt; vector() const noexcept { V&lt;4, VT&gt; src; if constexpr ((std::is_same_v&lt;VT, float&gt; and std::is_same_v&lt;T, float&gt;) or (sizeof(VT) == 1 and byte_aligned())) { src = *reinterpret_cast&lt;const V&lt;4, VT&gt;*&gt;(this); if constexpr (has_alpha()) src = V&lt;4, VT&gt; { src[0], src[1], src[2], 1 }; } else if constexpr (has_alpha()) src = V&lt;4, VT&gt; { static_cast&lt;VT&gt;(this-&gt;b), static_cast&lt;VT&gt;(this-&gt;g), static_cast&lt;VT&gt;(this-&gt;r), static_cast&lt;VT&gt;(this-&gt;a), }; else src = V&lt;4, VT&gt; { static_cast&lt;VT&gt;(this-&gt;b), static_cast&lt;VT&gt;(this-&gt;g), static_cast&lt;VT&gt;(this-&gt;r), 1 }; return src; } template &lt;typename U&gt; static constexpr __m128 m128_cast_to(__m128 src) noexcept { constexpr __m128 cast = reinterpret_cast&lt;__m128&gt;(pixel&lt;U&gt;::template vector_max&lt;float&gt;(P::ax) * (1.0f / vector_max&lt;float&gt;(U::ax or 1.0f))); src = _mm_mul_ps(src, cast); if constexpr (pixel&lt;U&gt;::has_alpha() and not has_alpha()) src = _mm_setr_ps(src[0], src[1], src[2], static_cast&lt;float&gt;(U::ax)); return src; } template &lt;typename U&gt; static constexpr __m64 m64_cast_to(__m64 src) noexcept { constexpr auto mullo = reinterpret_cast&lt;__m64&gt;(pixel&lt;U&gt;::template vector_max&lt;std::uint16_t&gt;()); constexpr auto mulhi = reinterpret_cast&lt;__m64&gt;(vector_max_reciprocal&lt;17, std::uint16_t, 15&gt;()); auto vector_max_contains = [](std::uint16_t value) { auto v = vector_max&lt;std::uint16_t&gt;(); for (auto i = 0; i &lt; 4; ++i) if (v[i] == value) return true; return false; }; src = _mm_mullo_pi16(src, mullo); auto dst = _mm_mulhi_pi16(src, mulhi); dst = _mm_srli_pi16(_mm_adds_pu8(dst, _mm_set1_pi16(1)), 1); if constexpr (vector_max_contains(1)) { constexpr auto is1 = reinterpret_cast&lt;__m64&gt;(vector_max&lt;std::uint16_t&gt;() == 1); auto v1 = _mm_and_si64(src, is1); dst = _mm_or_si64(_mm_andnot_si64(is1, dst), v1); } if constexpr (vector_max_contains(3)) { constexpr auto mulhi3 = reinterpret_cast&lt;__m64&gt;(vector_max_reciprocal&lt;16, std::uint16_t, 15&gt;()); constexpr auto is3 = reinterpret_cast&lt;__m64&gt;(vector_max&lt;std::uint16_t&gt;() == 3); auto v3 = _mm_mulhi_pi16(_mm_and_si64(src, is3), mulhi3); dst = _mm_or_si64(_mm_andnot_si64(is3, dst), v3); } if constexpr (pixel&lt;U&gt;::has_alpha() and not has_alpha()) dst = _mm_insert_pi16(dst, U::ax, 3); return dst; } template &lt;typename U, typename VT&gt; static constexpr V&lt;4, VT&gt; vector_cast_to(V&lt;4, VT&gt; src) noexcept { if constexpr (std::is_floating_point_v&lt;VT&gt;) { src *= pixel&lt;U&gt;::template vector_max&lt;VT&gt;(P::ax) * (1.0f / vector_max&lt;VT&gt;(U::ax or 1.0f)); } else { constexpr auto rbits = (sizeof(VT) - 1) * 8; src *= pixel&lt;U&gt;::template vector_max&lt;VT&gt;(P::ax | 1); src *= vector_max_reciprocal&lt;rbits, VT&gt;(U::ax | 1); src += 1 &lt;&lt; (rbits - 1); src &gt;&gt;= rbits; } if constexpr (has_alpha()) return src; else return V&lt;4, VT&gt; { src[0], src[1], src[2], static_cast&lt;VT&gt;(U::ax) }; } static constexpr __m128 m128_premul(__m128 src) noexcept { if constexpr (not has_alpha()) return src; constexpr auto ax = reinterpret_cast&lt;__m128&gt;(1.0f / V&lt;4, float&gt; { P::ax, P::ax, P::ax, 1 }); auto srca = _mm_setr_ps(src[3], src[3], src[3], 1); src = _mm_mul_ps(src, srca); src = _mm_mul_ps(src, ax); return src; } static constexpr __m64 m64_premul(__m64 src) noexcept { if constexpr (not has_alpha()) return src; auto a = _mm_shuffle_pi16(src, shuffle_mask(3, 3, 3, 3)); src = _mm_mullo_pi16(src, a); if constexpr (P::ax == 3) { constexpr auto ax = vector_reciprocal&lt;16, std::uint16_t, 15&gt;(P::ax); src = _mm_mulhi_pi16(src, reinterpret_cast&lt;__m64&gt;(ax)); } else if constexpr (P::ax &gt; 3) { constexpr auto ax = vector_reciprocal&lt;17, std::uint16_t, 15&gt;(P::ax); src = _mm_mulhi_pi16(src, reinterpret_cast&lt;__m64&gt;(ax)); src = _mm_srli_pi16(_mm_adds_pu8(src, _mm_set1_pi16(1)), 1); } src = _mm_insert_pi16(src, a[0], 3); return src; } template &lt;typename VT&gt; static constexpr V&lt;4, VT&gt; vector_premul(V&lt;4, VT&gt; src) noexcept { if constexpr (not has_alpha()) return src; auto a = V&lt;4, VT&gt; { src[3], src[3], src[3], 1 }; if constexpr (std::is_floating_point_v&lt;VT&gt;) { constexpr auto ax = 1.0f / V&lt;4, float&gt; { P::ax, P::ax, P::ax, 1 }; src *= a * ax; } else { constexpr auto rbits = (sizeof(VT) - 1) * 8; constexpr auto ax = vector_reciprocal&lt;rbits, VT&gt;(P::ax, P::ax, P::ax, 1); src *= a; src *= ax; src += 1 &lt;&lt; (rbits - 1); src &gt;&gt;= rbits; } return src; } template &lt;typename U&gt; constexpr __m128 m128_blend(__m128 dst, __m128 src) { constexpr auto ax = reinterpret_cast&lt;__m128&gt;(1.0f / V&lt;4, float&gt; { U::ax, U::ax, U::ax, U::ax }); auto a = _mm_sub_ps(_mm_set1_ps(U::ax), _mm_set1_ps(src[3])); if constexpr (not std::is_same_v&lt;P, U&gt;) src = pixel&lt;U&gt;::template m128_cast_to&lt;P&gt;(src); dst = _mm_mul_ps(dst, a); dst = _mm_mul_ps(dst, ax); dst = _mm_add_ps(dst, src); return dst; } template &lt;typename U&gt; constexpr __m64 m64_blend(__m64 dst, __m64 src) { //auto a = _mm_sub_pi16(_mm_set1_pi16(U::ax), _mm_shuffle_pi16(src, shuffle_mask(3, 3, 3, 3))); auto a = _mm_set1_pi16(U::ax - reinterpret_cast&lt;V&lt;4, std::uint16_t&gt;&gt;(src)[3]); if constexpr (not std::is_same_v&lt;P, U&gt;) src = pixel&lt;U&gt;::template m64_cast_to&lt;P&gt;(src); dst = _mm_mullo_pi16(dst, a); if constexpr (U::ax == 3) { constexpr auto ax = vector_reciprocal&lt;16, std::uint16_t, 15&gt;(U::ax); dst = _mm_mulhi_pi16(dst, reinterpret_cast&lt;__m64&gt;(ax)); } else if constexpr (U::ax != 1) { constexpr auto ax = vector_reciprocal&lt;17, std::uint16_t, 15&gt;(U::ax); dst = _mm_mulhi_pi16(dst, reinterpret_cast&lt;__m64&gt;(ax)); dst = _mm_srli_pi16(_mm_adds_pu8(dst, _mm_set1_pi16(1)), 1); } dst = _mm_adds_pu16(dst, src); return dst; } template &lt;typename U, typename VT&gt; static constexpr V&lt;4, VT&gt; vector_blend(V&lt;4, VT&gt; dst, V&lt;4, VT&gt; src) noexcept { if constexpr (not std::is_same_v&lt;P, U&gt;) src = pixel&lt;U&gt;::template vector_cast_to&lt;P, VT&gt;(src); if constexpr (std::is_floating_point_v&lt;VT&gt;) { constexpr auto ax = 1.0f / U::ax; dst *= static_cast&lt;VT&gt;(U::ax - src[3]) * ax; dst += src; } else { constexpr auto rbits = (sizeof(VT) - 1) * 8; constexpr auto ax = vector_reciprocal&lt;rbits, VT&gt;(U::ax); dst *= static_cast&lt;VT&gt;(U::ax - src[3]); dst *= ax; dst += 1 &lt;&lt; (rbits - 1); dst &gt;&gt;= rbits; dst += src; } return dst; } template&lt;std::size_t bits, typename VT = std::uint16_t, std::size_t maxbits = bits&gt; static constexpr auto vector_reciprocal(VT v0, VT v1, VT v2, VT v3) noexcept { auto r = [](VT v) -&gt; VT { return std::min(((1ul &lt;&lt; bits) + v - 1) / v, (1ul &lt;&lt; maxbits) - 1); }; return V&lt;4, VT&gt; { r(v0), r(v1), r(v2), r(v3)}; } template&lt;std::size_t bits, typename VT = std::uint16_t, std::size_t maxbits = bits&gt; static constexpr auto vector_reciprocal(VT v0) noexcept { return vector_reciprocal&lt;bits, VT, maxbits&gt;(v0, v0, v0, v0); } template&lt;typename VT = float&gt; static constexpr auto vector_max(VT noalpha = 1) noexcept { return V&lt;4, VT&gt; { P::bx, P::gx, P::rx, static_cast&lt;VT&gt;(has_alpha() ? P::ax : noalpha) }; } template&lt;std::size_t bits, typename VT = std::uint16_t, std::size_t maxbits = bits&gt; static constexpr auto vector_max_reciprocal(VT noalpha = 1) noexcept { return vector_reciprocal&lt;bits, VT, maxbits&gt;(P::bx, P::gx, P::rx, static_cast&lt;VT&gt;(has_alpha() ? P::ax : noalpha)); } template&lt;typename T&gt; constexpr bool is_constexpr(T value) { return __builtin_constant_p(value); } static constexpr auto shuffle_mask(int v0, int v1, int v2, int v3) noexcept { return (v0 &amp; 3) | ((v1 &amp; 3) &lt;&lt; 2) | ((v2 &amp; 3) &lt;&lt; 4) | ((v3 &amp; 3) &lt;&lt; 6); } static constexpr bool byte_aligned() noexcept { return P::byte_aligned; } }; struct alignas(0x10) bgra_ffff { using T = float; T b, g, r, a; static constexpr T rx = 1.0f; static constexpr T gx = 1.0f; static constexpr T bx = 1.0f; static constexpr T ax = 1.0f; static constexpr bool byte_aligned = false; }; struct alignas(0x10) bgra_fff0 { using T = float; T b, g, r; unsigned : sizeof(float); static constexpr T rx = 1.0f; static constexpr T gx = 1.0f; static constexpr T bx = 1.0f; static constexpr T ax = 0.0f; static constexpr bool byte_aligned = false; }; struct alignas(4) bgra_8888 { using T = std::uint8_t; T b, g, r, a; static constexpr T rx = 255; static constexpr T gx = 255; static constexpr T bx = 255; static constexpr T ax = 255; static constexpr bool byte_aligned = true; }; struct [[gnu::packed]] alignas(4) bgra_8880 { using T = std::uint8_t; T b, g, r; T : 8; static constexpr T rx = 255; static constexpr T gx = 255; static constexpr T bx = 255; static constexpr T ax = 0; static constexpr bool byte_aligned = true; }; struct [[gnu::packed]] bgr_8880 { using T = std::uint8_t; T b, g, r; static constexpr T rx = 255; static constexpr T gx = 255; static constexpr T bx = 255; static constexpr T ax = 0; static constexpr bool byte_aligned = true; }; struct [[gnu::packed]] bgra_6668 { using T = unsigned; T b : 6, : 2; T g : 6, : 2; T r : 6, : 2; T a : 8; constexpr bgra_6668(T vb, T vg, T vr, T va) noexcept : b(vb), g(vg), r(vr), a(va) { } static constexpr T rx = 63; static constexpr T gx = 63; static constexpr T bx = 63; static constexpr T ax = 255; static constexpr bool byte_aligned = true; }; struct alignas(2) [[gnu::packed]] bgr_5650 { using T = unsigned; T b : 5; T g : 6; T r : 5; static constexpr T rx = 31; static constexpr T gx = 63; static constexpr T bx = 31; static constexpr T ax = 0; static constexpr bool byte_aligned = false; }; struct alignas(2) [[gnu::packed]] bgra_5551 { using T = unsigned; T b : 5; T g : 5; T r : 5; T a : 1; static constexpr T rx = 31; static constexpr T gx = 31; static constexpr T bx = 31; static constexpr T ax = 1; static constexpr bool byte_aligned = false; }; struct alignas(2) [[gnu::packed]] bgra_5550 { using T = unsigned; T b : 5; T g : 5; T r : 5; T : 1; static constexpr T rx = 31; static constexpr T gx = 31; static constexpr T bx = 31; static constexpr T ax = 0; static constexpr bool byte_aligned = false; }; struct alignas(2)[[gnu::packed]] bgra_4444 { using T = unsigned; T b : 4; T g : 4; T r : 4; T a : 4; static constexpr T rx = 15; static constexpr T gx = 15; static constexpr T bx = 15; static constexpr T ax = 15; static constexpr bool byte_aligned = false; }; struct [[gnu::packed]] bgr_2330 { using T = unsigned; T b : 2; T g : 3; T r : 3; static constexpr T rx = 7; static constexpr T gx = 7; static constexpr T bx = 3; static constexpr T ax = 0; static constexpr bool byte_aligned = false; }; struct [[gnu::packed]] bgra_2321 { using T = unsigned; T b : 2; T g : 3; T r : 2; T a : 1; static constexpr T rx = 3; static constexpr T gx = 7; static constexpr T bx = 3; static constexpr T ax = 1; static constexpr bool byte_aligned = false; }; struct[[gnu::packed]] bgra_2222 { using T = unsigned; T b : 2; T g : 2; T r : 2; T a : 2; static constexpr T rx = 3; static constexpr T gx = 3; static constexpr T bx = 3; static constexpr T ax = 3; static constexpr bool byte_aligned = false; }; using pxf = pixel&lt;bgra_ffff&gt;; // floating-point for use with SSE using pxfn = pixel&lt;bgra_fff0&gt;; // floating-point, no alpha using px32a = pixel&lt;bgra_8888&gt;; // 24-bit, 8-bit alpha channel using px32n = pixel&lt;bgra_8880&gt;; // 24-bit, no alpha, 4 bytes wide using px24 = pixel&lt;bgr_8880&gt;; // 24-bit, 3 bytes wide using px16 = pixel&lt;bgr_5650&gt;; // 16-bit, typical 5:6:5 format using px16a = pixel&lt;bgra_5551&gt;; // 15-bit with 1-bit alpha using px16n = pixel&lt;bgra_5550&gt;; // 15-bit, no alpha, equal 5:5:5 format using px16aa = pixel&lt;bgra_4444&gt;; // 12-bit, 4-bit alpha, equal 4:4:4 format using px8aa = pixel&lt;bgra_2222&gt;; // 6-bit 2:2:2, 2-bit alpha using px8a = pixel&lt;bgra_2321&gt;; // 7-bit 2:3:2, 1-bit alpha using px8n = pixel&lt;bgr_2330&gt;; // 8-bit 3:3:2, no alpha using pxvga = pixel&lt;bgra_6668&gt;; // VGA DAC palette format static_assert(sizeof(pxf ) == 16); static_assert(sizeof(pxfn ) == 16); static_assert(sizeof(px32a ) == 4); static_assert(sizeof(px32n ) == 4); static_assert(sizeof(px24 ) == 3); static_assert(sizeof(px16 ) == 2); static_assert(sizeof(px16aa) == 2); static_assert(sizeof(px16a ) == 2); static_assert(sizeof(px16n ) == 2); static_assert(sizeof(px8aa ) == 1); static_assert(sizeof(px8a ) == 1); static_assert(sizeof(px8n ) == 1); static_assert(sizeof(pxvga ) == 4); inline auto generate_px8n_palette() { std::vector&lt;px32n&gt; result; result.reserve(256); for (auto i = 0; i &lt; 256; ++i) result.emplace_back(reinterpret_cast&lt;px8n&amp;&gt;(i)); return result; } </code></pre>
[]
[ { "body": "<p>The code seems to get more and more questionable as we read downward. Starting at the bottom:</p>\n\n<pre><code>inline auto generate_px8n_palette()\n{\n std::vector&lt;px32n&gt; result;\n result.reserve(256);\n for (auto i = 0; i &lt; 256; ++i)\n result.emplace_back(reinterpret_cas...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T01:19:13.967", "Id": "203154", "Score": "3", "Tags": [ "c++", "graphics", "c++17", "vectorization", "sse" ], "Title": "Generic pixel class to seamlessly alpha-blend and convert between different pixel structure layouts" }
203154
<p>I've been working on a full RPG skeleton for a while, and I've just now reached a point on the module dealing with items where I feel comfortable sharing. My intent was to create a structure for the items, and then a CLI tool for creating/editing/saving JSON files which will be read as data.</p> <p>This is going to be quite a bit of code, so I understand if people don't particularly care to read it. I know there are some odd things already. I went a little too crazy with name mangling and my documentation isn't always on point. Everything is still set up for creating a text based game, but I figured once I get that knocked out adding additional attributes for images wouldn't bee all that difficult. I'm not sure if that's the wrong approach, but I guess I'll find out when I get there.</p> <p>I've left out one file because it doesn't really pertain to anything else here. It's shop_dict.py and just contains a ShopDict class and methods for updating stock. Not entirely important for this and maybe doesn't specifically belong in this module. I know that structure and naming are a couple of my big issues as well, and I'm working to understand a little better.</p> <p>All of these files, as well as my progress with the other modules, can be found <a href="https://gitlab.com/users/morph8hprom/projects" rel="nofollow noreferrer">here at my Gitlab</a>.</p> <p>item.py</p> <pre><code>#!/usr/bin/env python3 from pkg_resources import resource_string import json """ File used to define item class, weapon class, armor class, and consumable class """ class Item: """ Parameters and methods for the base Item class """ def __init__(self, id = '1', name = 'test', desc = 'test desc', item_type = None): self._id = id self._name = name self._desc = desc self.item_type = item_type def __repr__(self): return 'Id:{}\n Name:{}\n Desc:{}\n Item Type:{}'.format(self._id, self._name, self._desc, self.item_type) class Weapon(Item): """ Parameters and methods for the Weapon subclass """ def __init__(self, id = 8, name = 'test weapon', desc = 'test desc', item_type = 'Weapon', damage = 0, weapon_type = None, two_handed = False): super().__init__(id, name, desc, item_type) self.damage = damage self.weapon_type = weapon_type self.two_handed = two_handed self.equipped = False class Armor(Item): """ Parameters and methods for the Armor subclass """ def __init__(self, id = '10', name = 'test armor', desc = 'test desc', item_type = 'Armor', defense = 0, slot = None): super().__init__(id, name, desc, item_type) self.defense = defense self._slot = slot self.equipped = False class Consumable(Item): """ Parameters and methods for the Consumable subclass """ def __init__(self, id = '12', name = 'test consumable', desc = 'test desc', item_type = 'Consumable', first_effect = None, second_effect = None): super().__init__(id, name, desc, item_type) self.item_type = 'Consumable' self.first_effect = first_effect self.second_effect = second_effect def _check_stat(self, effect): """ Checks which stat to modify """ stat = effect.keys() return stat def _check_mod(self, effect): """ Checks the value for the effect dict """ mod_amount = effect.values() return mod_amount </code></pre> <p>item_dict.py</p> <pre><code>#!/usr/bin/env python3 from pkg_resources import resource_string from gim import item as I import json """ File used to define ItemDict class and it's methods """ class ItemDict(): def __init__(self, id = 1, num_of_items = 5): # Dictionary containing reference to all items self.all_items = {} # Dictionary containing reference to only weapons self.weapons = {} # Dictionary containing reference to only armor self.armor = {} # Dictionary containing reference to only consumables self.consumables = {} self._id = id self._num_of_items = num_of_items self._update_main_dict() self._update_weapons() self._update_armor() self._update_consumables() def __iter__(self): return iter(self.all_items.items()) def __len__(self): return len(self.all_items) def __contains__(self, item): return item.id in self.all_items def __getitem__(self, item): return self.all_items[item.id] def _build_item(self, id): """ Gathers item data from json file and returns instance object based on item type. """ jsontext = resource_string(__name__, 'data/item{}.json'.format(id)) d = json.loads(jsontext.decode('utf-8')) d['id'] = id if d['item_type'] == 'Weapon': item = I.Weapon(**d) elif d['item_type'] == 'Armor': item = I.Armor(**d) elif d['item_type'] == 'Consumable': item = I.Consumable(**d) return item def _update_main_dict(self): d = {} for i in range(self._id, self._num_of_items + 1): try: d[i] = self._build_item(i) except FileNotFoundError: print('File not found. Please check to make sure it exists') self.all_items = d def _update_weapons(self): d = {} for i in self.all_items.values(): if i.item_type == 'Weapon': d[i._id] = i self.weapons = d def _update_armor(self): d = {} for i in self.all_items.values(): if i.item_type == 'Armor': d[i._id] = i self.armor = d def _update_consumables(self): d = {} for i in self.all_items.values(): if i.item_type == 'Consumable': d[i._id] = i self.consumables = d </code></pre> <p>json_handler.py</p> <pre><code>#!/usr/bin/env python3 import json import glob from pkg_resources import resource_string class DirectoryFiles(): def __init__(self, directory = 'data/', filename = '*', extension = '.json'): self._directory = directory self._filename = filename self._extension = extension self._full_path = "{}{}{}".format(self._directory, self._filename, self._extension) self._files = None self._digits = [] self._next = None # Build a list of all files in the data directory self._update_files() # Isolate only the digits in the filenames self._isolate_digits() # Store digit for next file in self._next self._get_next() def __repr__(self): return "{}\n{}\n{}".format(self.__class__.__name__, self._full_path, self._files) def _update_files(self): self._files = glob.glob('{}'.format(self._full_path)) self._files.sort() def _isolate_digits(self): for filename in self._files: digit = '' for c in filename: if c.isdigit(): digit += c try: self._digits.append(int(digit)) except ValueError: pass def _get_next(self): self._next = str(self._digits[-1] + 1) class ItemData(): def __init__(self, item_type = None, filename = None): self._item_type = item_type self._filename = filename self._attributes = None self._dict = {} self._json_dump = None self._mangle_file = 'data/mangle.json' self._mangle_dict = None self._update_mangle() def __iter__(self): return iter(self._dict.items()) def __setitem__(self, key, item): self._dict[key] = item def _update_mangle(self): jsontext = resource_string(__name__, self._mangle_file) d = json.loads(jsontext.decode('utf-8')) self._mangle_dict = d def _mangle_names(self): """ Used to mangle attribute names to ensure that there are no conflicts when creating an instance of Item() class. """ for k, v in self._mangle_dict.items(): try: self._dict[v] = self._dict.pop(k) except (KeyError, ValueError): pass def _to_json(self): self._json_dump = json.dumps(self._dict) def test(): test = DirectoryFiles() if __name__ == "__main__": test() </code></pre> <p>command.py</p> <pre><code>#!/usr/bin/env python3 import os import json import textwrap import cmd2 from pkg_resources import resource_string from gim import json_handler as jh from gim import item as i class Command(cmd2.Cmd): def __init__(self): super().__init__() # Set break_long_words to False to prevent words being split self.break_long_words = False self.prompt = '&gt;' # FLAGS # flag for confirming creating a new file self._conf_new = False # flag for selecting item_type self._sel_type = False # flag for editting attributes self._edit_att = False # flag for confirming saving a file self._conf_save = False # current working directory self._cwd = None # extension self._ext = None # data file for cmd print messages self._msgs_file = 'data/cmd_msgs.json' # variable to hold instance of MessageHandler() self._msgs = None # data file for item attributes self._att_file = 'data/item_att.json' # variable to hold filename for creation of ItemData() instance self._filename = None # variable to hold all item attributes dict self._all_att = None # variable to hold specific item type attributes dict self._item_att = None # variable to hold string of item attributes for do_attributes method self._att_str = None # variable to hold instance of jh.DirectoryFiles() self._all_files = None # variable to hold instance of jh.ItemData() self._current_file = None # Load all print messages into a dictionary for easy access self._load_cmd_msgs() # Load item _attributes self._load_att() # Update _all_files self._update_dir() # Display startup messages self._startup() def _update_dir(self): """ Create instance of jh.DirectoryFiles() using default parameters """ self._all_files = jh.DirectoryFiles() def _load_cmd_msgs(self): """ Load cmd messages from json file specified by self._msgs_file """ jsontext = resource_string(__name__, self._msgs_file) d = json.loads(jsontext.decode('utf-8')) self._msgs = MsgHandler(**d) def _load_att(self): """ Load item attribute dictionary from json file specified by self._att_file """ jsontext = resource_string(__name__, self._att_file) d = json.loads(jsontext.decode('utf-8')) self._all_att = d def _save_file(self): self._current_file._to_json() with open(self._current_file._filename, 'w') as f: f.write(self._current_file._json_dump) def _edit_att(self, att, val): """ Used to set attribute provided to value provided """ self._current_file[att] = val def _startup(self): """ Print startup messages """ self._msgs._print_msg('welcome') self._msgs._print_msg('new_or_load') def _create_new(self): """ Used to create a new instance of jh.ItemData() and change the _sel_type flag to True """ self._cwd = self._all_files._directory self._ext = self._all_files._extension self._next = self._all_files._next filename = '{}item{}{}'.format(self._cwd, self._next, self._ext) self._current_file = jh.ItemData(None, filename) self._sel_type = True self._msgs._print_msg('select_type') def _select_type(self, type): self._current_file._item_type = type self._current_file['item_type'] = type self._item_att = self._all_att[type] self._att_str = ', '.join(self._item_att) def do_new(self, arg): """ If current file is None, create new instance of jh.ItemData using parameters from self._all_files to generate a filename. If current file is not None ask for confirmation before creating new instance """ if self._current_file == None: self._create_new() else: self._conf_new = True self._msgs._print_msg('current_not_none') def do_save(self,arg): if self._current_file == None: pass else: self._conf_save = True self._msgs._print_msg('save_msg') def do_yes(self, arg): if self._conf_new: self._create_new() self._conf_new = False elif self._conf_save: self._save_file() self._conf_save = False else: pass def do_no(self, arg): if self._conf_new: self._conf_new = False elif self._conf_save: self._conf_save = False else: pass def do_weapon(self, arg): """ Set item type to Weapon when creating a new item. """ if self._sel_type: self._select_type('Weapon') self._sel_type = False self._edit_att = True self._msgs._print_msg('att_msg') else: pass def do_armor(self, arg): """ Set item type to Armor when creating a new item. """ if self._sel_type: self._select_type('Armor') self._sel_type = False self._edit_att = True self._msgs._print_msg('att_msg') else: pass def do_consumable(self, arg): """ Set item type to Consumable when creating a new item. """ if self._sel_type: self._select_type('Consumable') self._sel_type = False self._edit_att = True self._msgs._print_msg('att_msg') else: pass def do_show(self, arg): print(self._current_file._dict) def do_edit(self, arg): if arg in self._item_att: self._msgs._print_msg(arg) val = input('&gt;') self._current_file[arg] = val else: self._msgs._print_msg('invalid_att') def do_attributes(self, arg): self._msgs._print_msg('current_attributes') print(self._att_str) class MsgHandler(): def __init__(self, **kwargs): self.__dict__.update((key, value) for key, value in kwargs.items()) def _print_msg(self, msg): for line in textwrap.wrap(vars(self)[msg], 80): print(line) def test(): test_inst = Command() #test_inst.cmdloop() print(test_inst._all_files._files) if __name__ == "__main__": test() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T03:54:19.610", "Id": "203157", "Score": "1", "Tags": [ "python", "python-3.x", "json", "role-playing-game" ], "Title": "Python Text RPG Item Management System (with CLI tool for creating JSON files)" }
203157
<blockquote> <p>The goal of this code is to seat students in a classroom based on a single test score. We want students to be evenly distributed across the class such that every student is positioned next to the greatest amount of peer-assistance they can, avoiding clustering of low or high scores.</p> </blockquote> <p>The following method seems to work rather well. Modeling scores a force measurement <code>(score1*score2)/r**2</code> and minimizing mean force across the class, then sorting for each possible arrangement reliably produces really high-quality distributions. </p> <p>Unfortunately, the complexity of the problem becomes ~<span class="math-container">\$O(N!)\$</span> difficult, so class sizes above 7 students are super prohibitive. 8 students is pushing it on my 4 core machine.</p> <p>I would like to look at more efficient ways of calculating these sets, even if I arrive there separately.</p> <pre><code>import numpy as np import pandas as pd import math import scipy.special from functools import reduce from itertools import permutations, combinations import matplotlib.pyplot as plt import time ########## ##Starting a Clock ########## t0a = time.clock() t0b = time.time() ##Distance function def dist(locarray): temp_ar = [None]*len(locarray) for i in range(len(locarray)): temp_ar[i] = abs(locarray[i][1]-locarray[i][0]) #print('a = ',locarray[0], '\n','b= ', locarray[1]) #debug step. Add detection for 2-d layouts. return temp_ar ##THE VARIABLE HOW MANY STUDENTS no_students = 6 #Any number &gt; 6 will take a significant amount of time! ###Generate Test DataSet for 5 students uar = [None]*no_students for i in range(no_students): uar[i] = ['u'+str(i), int(np.random.rand(1)*70+30)] #Define Classroom - each cell is a location loc_1d = np.array(range(no_students)) ##Initialize pandas dataframe for holding population data data_col = ['sample_mean','sample_stddev','seating'] pop_data = pd.DataFrame(columns=data_col) size = reduce(lambda x, y: x*y, np.shape(loc_1d)) ##The counter wahaha step_count = 0 ##Create base class assignment with null locations where applicable layout_init = [None] * size for loc_id in range(size): try: layout_init[loc_id] = uar[loc_id] except IndexError: layout_init[loc_id] = 'empty' ##Now we can use itertools to generate all possible permutations in the class perm = permutations(layout_init,size) loc_space = list(perm) ##Wonderful! Now we have userid and scores in their respective locations. ##Each row in loc_space is a possible seating arrangement. n_unique = int(math.factorial(size)/(math.factorial(num_surr)*math.factorial(size-num_surr))) #QC step for unique_diff combos unique_diff = list(combinations(loc_1d,2)) #yes, itertools is that awesome distance = dist(unique_diff) ##In creating a progress bar max_steps = len(loc_space)*len(unique_diff) #Now, let's use the unique combinations to calculate the force at each node for a in range(len(loc_space)): test_set = loc_space[a] #grab a row of data to work on #print('Set of Locations = ', loc_space[a]) #debug print force_vec = [None]*len(unique_diff) #clears diff_vec and sets for new row for b in range(len(unique_diff)): #print('combo is: ', unique_diff[b], '\n', 'debug (distance): ', distance) force_vec[b] = np.array((test_set[unique_diff[b][0]][1] * test_set[unique_diff[b][1]][1]) / distance[b]**2 ) #note absolute value, change nearest neighbor #print('Force Vector_ALL FORCES =', force_vec) step_count = step_count + 1 print('We are on step ', step_count, ' of max_steps ', max_steps, ' --(', int((step_count/max_steps)*100), ')--') #Great! We now have a vector of differences. Let's get the mean of the absolute values pop_data.loc[len(pop_data)] = [np.average(force_vec), np.std(force_vec), test_set] print('Operation completed in -- ', step_count, ' --') #pop_sorted_std = pop_data.sort_values(by='sample_stddev') pop_sorted_mean = pop_data.sort_values(by='sample_mean') pop_size = len(loc_space) #THIS COMES IN HANDY ####### ##Plotting to get an idea of the anwer landscape! ####### ##Extreme means subset_low = pop_sorted_mean[0:size*2]['seating'].apply(pd.Series).reset_index(drop=True) #lowest means subset_high = pop_sorted_mean[pop_size-size*2-1:pop_size-1]['seating'].apply(pd.Series).reset_index(drop=True) #Highest means ########## ##Print Low ########## scrim2 = [] y_pos = np.arange(size) for m in range(len(subset_low)): worker_a = subset_low.loc[m] scrim1 = [] # print('worker_a: ', worker_a) for n in range(len(worker_a)): worker_b = np.array(worker_a[n][1]) scrim1 = np.append(scrim1,worker_b) # print(worker_b) watch out for these prints scrim2.append(scrim1) plt.figure(figsize=(10,5)) for k in range(len(scrim2)): plt.bar(y_pos,scrim2[k], alpha=0.08) plt.show() ##Time everything took print('Process time: ',time.clock()-t0a) print('Wall time: ',time.time()-t0b) print('\nRaw Results: ', uar) ##Display scoreset </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T15:32:03.920", "Id": "391875", "Score": "1", "body": "Ah. thanks. I was working in spyder which kept an old list in memory. I updated the code to include [None]*no_students initialization" }, { "ContentLicense": "CC BY-SA ...
[ { "body": "<h1>TL;DR</h1>\n\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport pandas as pd\nimport math\nimport scipy.special\nfrom functools import reduce\nfrom itertools import permutations, combinations, zip_longest\nimport matplotlib.pyplot as plt\nimport time\nfrom operator impo...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T05:17:49.417", "Id": "203161", "Score": "12", "Tags": [ "python", "performance", "complexity" ], "Title": "Seating Students (partitioning sort of)" }
203161
<p>I have written a simple program to read file that contains record spread between multiple lines. There is requirement to read file from source that is dirty and contains line breaks which are unexpected.</p> <p>I would like to tune this if there is any suggestions. I am very new to Java programming. This is just to demonstrate to a technical team a algorithm to perform the same. It might be dirty but any feedback in welcome.</p> <pre><code>import java.io.*; import java.util.*; import java.util.function.Consumer; import java.util.stream.Stream; final class RawFile{ private InputStreamReader filereader; private char dlm; // Delimeter char of the file private int maxdlmcnt; // depending on number of columns assign num of dlm expected private int cntdlm; // this is a counter used while looping the file private StringBuffer bufferline; // this is to buffer if there is unexpected line breaks RawFile(String filename,int numcolmns) throws FileNotFoundException { try { filereader=new InputStreamReader(new FileInputStream(filename), "UTF-8"); dlm=' '; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block System.out.println("Encoding not supported"); } } RawFile(String filename,int numcolmns, char seperator) throws FileNotFoundException { try { filereader=new InputStreamReader(new FileInputStream(filename), "UTF-8"); dlm=seperator; maxdlmcnt=numcolmns-1; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block System.out.println("Encoding not supported"); } } int countdelimiters(char chararr[]) { int cnt=0; for(int i=0; i&lt;= chararr.length-1;i++){ if(chararr[i]==dlm) cnt=cnt+1; } return cnt; } List&lt;String&gt; readline() throws IOException { List&lt;String&gt; recordlist=new ArrayList&lt;String&gt;(); BufferedReader filerecords = null; Stream&lt;String&gt; recordstream = null; try{ bufferline=new StringBuffer(); filerecords=new BufferedReader(filereader); recordstream=filerecords.lines(); Consumer&lt;String&gt; readline = (rawline) -&gt; { int cnt=0; if(rawline!=null) { cnt=countdelimiters(rawline.toCharArray()); cntdlm=cntdlm+cnt; if (cnt==maxdlmcnt) { recordlist.add(rawline);cntdlm=0; } else if(cntdlm&gt;=maxdlmcnt) { bufferline.append(rawline); recordlist.add(bufferline.toString()); cntdlm=0; //reset the line count } else bufferline.append(rawline); } }; recordstream.forEach(readline); } finally { recordstream.close(); filerecords.close(); } return recordlist; } } public class ReadRawFile { public static void main(String args[]) throws FileNotFoundException, IOException { List&lt;String&gt; outputrecords=new ArrayList&lt;String&gt;(); String pathstr="C:\\HOMEWARE\\ITEC-Toolbox\\projects\\Training\\SAMPLE_COPY.txt"; RawFile recordlist=new RawFile(pathstr,29,'|'); outputrecords=recordlist.readline(); Consumer&lt;String&gt; strline=(n)-&gt;System.out.println(n); outputrecords.forEach(strline); } } </code></pre> <p>Let me also put some example record,</p> <pre><code>05|XXX476-319|458|AJKSDGAKSJDGJASDKJGASD|ASDJGASDFHANDVSNVSD|Babu|Villian|Pharmacy - Clinical Trials|London||United Kingdom|KJASDHKASJDGKASJDGAJKSDGJKASGD|A|Arewerwayo|Site Coordinator|Site Coordinator|||||0255555555||Denmark Hill|||London||SR5 3CS|United Kingdom 05|XXX476-419|432|KAJSHDKASDHAKSDHASDG|FKASDHASDKHASDKHASDSD|Mary|Wickel|E Daer Pantel|Gent||Belgium|JKASDGJASDGASJDGHASGDGASDASD|Els|Kristens|Pharma|Pharma|||||:+32(9)93326666|pharmacy.clinicaltrials@google.com|JGASDJGAS|C. He ymasewe 10|Entrance T32 - Route 5678 |Gant||B- 9995|Belgium 05|XXX476-319|458|AJKSDGAKSJDGJASDKJGASD|ASDJGASDFHANDVSNVSD|Babu|Villian|Pharmacy - Clinical Trials|London||United Kingdom|KJASDHKASJDGKASJDGAJKSDGJKASGD|A|Arewerwayo|Site Coordinator|Site Coordinator|||||0255555555||Denmark Hill|||London||SR5 3CS|United Kingdom </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T07:03:43.240", "Id": "391568", "Score": "0", "body": "What kind of records? An example of an input file and the corresponding output might be helpful in order to understand the goal better." }, { "ContentLicense": "CC BY-SA ...
[ { "body": "<p>Don’t use comments to explain what a variable holds. Instead, use descriptive variable names. For instance, use <code>delimiter</code> instead of <code>dlm</code>. The former is much easier to read. </p>\n\n<p>Use camelCase when naming methods like <code>countDelimiters</code> and variables like <...
{ "AcceptedAnswerId": "203187", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T07:00:28.343", "Id": "203163", "Score": "0", "Tags": [ "java", "file-system" ], "Title": "Java code for delimited raw file read with multi line record" }
203163
<p>I recently had the chance to try Codility's algorithm training, and the very first one in the list is <a href="https://app.codility.com/programmers/lessons/1-iterations/binary_gap/" rel="nofollow noreferrer">finding the longest binary gap of a given integer</a>.</p> <p>I tried to implement this in Swift, and after finishing it up, I looked at answers all over the internet. My approach is a bit different from what I have seen from others.</p> <hr /> <p><strong>What is a Binary Gap?</strong></p> <blockquote> <p>A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.</p> <p>For example, number <strong>9</strong> has binary representation <code>1001</code> and contains a binary gap of length <strong>2</strong>. The number <strong>529</strong> has binary representation <code>1000010001</code> and contains two binary gaps: one of length <strong>4</strong> and one of length <strong>3</strong>. The number <strong>20</strong> has binary representation <code>10100</code> and contains one binary gap of length <strong>1</strong>. The number <strong>15</strong> has binary representation <code>1111</code> and has no binary gaps. The number <strong>32</strong> has binary representation <code>100000</code> and has no binary gaps.</p> </blockquote> <hr /> <p><em>The following is from the console which makes it easy to understand the implementation.</em></p> <pre><code>Binary String of &quot;1041&quot; is: &quot;10000010001&quot; Position of 1's: [0, 6, 10] The longest binary gap is 5 </code></pre> <p><strong>Basically what I am doing is:</strong></p> <ol> <li>Iterating each binary character, and store the position/index of 1's in an array.</li> <li>As I am looping through, I find the binary gap between two 1's by subtracting the current index of <code>1</code> with previous index of <code>1</code>, so that it gives me how many <code>0</code>'s are present in between them. I then decrement whatever value I get by 1 ('cause arrays...).</li> <li>As I am looping through, I keep track of the longest binary gap in a variable.</li> </ol> <p>The complexity is <strong>O(n)</strong>, and I'd like to know if this approach is in any way efficient in terms of memory, or any scope of improvements with this? Thanks for your time.</p> <hr /> <p><strong>Code:</strong></p> <pre><code>public func getLongestBinaryGapFor(_ N : Int) -&gt; Int { var arrayOfIndexes:[Int] = [] let binaryString = String(N, radix:2) print(&quot;Binary String of \&quot;\(N)\&quot; is: \&quot;\(binaryString)\&quot;&quot;) var longestBinaryGap:Int = 0 var index = 0 for char in binaryString { if char == &quot;1&quot; { arrayOfIndexes.append(index) let currentBinaryGap = getCurrentBinaryGapFor(arrayOfIndexes) if arrayOfIndexes.count == 2 { longestBinaryGap = currentBinaryGap } else if index &gt; 2 { if currentBinaryGap &gt; longestBinaryGap { longestBinaryGap = currentBinaryGap } } } index += 1 } print(&quot;Position of 1's: \(arrayOfIndexes)&quot;) return longestBinaryGap } func getCurrentBinaryGapFor(_ array:[Int]) -&gt; Int { var currentBinaryGap = 0 if array.count &gt;= 2 { let currentPosition = array.count - 1 let previousPosition = currentPosition - 1 currentBinaryGap = array[currentPosition] - array[previousPosition] - 1 return currentBinaryGap } else { return currentBinaryGap } } </code></pre>
[]
[ { "body": "<h3>Naming</h3>\n\n<p>According to the\n<a href=\"https://swift.org/documentation/api-design-guidelines\" rel=\"nofollow noreferrer\">API Design Guidelines</a>,\nneedless word should be omitted, and prepositional phrases should be made\nargument labels. Also variable names should generally be lower ...
{ "AcceptedAnswerId": "203189", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T08:24:31.107", "Id": "203166", "Score": "3", "Tags": [ "performance", "algorithm", "array", "swift", "complexity" ], "Title": "Swift - Finding longest binary gap of a given integer" }
203166
<p>I have function which returns a vector or strings (values from an sqlite3 table).</p> <p>For each of those strings I need to generate a Qt Checkbox, if it does not exist yet.</p> <p>My first version looks like this:</p> <pre><code>const auto results = queryStrings(QStringLiteral("select ...")); const auto pred = [this](const QString&amp; name) { return this-&gt;findChild&lt;QCheckBox*&gt;(name + QStringLiteral("_CB")) == nullptr; }; for (const auto&amp; sourceName : boost::adaptors::filter(results, pred)) { // create checkbox ... } </code></pre> <p>Alternatively I could use something like this:</p> <pre><code>const auto pred = [this](const QString&amp; name) { return this-&gt;findChild&lt;QCheckBox*&gt;(name + QStringLiteral("_CB")) == nullptr; }; const auto results = queryStrings(QStringLiteral("select ..."), pred); for (const auto&amp; typeName : results) { // create checkbox ... } </code></pre> <p>As this code can be called quite frequently, I was wondering if the use of boost::adaptors::filter comes with a overhead or if the second second version with the predicate passed to the queryStrings function is better.</p>
[]
[ { "body": "<p>You won't know for sure which is the fastest unless you test it. And you won't know if that portion of the code is what matters unless you profile its runtime execution. When you care about performance, testing in real time is the only way.</p>\n\n<p>If you look at it from a more theoretical persp...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T09:03:53.120", "Id": "203171", "Score": "-1", "Tags": [ "c++", "c++14", "boost", "qt" ], "Title": "How to use a predicate to create or filter vector" }
203171
<p>Requirement is to monitor the changes in a <code>List&lt;T&gt;</code>, possible changes are <code>Add / Remove / Update</code>, which are registered in an Audit log, which I do in the code underneath using a <code>Dictionary</code>. Now user can take an action to revert each of the operations, using an integrated <code>Action</code> delegate. Each operation runs its respective Revert operation. Please note here undo is not about notification, like <code>ObservableCollection&lt;T&gt;</code> but removal at the later time based on user discretion. Following is my design, please suggest, what shall be done to further improvise.</p> <hr> <pre><code>public class ActionWrapper&lt;T&gt; { public int Index {get;set;} public T OriginalValue {get;set;} public T NewValue {get;set;} public Action&lt;int,T&gt; Action {get;set;} } public class ChangeList&lt;T&gt; : List&lt;T&gt; where T:class,IEquatable&lt;T&gt; { public Dictionary&lt;T,ActionWrapper&lt;T&gt;&gt; ActionMap {get;set;} public ChangeList() { ActionMap = new Dictionary&lt;T,ActionWrapper&lt;T&gt;&gt;(); } public new void Add(T item) { base.Add(item); var actionWrapper = new ActionWrapper&lt;T&gt; { Action = new Action&lt;int,T&gt;(RevertAdd), Index = this.FindIndex(x =&gt; x.Equals(item)), NewValue = item, OriginalValue = null }; ActionMap[actionWrapper.NewValue] = actionWrapper; } public new void Remove(T item) { var actionWrapper = new ActionWrapper&lt;T&gt; { Action = new Action&lt;int, T&gt;(RevertRemove), Index = this.FindIndex(x =&gt; x.Equals(item)), NewValue = null, OriginalValue = item }; if(actionWrapper.Index &lt; 0) return; base.Remove(actionWrapper.OriginalValue); ActionMap[actionWrapper.OriginalValue] = actionWrapper; } public void Update(T actualValue,T newValue) { var actionWrapper = new ActionWrapper&lt;T&gt; { Action = new Action&lt;int, T&gt;(RevertUpdate), Index = this.FindIndex(x =&gt; x.Equals(actualValue)), NewValue = newValue, OriginalValue = actualValue }; if (actionWrapper.Index &lt; 0) return; base[actionWrapper.Index] = newValue; ActionMap[actionWrapper.NewValue] = actionWrapper; } public void RevertAdd(int index, T actual) { base.Remove(actual); } public void RevertRemove(int index,T actual) { base.Add(actual); } public void RevertUpdate(int index,T actual) { base[index] = actual; } } </code></pre> <h2>Use Case</h2> <pre><code>void Main() { var changeList = new ChangeList&lt;string&gt;(); changeList.Add("Person1"); changeList.Add("Person2"); changeList.Add("Person3"); changeList.Add("Person4"); changeList.Add("Person5"); changeList.Add("Person6"); changeList.Add("Person7"); changeList.Dump(); // Print statement var actionMapUpdateAdd = changeList.ActionMap["Person5"]; actionMapUpdateAdd.Action(actionMapUpdateAdd.Index, actionMapUpdateAdd.NewValue); changeList.Dump(); // Print statement changeList.Update("Person7","Person77"); changeList.Dump(); // Print statement var actionMapUpdate = changeList.ActionMap["Person77"]; actionMapUpdate.Action(actionMapUpdate.Index,actionMapUpdate.OriginalValue); changeList.Dump(); // Print statement changeList.Remove("Person6"); changeList.Dump(); // Print statement var actionMapRemove = changeList.ActionMap["Person6"]; actionMapRemove.Action(actionMapRemove.Index, actionMapRemove.OriginalValue); changeList.Dump(); // Print statement } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T14:07:00.970", "Id": "391609", "Score": "1", "body": "As a small info, given the `ActionMap` as a public property with a public setter is just asking for problems, for that having a method recovering the `ActionWrapper` should great...
[ { "body": "<h3>Edge cases</h3>\n\n<p>This fails to handle several edge-cases:</p>\n\n<ul>\n<li>Undoing a remove action multiple times results in that item being added back multiple times.</li>\n<li>Undoing an update action after other items have been inserted at a lower index causes the wrong items to be replac...
{ "AcceptedAnswerId": "203182", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T11:43:44.593", "Id": "203176", "Score": "6", "Tags": [ "c#", "framework" ], "Title": "Undo Framework Design (Revert the changes in the collection)" }
203176
<p>In an attempt to learn more with Java, I decided to challenge myself by creating a GUI-based, multi-threaded chat room. Currently, you run the Client and it prompts you to either create or join a server based on an IP. Port used is 9000. Any suggestions on how I can improve?</p> <p>Server.java:</p> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.sql.Timestamp; import java.util.HashSet; import java.util.Set; public class Server extends Thread { /** * Used to write to all the connected clients. */ private static final Set&lt;PrintWriter&gt; WRITERS = new HashSet&lt;&gt;(); /** * Used to keep track of all of th enames of connected clients. */ private static final Set&lt;String&gt; NAMES = new HashSet&lt;&gt;(); /** * Used to keep track of the current client's ID for logging purposes. */ private static int clientId = 1; /** * Used when creating a server. */ private final ServerSocket listener; public Server(ServerSocket listener) { this.listener = listener; } /** * Used to log messages. * * @param message */ public static void log(String message) { String timestamp = new Timestamp(System.currentTimeMillis()).toString(); timestamp = timestamp.substring(0, timestamp.length() - 4); System.out.println("[" + timestamp + "] " + message); } /** * Returns the ServerSocket listener. * * @return */ public ServerSocket getListener() { return this.listener; } @Override public void run() { if (listener != null) { try { if (listener.isBound()) { log("Server started on " + (listener.getInetAddress().getHostAddress()) + " and listening on port " + ServerConstants.PORT); } while (true) { new User(listener.accept(), clientId++).start(); } } catch (IOException e) { e.printStackTrace(); } finally { try { listener.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * Creates a server and starts accepting inputs. * * @param port * @throws IOException */ public static Server createServer(int port) throws IOException { return new Server(new ServerSocket(port)); } /** * This class listens for and sends messages to messages from all clients. * * @author ivisc * */ private static class User extends Thread { private Socket socket; private PrintWriter out; private BufferedReader in; private String address; private String name; private int id; public User(Socket sock, int id) { this.socket = sock; this.id = id; this.address = socket.getInetAddress().getHostAddress(); } @Override public void run() { try { log("Starting connection from " + this.toString()); // Start up our variables for use with the socket. out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Ask for a name while (true) { out.println("ENTERNAME"); String line = in.readLine(); if (line == null) { return; } if (!Filter.filter(line)) { out.println("INVALIDNAME"); } else { synchronized (NAMES) { if (!NAMES.contains(line)) { NAMES.add(line); name = line; out.println("NAMEACC"); break; } } } } WRITERS.add(out); log("Registering " + this.toString() + " (" + name + ")"); for (PrintWriter writer : WRITERS) { writer.println("NEWMEM" + name); } // Now we listen for names while (true) { String message = in.readLine(); if (message == null) { return; } if (!Filter.filter(message)) { out.println("INVALIDMESSAGE"); } else { for (PrintWriter writer : WRITERS) { writer.println("MESSAGE" + name + ": " + message); } } } } catch (IOException e) { log(this.toString() + " is disconnecting..."); } finally { log("Shutting down I/O from " + this.toString() + " (" + id + ")"); try { out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public String toString() { return address + "(" + id + ")"; } } } </code></pre> <p>Client.java:</p> <pre><code>import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; @SuppressWarnings("serial") public class Client extends JFrame { private JTextField textField; private JTextArea textArea; private Socket socket; private PrintWriter out; private BufferedReader in; public Client() { textField = new JTextField(40); getContentPane().add(textField, BorderLayout.SOUTH); textField.setEditable(false); textArea = new JTextArea(); getContentPane().add(textArea, BorderLayout.NORTH); textArea.setEditable(false); getContentPane().add(new JScrollPane(textArea), BorderLayout.CENTER); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { out.println(textField.getText()); textField.setText(""); } }); setPreferredSize(new Dimension(800, 600)); pack(); setSize(getPreferredSize()); setLocationRelativeTo(null); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void initVars() throws IOException { this.out = new PrintWriter(socket.getOutputStream(), true); this.in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } public void connect(String address) { try { this.socket = new Socket(address, ServerConstants.PORT); initVars(); this.textField.setEditable(true); Server.log("Connected to " + address); this.setVisible(true); while (true) { new ServerListener(out, in).start(); } } catch (IOException e) { e.printStackTrace(); } } public void connect(Server server) { try { String address = server.getListener().getInetAddress().getHostAddress(); this.socket = new Socket(address, ServerConstants.PORT); initVars(); this.textField.setEditable(true); Server.log("Connected to " + address); this.setVisible(true); while (true) { new ServerListener(out, in).start(); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { Scanner s = new Scanner(System.in); Object[] options = new Object[] { "Start", "Join", "Cancel" }; int input = JOptionPane.showOptionDialog(null, "Would you like to create or join a server?", "Chat Room Selection", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[1]); Client client = new Client(); switch (input) { case 0: try { Server server = Server.createServer(ServerConstants.PORT); server.start(); client.connect(server); } catch (IOException e) { e.printStackTrace(); } break; case 1: String address = JOptionPane.showInputDialog("Please enter server IP"); if (address != null) { client.connect(address); } break; case 2: System.exit(0); break; } s.close(); } private class ServerListener extends Thread { private PrintWriter out; private BufferedReader in; public ServerListener(PrintWriter out, BufferedReader in) { this.out = out; this.in = in; } @Override public void run() { while (true) { try { handle(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } } public void handle(String message) throws IOException { System.out.println("handling " + message); if (message == null) { return; } System.out.println(message); if (message.startsWith("MESSAGE")) { message = message.substring(7); textArea.append(message + "\n"); } else if (message.startsWith("ENTERNAME")) { while (true) { String name = JOptionPane.showInputDialog("Please enter a username"); out.println(name); String response = in.readLine(); if (response.equals("INVALIDNAME")) { JOptionPane.showMessageDialog(null, "Name does not pass Name Filter", "Invalid Name", JOptionPane.ERROR_MESSAGE); } else { break; } } } else if (message.startsWith("NEWMEM")) { String name = message.substring(6); textArea.append(name + " has joined the server.\n"); } } } } </code></pre> <p>There are a few references to ServerConstants.java and Filter.java here, but I won't include them for brevity's sake. Basically, ServerConstants is an abstract interface that just defines the port to use, and Filter is a simple name filter using a list of "bad words" (I believe it's <a href="https://www.freewebheaders.com/full-list-of-bad-words-banned-by-google/" rel="nofollow noreferrer">this one</a> that I used).</p> <p>I know I didn't comment everything, and adding <code>throws</code> statements might not be best practice, and extending from <code>JFrame</code> is usually not recommended, but, based on everything here, any suggestions?</p>
[]
[ { "body": "<p>First of all, it's nice to see at least some comments. It makes understanding your code a lot easier. </p>\n\n<p>To the suggestions:<br>\nYes, you are right, inheriting from JFrame isn't good. Inheriting from Thread isn't good, too. Your case is a little bit worse because your code says, your cli...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T13:50:39.703", "Id": "203181", "Score": "0", "Tags": [ "java", "multithreading", "swing", "gui", "chat" ], "Title": "Java Multi-threaded Chat Room" }
203181
<h2>First off</h2> <p>I'm quite new to Python, there will be a lot of messy/overcomplicated code, that's why I'm posting on this site.</p> <p>This code is written in Python (2.7) using the Tkinter library.</p> <h2>Questions</h2> <p>To allow for viewing/editing large files, I am loading the file and saving it to a variable, then displaying only the text that can be seen. Is this the best way of going about this?</p> <p>I have chosen to use a class here, because there are a lot of global variables. I also want to allow for scalability, so is this a good choice?</p> <p>If I came back to this in a year or so, would I be able to understand what is going on?</p> <p>Any and all criticism to do with formatting and Pythonicness is welcome.</p> <h2>Code</h2> <pre><code>class Window(): def __init__(self): &quot;&quot;&quot;imports and define global vars&quot;&quot;&quot; import binascii, Tkinter, tkFileDialog self.binascii = binascii self.Tkinter = Tkinter self.tkFileDialog = tkFileDialog self.root = self.Tkinter.Tk() self.lineNumber = 0 self.fileName = &quot;&quot; self.lines = [] self.width = 47 self.height = 20 self.lastLine = 0.0 self.rawData = &quot;&quot; self.defaultFiles = ( (&quot;Hexadecimal Files&quot;, &quot;*.hex&quot;), (&quot;Windows Executables&quot;, &quot;*.exe&quot;), (&quot;Linux Binaries&quot;, &quot;*.elf&quot;), (&quot;all files&quot;, &quot;*.*&quot;) ) def resize(self, event = None): &quot;&quot;&quot;called when the window is resized. Re-calculates the chars on each row&quot;&quot;&quot; self.width = self.mainText.winfo_width() / 8 self.height = self.mainText.winfo_height() / 16 if not self.width / 3 == 0: self.data = self.binascii.hexlify(self.rawData)[2:] dataSave = self.data lines = [] chars = self.width - (self.width / 3) while len(self.data) &gt; 0: if len(self.data) &gt;= chars: lines.append(self.data[:chars]) self.data = self.data[chars:] else: lines.append(self.data) self.data = &quot;&quot; self.data = dataSave self.lines = lines self.mainText.delete(&quot;1.0&quot;,&quot;end&quot;) self.mainText.insert(&quot;1.0&quot;, self.getBlock(self.lineNumber)) def openFile(self, filename): &quot;&quot;&quot;Opens a file and displays the contents&quot;&quot;&quot; self.fileName = filename with open(filename,&quot;rb&quot;) as f: rawData = chr(0) + f.read() self.rawData = rawData self.data = self.binascii.hexlify(rawData)[2:] dataSave = self.data lines = [] chars = self.width - (self.width / 3) print self.width while len(self.data) &gt; 0: if len(self.data) &gt;= chars: lines.append(self.data[:chars]) self.data = self.data[chars:] else: lines.append(self.data) self.data = &quot;&quot; self.data = dataSave self.lines = lines self.mainText.delete(&quot;1.0&quot;,&quot;end&quot;) self.mainText.insert(&quot;1.0&quot;, self.getBlock(0)) self.lineNumber = 0 def saveFile(self, filename, data = None): &quot;&quot;&quot;saves the 'lines' variable (keeps track of the data) to a file&quot;&quot;&quot; if data is None: data = &quot;&quot;.join(self.lines) with open(filename, &quot;wb&quot;) as f: f.write(self.binascii.unhexlify(data)) def saveAll(self, event = None): &quot;&quot;&quot;saves a file (for binding a key to)&quot;&quot;&quot; self.setBlock(self.mainText.get(&quot;1.0&quot;,&quot;end&quot;),self.lineNumber) self.saveFile(self.fileName) def saveClose(self, event = None): &quot;&quot;&quot;Saves and closes (for binding a key to&quot;&quot;&quot; self.saveAll() self.root.destroy() def saveAsWindow(self, event = None): &quot;&quot;&quot;Opens the 'save as' popup&quot;&quot;&quot; f = self.tkFileDialog.asksaveasfilename(filetypes = self.defaultFiles) if f is None or f is &quot;&quot;: return else: self.saveFile(f) self.fileName = f def openWindow(self, event = None): &quot;&quot;&quot;Opens the 'open' popup&quot;&quot;&quot; f = self.tkFileDialog.askopenfilename(filetypes = self.defaultFiles) if f is None or f is &quot;&quot;: return else: self.openFile(f) def q(self, event = None): &quot;&quot;&quot;quits (for binding a key to&quot;&quot;&quot; self.root.destroy() def neatify(self,data): &quot;&quot;&quot;adds a space every 2 chars (splitss into bytes)&quot;&quot;&quot; out = &quot;&quot; for line in data: count = 0 for char in line: if count == 2: count = 0 out += &quot; &quot; + char else: out += char count += 1 out += &quot;\n&quot; return out def getBlock(self, lineNum): &quot;&quot;&quot;gets a block of text with the line number corresponding to the top line&quot;&quot;&quot; self.formattedData = self.neatify(self.lines[lineNum:lineNum+self.height]) return self.formattedData def setBlock(self, data, lineNum): &quot;&quot;&quot;sets a block (same as getBlock but sets)&quot;&quot;&quot; rawData = data.replace(&quot; &quot;,&quot;&quot;).split(&quot;\n&quot;) data = [] for line in rawData: if not line == &quot;&quot;: data.append(line) if len(data) &lt; self.height: extra = len(data) else: extra = self.height for i in range(lineNum,lineNum + extra): self.lines[i] = data[i - lineNum] def scrollTextUp(self, event = None): &quot;&quot;&quot;Some may argue 'scrollTextDown' but this is what happens when you press the up arrow&quot;&quot;&quot; if not self.lineNumber &lt;= 0: self.setBlock(self.mainText.get(&quot;1.0&quot;,&quot;end&quot;),self.lineNumber) self.lineNumber -= 1 self.mainText.delete(&quot;1.0&quot;,&quot;end&quot;) self.mainText.insert(&quot;1.0&quot;, self.getBlock(self.lineNumber)) def scrollTextDown(self, event = None): &quot;&quot;&quot;same as above except the opposite&quot;&quot;&quot; if not self.lineNumber &gt;= len(self.lines) - self.height: self.setBlock(self.mainText.get(&quot;1.0&quot;,&quot;end&quot;),self.lineNumber) self.lineNumber += 1 self.mainText.delete(&quot;1.0&quot;,&quot;end&quot;) self.mainText.insert(&quot;1.0&quot;, self.getBlock(self.lineNumber)) def scroll(self, event = None, direction = None): &quot;&quot;&quot;calls the correct scroll function&quot;&quot;&quot; if self.mainText.index(&quot;insert&quot;).split(&quot;.&quot;)[0] == str(self.height + 1): self.scrollTextDown() elif self.mainText.index(&quot;insert&quot;).split(&quot;.&quot;)[0] == &quot;1&quot;: cursorPos = self.mainText.index(&quot;insert&quot;) self.scrollTextUp() self.mainText.mark_set(&quot;insert&quot;, cursorPos) def defineWidgets(self): &quot;&quot;&quot;defines the widgets&quot;&quot;&quot; self.menu = self.Tkinter.Menu(self.root) self.filemenu = self.Tkinter.Menu(self.menu, tearoff = 0) self.filemenu.add_command(label = &quot;Save&quot;, command = self.saveAll, accelerator = &quot;Ctrl-s&quot;) self.filemenu.add_command(label = &quot;Save as...&quot;, command = self.saveAsWindow, accelerator = &quot;Ctrl-S&quot;) self.filemenu.add_command(label = &quot;Open...&quot;, command = self.openWindow, accelerator = &quot;Ctrl-o&quot;) self.filemenu.add_separator() self.filemenu.add_command(label = &quot;Quit&quot;, command = self.saveClose, accelerator = &quot;Ctrl-q&quot;) self.filemenu.add_command(label = &quot;Quit without saving&quot;, command = self.root.destroy, accelerator = &quot;Ctrl-Q&quot;) self.menu.add_cascade(label = &quot;File&quot;, menu = self.filemenu) self.mainText = self.Tkinter.Text(self.root, width = 47, height = 20) def initWidgets(self): &quot;&quot;&quot;initialises the widgets. Also key bindings etc&quot;&quot;&quot; self.mainText.pack(fill = &quot;both&quot;, expand = 1) self.mainText.insert(&quot;1.0&quot;, self.getBlock(0)) self.root.config(menu = self.menu) #up and down bound to the scroll function to check if the text should scroll self.root.bind(&quot;&lt;Down&gt;&quot;, self.scroll) self.root.bind(&quot;&lt;Up&gt;&quot;, self.scroll) self.root.bind(&quot;&lt;Control-s&gt;&quot;, self.saveAll) self.root.bind(&quot;&lt;Control-o&gt;&quot;, self.openWindow) self.root.bind(&quot;&lt;Control-S&gt;&quot;, self.saveAsWindow) self.root.bind(&quot;&lt;Control-q&gt;&quot;, self.saveClose) self.root.bind(&quot;&lt;Control-Q&gt;&quot;, self.q) self.root.bind(&quot;&lt;Configure&gt;&quot;, self.resize) self.root.protocol('WM_DELETE_WINDOW', self.saveClose) win = Window() win.defineWidgets() win.initWidgets() win.root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T07:25:20.997", "Id": "391671", "Score": "1", "body": "This is the first time I come across the practice, so maybe I am missing something, but what are the benefits of binding modules to instance attributes?" }, { "ContentLic...
[ { "body": "<h1>Style</h1>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> is the de-facto standard style guide for Python and adhering to it will make your code look like Python code to others:</p>\n\n<ul>\n<li>variable and method names should be <code>snake_case...
{ "AcceptedAnswerId": "203284", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T15:05:17.827", "Id": "203188", "Score": "7", "Tags": [ "python", "file", "serialization", "tkinter", "text-editor" ], "Title": "A little Python hex editor" }
203188
<p>I have found the following interesting challenge on the web:</p> <blockquote> <p><strong>Deficient Numbers</strong><br> A number is considered deficient if the sum of its factors is less than twice that number.<br> For example: 10 is a deficient number because its factors are 1, 2, 5, 10 and their sum is 1 + 2 + 5 + 10 = 18 which is less than 10 * 2 = 20.<br> <strong>Challenges</strong><br> <em>Easy level</em>: write a program to verify whether a given number is deficient or not.<br> <em>Medium level</em>: write a program to find all the deficient numbers in a range.<br> <em>Hard level</em>: given a number, write a program to display its factors, their sum and then verify whether it's deficient or not.</p> </blockquote> <p>I implemented it in C: </p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #define DEBUG 1 /* XXX EASY-OPTION IMPLEMENTATION A list data structure is used to store the factors of a given number. A simple boolean-like data type is then returned by the main isDeficient function. */ typedef enum bool bool; enum bool { false, true }; typedef struct ListElem ListElem; struct ListElem { int value; ListElem* next; }; typedef struct List List; struct List { ListElem* head; int length; }; List* listInit() { List* list = (List*) malloc(sizeof(List)); list-&gt;head = NULL; list-&gt;length = 0; return list; } ListElem* listAppend(List* list, int elem) { ListElem* newHead = (ListElem*) malloc(sizeof(ListElem)); newHead-&gt;value = elem; newHead-&gt;next = list-&gt;head; list-&gt;head = newHead; list-&gt;length++; return newHead; } void listPrint(List* list) { ListElem* head = list-&gt;head; printf("list &gt; "); do { printf("%i ", head-&gt;value); head = head-&gt;next; } while (head != NULL); printf("\n"); } void listSort(List* list) { int inactive = 0, debug = 0; while (inactive &lt; list-&gt;length - 1) { inactive = 0; ListElem* previous = NULL; // Initialise pointers... ListElem* current = list-&gt;head; ListElem* next = list-&gt;head-&gt;next; for (int i = 0; i &lt; list-&gt;length - 1; i++) { if (current-&gt;value &gt; next-&gt;value) { if (i != 0) previous-&gt;next = next; current-&gt;next = next-&gt;next; next-&gt;next = current; if (i == 0) // Update list head... list-&gt;head = next; inactive = 0; previous = next; next = current-&gt;next; } else { inactive++; previous = current; current = next; next = next-&gt;next; } } debug += list-&gt;length - 1; } #if DEBUG printf("Debug info: sorting toke %i iterations.\n", debug); #endif } bool isInList(List* l, int elem) { ListElem* listElem = l-&gt;head; for (int i = 0; i &lt; l-&gt;length; i++) { int value = listElem-&gt;value; if (value == elem) return true; listElem = listElem-&gt;next; } return false; } List* findFactors(int n) { List* factors = listInit(); int tempRes = 0; int debug = 1; listAppend(factors, 1); if (!(isInList(factors, n))) // Avoid duplicates only when n = 1... listAppend(factors, n); for (int d = 2; d &lt;= n / 2; d++) { // The &lt;= operator is necessary when n = 4 or the iterations don't start... if (!(n % d)) { tempRes = n / d; if (isInList(factors, tempRes)) break; listAppend(factors, d); if (!(isInList(factors, tempRes))) // Avoid duplicate entries when the divisor and the result of the division are the same... listAppend(factors, tempRes); } debug++; } #if DEBUG printf("Debug info: %i's factors found with %i iterations.\n", n, debug); listSort(factors); listPrint(factors); #endif return factors; } int calculateSum(List* list) { int sum = 0; ListElem* listElem = list-&gt;head; for (int i = 0; i &lt; list-&gt;length; i++) { sum += listElem-&gt;value; listElem = listElem-&gt;next; } return sum; } bool isDeficient(int n) { List* f = findFactors(n); if (calculateSum(f) &lt; 2 * n) return true; return false; } // XXX MEDIUM-OPTION IMPLEMENTATION List* findDeficients(int min, int max) { List* deficients = listInit(); for (int i = min; i &lt;= max; i++) { if (isDeficient(i)) listAppend(deficients, i); } return deficients; } // XXX HARD-OPTION IMPLEMENTATION int main(int argc, char* argv[]) { if (argc != 2) { printf("Error: arguments are not one!\n"); return 0; } int n = atoi(argv[1]); List* facts = findFactors(n); printf("The factors of %i are:\n", n); listPrint(facts); int sum = calculateSum(facts); printf("Their sum is:\n%i\n", sum); if (sum &lt; 2 * n) printf("%i IS deficient.\n", n); else printf("%i IS NOT deficient.\n", n); return 0; } </code></pre> <p>What about it? In particular, I would like to ask you for a feedback about the List structure and the sorting function. Is their code readable and understandable? Could it be improved with regard to performance?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T17:06:46.603", "Id": "391630", "Score": "1", "body": "regarding: `printf(\"Error: arguments are not one!\\n\")` 1) Error messages should be output to `stderr` rather than `stdout`. 2) when the error message is about the command li...
[ { "body": "<h3>The algorithm:</h3>\n\n<ol>\n<li><p>Well, <code>findFactors</code> is far too inefficient. Better do a prime-factoring, and then create the list of all factors from that.</p></li>\n<li><p>If you need to do enough prime-factorings, consider pre-calculating all candidate primes, be it during or bef...
{ "AcceptedAnswerId": "203198", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T16:06:30.373", "Id": "203192", "Score": "5", "Tags": [ "c", "programming-challenge", "sorting", "linked-list" ], "Title": "Deficient Numbers" }
203192
<p>I have been programming with Python on-and-off for about 2 years now, even now I still find that when I look at other applications I struggle to follow along with their classes/objects. Please help me improve upon my own OOP experience.</p> <p>Here is one of my more recent projects for a Django Website.</p> <p><code>pokemon.py</code></p> <pre><code># pylint: disable=too-many-instance-attributes,too-many-locals,too-many-branches,too-many-statements """ Represent Pokemon objects """ from pokedex.models import Pokemon as pokemon, PokemonTypes, PokemonStats, PokemonAbilities, \ PokemonSpecies, PokemonGenderRatios, PokemonProse, PokemonMoves, Types class PokemonList: """ A Class to represent all Pokemon """ def __init__(self, page): """ Gets 100 pokemon at a time based off of the GET variable "page" :param page: Defaults to 1. Is used for pagination """ self.poke_list = [] if page == 1: all_rows = [list(x) for x in list( pokemon.objects.filter(id__range=(0, 100)).values_list( 'id', 'identifier', 'height', 'weight'))] else: OFFSET = int(page) * 100 all_rows = [list(x) for x in list( pokemon.objects.filter(id__range=(OFFSET - 99, OFFSET)).values_list( 'id', 'identifier', 'height', 'weight'))] for row in all_rows: type_list = list(Types.objects.filter( pokemontypes_type__pokemon__id=row[0]).values_list('identifier', flat=True)) row.append(type_list) self.poke_list.append(row) class Pokemon: """ A Class to represent a pokemon. """ def __init__(self, poke_id): """ Instantiate a pokemon object with base information :param poke_id: id of the pokemon to get from the database """ # Select base information about a pokemon poke = pokemon.objects.get(id=poke_id) self.id = poke.id self.static_path = 'pokedex/img/profiles/' + str(self.id) + '.png' self.long_id = str(self.id).zfill(3) self.identifier = poke.identifier self.species_id = poke.species.identifier self.height = poke.height / 10.0 self.weight = poke.weight / 10.0 self.base_experience = poke.base_experience self.evolution_chain = self._get_evolution_chain() self.type = [] self.available_types = ['normal', 'fire', 'water', 'electric', 'grass', 'ice', 'fighting', 'poison', 'ground', 'flying', 'psychic', 'bug', 'rock', 'ghost', 'dragon', 'dark', 'steel', 'fairy'] self.type_static = [] # Get Type (may be multiple) types = PokemonTypes.objects.filter(pokemon=self.id).select_related('type').values_list( 'type__identifier', flat=True) for t in types: self.type.append(t) self.type_static.append('pokedex/img/types' + t + '-type.png') # Get base stats stat = [list(x) for x in list( PokemonStats.objects.filter(pokemon=self.id).select_related('stat').values_list( 'stat__identifier', 'base_stat'))] self.stats = [] for s in stat: tempdict = { s[0]: s[1] } self.stats.append(tempdict) # Get Abilities ability = PokemonAbilities.objects.filter( pokemon=self.id).select_related('ability').values_list( 'ability__identifier', flat=True) self.abilities = [] for item in ability: self.abilities.append(item) # Get Moves self.moves = _get_moves() # Get Gender Rates gender_obj = PokemonGenderRatios.objects.select_related('ratio').get(pokemon=self.id) if gender_obj is not None: self.percent_male, self.percent_female = gender_obj.ratio.percent_male, \ gender_obj.ratio.percent_female # Get Description if applicable try: desc_obj = PokemonProse.objects.get(pokemon=self.id) self.description = desc_obj.description except PokemonProse.DoesNotExist: pass def prev_pokedex(self): """ Returns a dictionary of information about the previous pokemon in pokedex (path to image, id, and identifier) """ prev_id = self.id - 1 if prev_id &gt; 721 or prev_id &lt; 1: return None path_to_image = '/pokedex/img/profiles/' + str(prev_id) + '-small.png' identifier = pokemon.objects.values_list('identifier', flat=True).get(id=prev_id) prev_pokemon = { 'image': path_to_image, 'id': prev_id, 'identifier': identifier } return prev_pokemon def next_pokedex(self): """ Returns a dictionary of information about the next pokemon in pokedex (path to image, id, and identifier) """ next_id = self.id + 1 if next_id &gt; 721 or next_id &lt; 1: return None path_to_image = '/pokedex/img/profiles/' + str(next_id) + '-small.png' identifier = pokemon.objects.values_list('identifier', flat=True).get(id=next_id) next_pokemon = { 'image': path_to_image, 'id': next_id, 'identifier': identifier } return next_pokemon def _get_evolution_chain(self): """ Queries for Pokemon Evolution Chain """ # Gather Evolution Chain evolution_chain = { 'id': self.id, 'identifier': self.identifier } # Get previous evolution try: evolves_from = PokemonSpecies.objects.get(id=self.id) except PokemonSpecies.DoesNotExist: evolves_from = None if evolves_from is not None and evolves_from.evolves_from_species_id is not None: evolution = {'id': evolves_from.evolves_from_species_id} evolution['identifier'] = pokemon.objects.get(id=evolution['id']).identifier evolution_chain.insert(0, evolution) try: prev_evolv = PokemonSpecies.objects.get(id=evolution['id']) except PokemonSpecies.DoesNotExist: prev_evolv = None if prev_evolv is not None and prev_evolv.evolves_from_species_id is not None: evolution = {'id': prev_evolv.evolves_from_species_id} evolution['identifier'] = pokemon.objects.get(id=evolution['id']).identifier evolution_chain.insert(0, evolution) # Get Next Evolution try: next_evol = PokemonSpecies.objects.get(evolves_from_species_id=self.id) except PokemonSpecies.DoesNotExist: next_evol = None if next_evol is not None and next_evol.id is not None: evolution = {'id': next_evol.id} evolution['identifier'] = pokemon.objects.get(id=evolution['id']).identifier evolution_chain.append(evolution) try: next_evol = PokemonSpecies.objects.get(evolves_from_species_id=evolution['id']) except PokemonSpecies.DoesNotExist: next_evol = None if next_evol is not None and next_evol.id is not None: evolution = {'id': next_evol.id} evolution['identifier'] = pokemon.objects.get(id=evolution['id']).identifier evolution_chain.append(evolution) return evolution_chain def _get_moves(self): """ Get available moves """ moves = [list(x) for x in list( PokemonMoves.objects.filter(pokemon=self.id).select_related( 'move__type', 'move').values_list( 'move__identifier', 'move__type__identifier', 'move__power', 'move__pp', 'move__accuracy'))] moves_list = [] move_ids = [] for move in moves: if move[0] not in move_ids: temp_list = [move[0], move[1], move[2], move[3], move[4]] moves_list.append(temp_list) move_ids.append(move[0]) return moves_list def __str__(self): """ Returns Identifier when str() is called""" return self.identifier </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T06:46:42.673", "Id": "391670", "Score": "2", "body": "Hi, what is the `pokedex` module you are using? Is it something you wrote or some well known Pokemon library?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": ...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T16:42:25.103", "Id": "203195", "Score": "5", "Tags": [ "python", "object-oriented", "django", "pokemon" ], "Title": "Python Class to represent a Pokemon" }
203195
<p>I'm trying to solve the OpenAI BipedalWalker-v2 by using a one-step actor-critic agent. I'm implementing the solution using python and tensorflow. My question is whether the code is slow because of the nature of the task or because the code is inefficient, or both.</p> <p>I'm following this pseudo-code taken from the Book <a href="https://rads.stackoverflow.com/amzn/click/com/0262193981" rel="nofollow noreferrer" rel="nofollow noreferrer">Reinforcement Learning An Introduction</a> by Richard S. Sutton and Andrew G. Barto.</p> <p><a href="https://i.stack.imgur.com/Ysx0Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ysx0Y.png" alt="enter image description here" /></a></p> <h1>My Agent Class</h1> <pre><code>import tensorflow as tf import numpy as np import gym import matplotlib.pyplot as plt class agent_episodic_continuous_action(): def __init__(self, lr,gamma,sample_variance, s_size,a_size,dist_type): self.gamma = gamma self.I = 1 self.delta = 1 self.dist_type = dist_type self.is_actor_brain_present = False self.is_critic_brain_present = False self.s_size = s_size self.state_in= tf.placeholder(shape=[None,s_size],dtype=tf.float32) self.a_size=a_size self.cov = tf.eye(a_size) self.reduction = sample_variance #0.01 self.weights_actor ={} self.biases_actor ={} self.weights_critic ={} self.biases_critic ={} self.time_step_info = {'s':0,'a':0,'r':0,'s1':0,'d':0} self.reward = tf.placeholder(shape=[None,1],dtype=tf.float32) if a_size &gt; 1: self.action_holder = tf.placeholder(shape=[None,a_size],dtype=tf.float32) else: self.action_holder = tf.placeholder(shape=[None],dtype=tf.float32) self.gradient_holders = [] self.optimizer = tf.train.AdamOptimizer(learning_rate=lr) def save_model(self,path,sess): self.saver.save(sess, path) def load_model(self,path,sess): self.saver.restore(sess, path) def weights_init_actor(self,hidd_layer,mean,stddev): num_input = self.s_size num_output = self.a_size n_hidden_1 = hidd_layer[0] num_hidden_layers = len(hidd_layer) self.weights_actor['h_{0}'.format(0)] = tf.Variable(tf.random_normal([num_input, n_hidden_1],mean=mean,stddev=stddev),name='actor') self.biases_actor['b_{0}'.format(0)] = tf.Variable(tf.random_normal([n_hidden_1],mean=mean,stddev=stddev),name='actor') for i in range(num_hidden_layers): if i &lt; num_hidden_layers-1: num_input = n_hidden_1 n_hidden_1 = hidd_layer[i+1] self.weights_actor['h_{0}'.format(i+1)] = tf.Variable(tf.random_normal([num_input, n_hidden_1],mean=mean,stddev=stddev),name='actor') self.biases_actor['b_{0}'.format(i+1)] = tf.Variable(tf.random_normal([n_hidden_1],mean=mean,stddev=stddev),name='actor') else: self.weights_actor['h_{0}'.format(&quot;out&quot;)] = tf.Variable(tf.random_normal([n_hidden_1, num_output],mean=mean,stddev=stddev),name='actor') self.biases_actor['b_{0}'.format(&quot;out&quot;)] = tf.Variable(tf.random_normal([num_output],mean=mean,stddev=stddev),name='actor') def weights_init_critic(self,hidd_layer,mean,stddev): num_input = self.s_size # num_output = self.a_size num_output = 1 n_hidden_1 = hidd_layer[0] num_hidden_layers = len(hidd_layer) self.weights_critic['h_{0}'.format(0)] = tf.Variable(tf.random_normal([num_input, n_hidden_1],mean=mean,stddev=stddev),name='critic') self.biases_critic['b_{0}'.format(0)] = tf.Variable(tf.random_normal([n_hidden_1],mean=mean,stddev=stddev),name='critic') for i in range(num_hidden_layers): if i &lt; num_hidden_layers-1: num_input = n_hidden_1 n_hidden_1 = hidd_layer[i+1] self.weights_critic['h_{0}'.format(i+1)] = tf.Variable(tf.random_normal([num_input, n_hidden_1],mean=mean,stddev=stddev),name='critic') self.biases_critic['b_{0}'.format(i+1)] = tf.Variable(tf.random_normal([n_hidden_1],mean=mean,stddev=stddev),name='critic') else: self.weights_critic['h_{0}'.format(&quot;out&quot;)] = tf.Variable(tf.random_normal([n_hidden_1, num_output],mean=mean,stddev=stddev),name='critic') self.biases_critic['b_{0}'.format(&quot;out&quot;)] = tf.Variable(tf.random_normal([num_output],mean=mean,stddev=stddev),name='critic') def create_actor_brain(self,hidd_layer,hidd_act_fn,output_act_fn,mean,stddev): self.is_actor_brain_present = True self.weights_init_actor(hidd_layer,mean,stddev) num_hidden_layers = len(hidd_layer) if hidd_act_fn == &quot;relu&quot;: layer_h = tf.nn.relu(tf.add(tf.matmul(self.state_in, self.weights_actor['h_0']), self.biases_actor['b_0'])) for i in range(num_hidden_layers): if i &lt; num_hidden_layers-1: layer_h = tf.nn.relu(tf.add(tf.matmul(layer_h, self.weights_actor['h_{0}'.format(i+1)]), self.biases_actor['b_{0}'.format(i+1)])) else: if output_act_fn == &quot;linear&quot;: layer_out = tf.add(tf.matmul(layer_h, self.weights_actor['h_{0}'.format(&quot;out&quot;)]), self.biases_actor['b_{0}'.format(&quot;out&quot;)]) elif output_act_fn == &quot;sopftmax&quot;: layer_out = tf.nn.softmax(tf.add(tf.matmul(layer_h, self.weights_actor['h_{0}'.format(&quot;out&quot;)]), self.biases_actor['b_{0}'.format(&quot;out&quot;)])) self.output_actor = layer_out self.actor_tvar_num = (num_hidden_layers+1)*2 def create_critic_brain(self,hidd_layer,hidd_act_fn,output_act_fn,mean,stddev): if self.is_actor_brain_present: self.weights_init_critic(hidd_layer,mean,stddev) num_hidden_layers = len(hidd_layer) if hidd_act_fn == &quot;relu&quot;: layer_h = tf.nn.relu(tf.add(tf.matmul(self.state_in, self.weights_critic['h_0']), self.biases_critic['b_0'])) for i in range(num_hidden_layers): if i &lt; num_hidden_layers-1: layer_h = tf.nn.relu(tf.add(tf.matmul(layer_h, self.weights_critic['h_{0}'.format(i+1)]), self.biases_critic['b_{0}'.format(i+1)])) else: if output_act_fn == &quot;linear&quot;: layer_out = tf.add(tf.matmul(layer_h, self.weights_critic['h_{0}'.format(&quot;out&quot;)]), self.biases_critic['b_{0}'.format(&quot;out&quot;)]) elif output_act_fn == &quot;sopftmax&quot;: layer_out = tf.nn.softmax(tf.add(tf.matmul(layer_h, self.weights_critic['h_{0}'.format(&quot;out&quot;)]), self.biases_critic['b_{0}'.format(&quot;out&quot;)])) self.output_critic = layer_out self.critic_tvar_num = (num_hidden_layers+1)*2 self.is_critic_brain_present = True else: print(&quot;please create actor brain first&quot;) def critic(self): return self.output_critic def get_delta(self,sess): self.delta = self.time_step_info['r'] + (not self.time_step_info['d'])*self.gamma*sess.run(self.critic(),feed_dict={self.state_in:self.time_step_info['s1']}) - sess.run(self.critic(),feed_dict={self.state_in:self.time_step_info['s']}) def normal_dist_prob(self): cov_inv = 1/float(self.reduction) y = tf.reduce_sum(tf.square((self.time_step_info['a']-self.output_actor))*tf.ones([1,self.a_size])*cov_inv,1) Z = (2*np.pi)**(0.5*4)*(self.reduction**self.a_size)**(0.5) pdf = tf.exp(-0.5*y)/Z return pdf def create_actor_loss(self): self.actor_loss = -tf.log(self.normal_dist_prob()) def create_critic_loss(self): self.critic_loss = -self.critic() def sample_action(self,sess,state): state = np.array([state]) mean= sess.run([self.output_actor],feed_dict={self.state_in:state}) sample = np.random.multivariate_normal(mean[0][0],np.eye(self.a_size)*self.reduction) return sample def calculate_actor_loss_gradient(self): self.actor_gradients = tf.gradients(self.actor_loss,self.tvars[:self.actor_tvar_num]) self.actor_gradients = self.I*self.delta*self.actor_gradients def calculate_critic_loss_gradient(self): self.critic_gradients = tf.gradients(self.critic_loss,self.tvars[self.actor_tvar_num:]) self.critic_gradients = self.delta*self.critic_gradients def update_actor_weights(self): self.update_actor_batch = self.optimizer.apply_gradients(zip(self.actor_gradients,self.tvars[:self.actor_tvar_num])) return self.update_actor_batch def update_critic_weights(self): self.update_critic_batch = self.optimizer.apply_gradients(zip(self.critic_gradients,self.tvars[self.actor_tvar_num:])) return self.update_critic_batch def update_I(self): self.I = self.I*self.gamma def reset_I(self): self.I = 1 def update_time_step_info(self,s,a,r,s1,d): self.time_step_info['s'] = s self.time_step_info['a'] = a self.time_step_info['r'] = r self.time_step_info['s1'] = s1 self.time_step_info['d'] = d def shuffle_memories(self): np.random.shuffle(self.episode_history) def create_graph_connections(self): if self.is_actor_brain_present and self.is_critic_brain_present: # self.create_pi_dist() self.normal_dist_prob() self.create_actor_loss() self.create_critic_loss() self.tvars = tf.trainable_variables() self.calculate_actor_loss_gradient() self.calculate_critic_loss_gradient() self.update_actor_weights() self.update_critic_weights() self.saver = tf.train.Saver() else: print(&quot;initialize actor and critic brains first&quot;) self.init = tf.global_variables_initializer() def bound_actions(self,sess,state,lower_limit,uper_limit): action = self.sample_action(sess,state) bounded_action = np.copy(action) for i,act in enumerate(action): if act &lt; lower_limit[i]: bounded_action[i] = lower_limit[i] elif act &gt; uper_limit[i]: bounded_action[i]= uper_limit[i] return bounded_action </code></pre> <h1>Agent instantiation</h1> <pre><code>tf.reset_default_graph() agent= agent_episodic_continuous_action(1e-3,0.7,0.02,s_size=24,a_size=4,dist_type=&quot;normal&quot;) agent.create_actor_brain([12,5],&quot;relu&quot;,&quot;linear&quot;,0.0,0.14) agent.create_critic_brain([12,5],&quot;relu&quot;,&quot;linear&quot;,0.0,0.14) agent.create_graph_connections() path = &quot;/home/diego/Desktop/Study/RL/projects/models/biped/model.ckt&quot; env = gym.make('BipedalWalker-v2') uper_action_limit = env.action_space.high lower_action_limit = env.action_space.low total_returns=[] </code></pre> <h1>Training loops</h1> <pre><code>with tf.Session() as sess: try: sess.run(agent.init) #agent_2.load_model(path,sess) for i in range(30): agent.reset_I() s = env.reset() d = False print(i) while not d: a=agent.bound_actions(sess,s,lower_action_limit,uper_action_limit) s1,r,d,_ = env.step(a) env.render() agent.update_time_step_info([s],[a],[r],[s1],d) agent.get_delta(sess) sess.run(agent.update_critic_weights(),feed_dict={agent.state_in:agent.time_step_info['s']}) sess.run(agent.update_actor_weights(),feed_dict={agent.state_in:agent.time_step_info['s']}) agent.update_I() s = s1 total_returns.append(r) except Exception as e: print(e) env.close() plt.plot(r) plt.show </code></pre> <h1>Edit: Update</h1> <p>I managed to locate what are the lines that slow down (and eventually break) the code, these are:</p> <pre><code> sess.run(agent.update_critic_weights(),feed_dict={agent.state_in:agent.time_step_info['s']}) sess.run(agent.update_actor_weights(),feed_dict={agent.state_in:agent.time_step_info['s']}) </code></pre> <p>Why is this happening? first the speed is good, then it starts getting slower and slower.</p> <h1>Edit #2:</h1> <p>There is a memory leak in the lines:</p> <pre><code> sess.run(agent.update_critic_weights(),feed_dict={agent.state_in:agent.time_step_info['s']}) sess.run(agent.update_actor_weights(),feed_dict={agent.state_in:agent.time_step_info['s']}) </code></pre> <p>The TensorFlow graph is getting bigger with each iteration. I still can't find the <a href="http://www.riptutorial.com/tensorflow/example/13426/use-graph-finalize---to-catch-nodes-being-added-to-the-graph" rel="nofollow noreferrer">leak</a>. Why is this happening?</p>
[]
[ { "body": "<p>By adding the line:</p>\n\n<pre><code>sess.graph.finalize()\n</code></pre>\n\n<p>I was able to track down the source of the problem.</p>\n\n<p>The code was slow because the Tensorflow graph was getting bigger after each iteration. The cause of this was the 2 lines mentioned on the Edit #2. \nThese...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T19:14:47.380", "Id": "203201", "Score": "3", "Tags": [ "python", "algorithm", "machine-learning", "tensorflow" ], "Title": "BipedalWalker-v2 one-step actor-critic agent trains slow" }
203201
<p>I'm about to post quite a bit of code. Hopefully, someone is willing to put some time into reviewing it all. I know linked lists have been done a lot on here, but I wanted to improve the basic C++ skills I learned in college by learning more about templates, inheritance, move semantics, smart pointers, SFINAE, etc. My code consists of an abstract base class, <code>LinkedList</code>, with two derived classes, <code>SLinkedList</code> and <code>DLinkedList</code>. Also included is a custom iterator hierarchy.</p> <p>My goal in posting this is to become a better C++ programmer. Therefore, any feedback regarding a better way of doing something is welcome!</p> <p><strong>NOTE</strong>: This code does not compile using G++ due to a compiler bug. See this <a href="https://stackoverflow.com/questions/50338164/issues-with-class-friendship-and-inheritance" title="Stack Overflow question">Stack Overflow question</a> for more information. It compiles just fine with Clang++ 6.0.1. <br><br> <strong>LinkedList.hpp</strong>:</p> <pre><code>#ifndef LINKEDLIST_HPP #define LINKEDLIST_HPP #include &lt;algorithm&gt; #include &lt;memory&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include "NodeIterator.hpp" namespace bork_lib { class SingleLinkage {}; class DoubleLinkage {}; template&lt;typename, typename = void&gt; struct supports_less_than : std::false_type { }; template&lt;typename T&gt; struct supports_less_than&lt;T, std::void_t&lt;decltype(std::declval&lt;T&amp;&gt;() &lt;= std::declval&lt;T&amp;&gt;())&gt;&gt; : std::true_type { }; template&lt;typename LinkageType, typename ValueType&gt; class LinkedList { protected: template&lt;typename ShadowedLinkageType, typename = void&gt; struct ListNode; template&lt;typename ShadowedLinkageType&gt; struct ListNode&lt;ShadowedLinkageType, std::enable_if_t&lt;std::is_same&lt;ShadowedLinkageType, SingleLinkage&gt;::value&gt;&gt; { ValueType data; std::unique_ptr&lt;ListNode&gt; next = std::unique_ptr&lt;ListNode&gt;(nullptr); template&lt;typename... Args, typename = std::enable_if_t&lt;std::is_constructible_v&lt;ValueType, Args&amp;&amp;...&gt;&gt;&gt; explicit ListNode(Args&amp;&amp;... args) : data{std::forward&lt;Args&gt;(args)...} { } explicit ListNode(const ValueType&amp; data) : data{data} { } explicit ListNode(ValueType&amp;&amp; data) : data{std::forward&lt;ValueType&gt;(data)} { } }; template&lt;typename ShadowedLinkageType&gt; struct ListNode&lt;ShadowedLinkageType, std::enable_if_t&lt;!std::is_same&lt;ShadowedLinkageType, SingleLinkage&gt;::value&gt;&gt; { ValueType data; std::unique_ptr&lt;ListNode&gt; next = std::unique_ptr&lt;ListNode&gt;(nullptr); ListNode* prev = nullptr; template&lt;typename... Args, typename = std::enable_if_t&lt;std::is_constructible_v&lt;ValueType, Args&amp;&amp;...&gt;&gt;&gt; explicit ListNode(Args&amp;&amp;... args) : data{std::forward&lt;Args&gt;(args)...} { } explicit ListNode(const ValueType&amp; data) : data{data} { } explicit ListNode(ValueType&amp;&amp; data) : data{std::forward&lt;ValueType&gt;(data)} { } }; public: using value_type = ValueType; using reference = ValueType&amp;; using const_reference = const ValueType&amp;; using pointer = ValueType*; using const_pointer = const ValueType*; using size_type = std::size_t; using difference_type = std::ptrdiff_t; using iterator = std::conditional_t&lt;std::is_same&lt;LinkageType, SingleLinkage&gt;::value, ForwardListIterator&lt;ValueType&gt;, ListIterator&lt;ValueType&gt;&gt;; using const_iterator = std::conditional_t&lt;std::is_same&lt;LinkageType, SingleLinkage&gt;::value, ConstForwardListIterator&lt;ValueType&gt;, ConstListIterator&lt;ValueType&gt;&gt;; using node_iterator = NodeIterator&lt;ListNode&lt;LinkageType&gt;, value_type&gt;; protected: using node_type = ListNode&lt;LinkageType&gt;; std::unique_ptr&lt;node_type&gt; head = std::unique_ptr&lt;node_type&gt;(nullptr); node_type* tail = nullptr; bool srtd = true; // the list is guaranteed to be sorted if true size_type sz = 0; // size of the list void list_swap(LinkedList&lt;LinkageType, ValueType&gt;&amp; other); void swap(value_type&amp; a, value_type&amp; b); template&lt;typename... Args&gt; void emplace_empty(Args&amp;&amp;... args); node_type* find_sorted_position(const value_type&amp; val); virtual node_type* insert_node_before(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) = 0; virtual node_type* insert_node_after(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) = 0; void mergesort(std::unique_ptr&lt;node_type&gt;&amp; left_owner, size_type size); virtual void merge(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) = 0; virtual node_type* delete_node(node_type* node, bool is_reverse) = 0; node_type* search_front(const value_type&amp; val) const noexcept; template&lt;typename InputIterator&gt; void construct_from_iterator_range(InputIterator begin, InputIterator end); public: // construction, assignment, and destruction LinkedList() = default; LinkedList(const LinkedList&lt;LinkageType, value_type&gt;&amp; other) = delete; LinkedList(LinkedList&lt;LinkageType, value_type&gt;&amp;&amp; other) noexcept : head{std::move(other.head)}, tail{other.tail}, sz{other.sz}, srtd{other.srtd} { } LinkedList&lt;LinkageType, ValueType&gt;&amp; operator=(const LinkedList&lt;LinkageType, ValueType&gt;&amp; other); LinkedList&lt;LinkageType, ValueType&gt;&amp; operator=(LinkedList&lt;LinkageType, ValueType&gt;&amp;&amp; other) noexcept; virtual ~LinkedList() noexcept { clear(); }; bool empty() const noexcept { return !head; } size_type size() const noexcept { return sz; } bool sorted() const noexcept { return srtd; } reference front() const noexcept { return head-&gt;data; } reference back() const noexcept { return tail-&gt;data; } node_iterator&amp; insert_before(node_iterator&amp; iter, const value_type&amp; val) { return emplace_before(iter, val); } node_iterator&amp; insert_before(node_iterator&amp; iter, value_type&amp;&amp; val) { return emplace_before(iter, std::forward&lt;value_type&gt;(val)); } node_iterator&amp; insert_after(node_iterator&amp; iter, const value_type&amp; val) { return emplace_after(iter, val); } node_iterator&amp; insert_after(node_iterator&amp; iter, value_type&amp;&amp; val) { return emplace_after(iter, std::forward&lt;value_type&gt;(val)); } void insert_sorted(const value_type&amp; val) { return emplace_sorted(val); } void insert_sorted(value_type&amp;&amp; val) { return emplace_sorted(std::forward&lt;value_type&gt;(val)); } template&lt;typename... Args&gt; node_iterator&amp; emplace_before(node_iterator&amp; iter, Args&amp;&amp;... args); template&lt;typename... Args&gt; node_iterator&amp; emplace_after(node_iterator&amp; iter, Args&amp;&amp;... args); template&lt;typename... Args&gt; void emplace_sorted(Args&amp;&amp;... args); void push_front(const value_type&amp; val) { emplace_front(val); } void push_front(value_type&amp;&amp; val) { emplace_front(std::forward&lt;value_type&gt;(val)); } void push_back(const value_type&amp; val) { emplace_back(val); } void push_back(value_type&amp;&amp; val) { emplace_back(std::forward&lt;value_type&gt;(val)); } template&lt;typename... Args&gt; void emplace_front(Args&amp;&amp;... args) { iterator iter{head.get()}; emplace_before(iter, std::forward&lt;Args&gt;(args)...); } template&lt;typename... Args&gt; void emplace_back(Args&amp;&amp;... args) { iterator iter{tail}; emplace_after(iter, std::forward&lt;Args&gt;(args)...); } void pop_front() { delete_node(head.get(), false); } void pop_back() { delete_node(tail, false); } iterator find(const value_type&amp; val) const noexcept; size_type count(const value_type&amp; val) const noexcept; node_iterator&amp; erase(node_iterator&amp; iter); void clear() noexcept; template&lt;typename T = value_type, std::enable_if_t&lt;supports_less_than&lt;T&gt;::value, int&gt; = 0&gt; void sort(); template&lt;typename T = value_type, std::enable_if_t&lt;!supports_less_than&lt;T&gt;::value, int&gt; = 0&gt; void sort() { throw std::logic_error("List cannot be sorted, as value_type does not support comparison."); } // iterator functions iterator begin() noexcept { return iterator{head.get()}; } const_iterator begin() const noexcept { return const_iterator{head.get()}; } iterator end() noexcept { return iterator{nullptr}; } const_iterator end() const noexcept { return const_iterator{nullptr}; }; const_iterator cbegin() const noexcept { return const_iterator{head.get()}; } const_iterator cend() const noexcept { return const_iterator{nullptr}; } friend class ListIterator&lt;value_type&gt;; friend class ConstListIterator&lt;value_type&gt;; friend class ReverseListIterator&lt;value_type&gt;; friend class ConstReverseListIterator&lt;value_type&gt;; friend class ForwardListIterator&lt;value_type&gt;; friend class ConstForwardListIterator&lt;value_type&gt;; friend class NodeIterator&lt;ListNode&lt;LinkageType&gt;, value_type&gt;; }; template&lt;typename LinkageType, typename ValueType&gt; LinkedList&lt;LinkageType, ValueType&gt;&amp; LinkedList&lt;LinkageType, ValueType&gt;::operator=(const LinkedList&lt;LinkageType, ValueType&gt;&amp; other) { clear(); for (const auto&amp; x : other) { push_back(x); } srtd = other.srtd; return *this; } template&lt;typename LinkageType, typename ValueType&gt; LinkedList&lt;LinkageType, ValueType&gt;&amp; LinkedList&lt;LinkageType, ValueType&gt;::operator=(LinkedList&lt;LinkageType, ValueType&gt;&amp;&amp; other) noexcept { list_swap(other); return *this; } template&lt;typename LinkageType, typename ValueType&gt; void LinkedList&lt;LinkageType, ValueType&gt;::list_swap(LinkedList&lt;LinkageType, ValueType&gt;&amp; other) { auto temp_unique = std::move(head); head = std::move(other.head); other.head = std::move(temp_unique); using std::swap; swap(tail, other.tail); swap(sz, other.sz); swap(srtd, other.srtd); } template&lt;typename LinkageType, typename ValueType&gt; void LinkedList&lt;LinkageType, ValueType&gt;::swap(value_type&amp; a, value_type&amp; b) { value_type tmp{std::move(a)}; a = std::move(b); b = std::move(tmp); } /* Helper function to insert an element in-place into an empty list. */ template&lt;typename LinkageType, typename ValueType&gt; template&lt;typename... Args&gt; void LinkedList&lt;LinkageType, ValueType&gt;::emplace_empty(Args&amp;&amp;... args) { head = std::make_unique&lt;node_type&gt;(std::forward&lt;Args&gt;(args)...); tail = head.get(); ++sz; } /* Helper function to find the correct position for inserting an element into a sorted list. */ template&lt;typename LinkageType, typename ValueType&gt; typename LinkedList&lt;LinkageType, ValueType&gt;::node_type* LinkedList&lt;LinkageType, ValueType&gt;::find_sorted_position(const value_type &amp;val) { auto node = head.get(); while (node) { if (node-&gt;data &gt;= val) { return node; } node = node-&gt;next.get(); } return nullptr; } /* Helper function used to recursively sort and merge sublists. */ template&lt;typename LinkageType, typename ValueType&gt; void LinkedList&lt;LinkageType, ValueType&gt;::mergesort(std::unique_ptr&lt;node_type&gt;&amp; left_owner, size_type size) { if (size &lt;= 1) // already sorted return; size_type split = size / 2; mergesort(left_owner, split); // sort left half auto node = left_owner.get(); for (size_type i = 0; i &lt; split - 1; ++i) { // split the list node = node-&gt;next.get(); } auto&amp; right_owner = node-&gt;next; mergesort(right_owner, size - split); // sort right half merge(left_owner, right_owner.get(), size - split); // merge the two halves } /* Helper function that returns a pointer to the first node with the value specified. */ template&lt;typename LinkageType, typename ValueType&gt; typename LinkedList&lt;LinkageType, ValueType&gt;::node_type* LinkedList&lt;LinkageType, ValueType&gt;::search_front(const value_type&amp; val) const noexcept { auto node = head.get(); while (node) { if (node-&gt;data == val) { return node; } node = node-&gt;next.get(); } return nullptr; } template&lt;typename LinkageType, typename ValueType&gt; template&lt;typename InputIterator&gt; void LinkedList&lt;LinkageType, ValueType&gt;::construct_from_iterator_range(InputIterator begin, InputIterator end) { while (begin != end) { push_back(*begin++); } srtd = std::is_sorted(begin, end); } /* Public function that inserts a value in-place before a node in the list. */ template&lt;typename LinkageType, typename ValueType&gt; template&lt;typename... Args&gt; typename LinkedList&lt;LinkageType, ValueType&gt;::node_iterator&amp; LinkedList&lt;LinkageType, ValueType&gt;::emplace_before(node_iterator&amp; iter, Args&amp;&amp;... args) { if (empty()) { emplace_empty(std::forward&lt;Args&gt;(args)...); iter.node = head.get(); } else { auto new_node = std::make_unique&lt;node_type&gt;(std::forward&lt;Args&gt;(args)...); iter.node = insert_node_before(iter.node, new_node, iter.is_reverse()); } return iter; } /* Public function that inserts a value in-place after a node in the list. */ template&lt;typename LinkageType, typename ValueType&gt; template&lt;typename... Args&gt; typename LinkedList&lt;LinkageType, ValueType&gt;::node_iterator&amp; LinkedList&lt;LinkageType, ValueType&gt;::emplace_after(node_iterator&amp; iter, Args&amp;&amp;... args) { if (empty()) { emplace_empty(std::forward&lt;Args&gt;(args)...); iter.node = head.get(); } else { auto new_node = std::make_unique&lt;node_type&gt;(std::forward&lt;Args&gt;(args)...); iter.node = insert_node_after(iter.node, new_node, iter.is_reverse()); } return iter; } /* Public function that inserts a value in-place into its correct position in a sorted list. */ template&lt;typename LinkageType, typename ValueType&gt; template&lt;typename... Args&gt; void LinkedList&lt;LinkageType, ValueType&gt;::emplace_sorted(Args&amp;&amp;... args) { if (empty()) { emplace_empty(std::forward&lt;Args&gt;(args)...); return; } sort(); // won't sort if already sorted auto new_node = std::make_unique&lt;node_type&gt;(std::forward&lt;Args&gt;(args)...); auto position = find_sorted_position(new_node-&gt;data); position ? insert_node_before(position, new_node, false) : insert_node_after(tail, new_node, false); srtd = true; } /* Public function that attempts to find a value within the list. */ template&lt;typename LinkageType, typename ValueType&gt; typename LinkedList&lt;LinkageType, ValueType&gt;::iterator LinkedList&lt;LinkageType, ValueType&gt;::find(const value_type &amp;val) const noexcept { auto node = head.get(); while (node) { if (node-&gt;data == val) { break; } node = node-&gt;next.get(); } return iterator{node}; }; /* Public function that counts the occurrences of a value in the list. */ template&lt;typename LinkageType, typename ValueType&gt; typename LinkedList&lt;LinkageType, ValueType&gt;::size_type LinkedList&lt;LinkageType, ValueType&gt;::count(const value_type&amp; val) const noexcept { auto node = head.get(); size_type count = 0; while (node) { if (node-&gt;data == val) { ++count; } node = node-&gt;next.get(); } return count; } /* Public sort function. Calls the mergesort helper function. */ template&lt;typename LinkageType, typename ValueType&gt; template&lt;typename T, std::enable_if_t&lt;supports_less_than&lt;T&gt;::value, int&gt;&gt; void LinkedList&lt;LinkageType, ValueType&gt;::sort() { if (srtd) { return; } mergesort(head, sz); // sort the entire list srtd = true; } /* Public function that erases a node pointed to by an iterator. */ template&lt;typename LinkageType, typename ValueType&gt; typename LinkedList&lt;LinkageType, ValueType&gt;::node_iterator&amp; LinkedList&lt;LinkageType, ValueType&gt;::erase(node_iterator&amp; iter) { if (empty()) { throw std::out_of_range{"Can't delete from empty list."}; } iter.node = delete_node(iter.node, iter.is_reverse()); return iter; } /* Public function that clears a list. */ template&lt;typename LinkageType, typename ValueType&gt; void LinkedList&lt;LinkageType, ValueType&gt;::clear() noexcept { while (head) { head = std::move(head-&gt;next); } tail = nullptr; sz = 0; } } // end namespace #endif </code></pre> <p><br> <strong>SLinkedList.hpp</strong>:</p> <pre><code>#ifndef SLINKEDLIST_HPP #define SLINKEDLIST_HPP #include &lt;algorithm&gt; #include &lt;initializer_list&gt; #include &lt;memory&gt; #include &lt;stdexcept&gt; #include &lt;utility&gt; #include "LinkedList.hpp" #include "NodeIterator.hpp" namespace bork_lib { template&lt;typename ValueType&gt; class SLinkedList : public LinkedList&lt;SingleLinkage, ValueType&gt; { public: using value_type = typename LinkedList&lt;SingleLinkage, ValueType&gt;::value_type; using reference = typename LinkedList&lt;SingleLinkage, value_type&gt;::reference; using const_reference = typename LinkedList&lt;SingleLinkage, value_type&gt;::const_reference; using pointer = typename LinkedList&lt;SingleLinkage, value_type&gt;::pointer; using const_pointer = typename LinkedList&lt;SingleLinkage, value_type&gt;::const_pointer; using size_type = typename LinkedList&lt;SingleLinkage, value_type&gt;::size_type; using difference_type = typename LinkedList&lt;SingleLinkage, value_type&gt;::difference_type; using iterator = typename LinkedList&lt;SingleLinkage, value_type&gt;::iterator; using const_iterator = typename LinkedList&lt;SingleLinkage, value_type&gt;::const_iterator; using LinkedList&lt;SingleLinkage, value_type&gt;::push_back; private: using node_iterator = typename LinkedList&lt;SingleLinkage, value_type&gt;::node_iterator; using node_type = typename LinkedList&lt;SingleLinkage, value_type&gt;::node_type; using LinkedList&lt;SingleLinkage, value_type&gt;::head; using LinkedList&lt;SingleLinkage, value_type&gt;::tail; using LinkedList&lt;SingleLinkage, value_type&gt;::srtd; using LinkedList&lt;SingleLinkage, value_type&gt;::sz; using LinkedList&lt;SingleLinkage, value_type&gt;::LinkedList; using LinkedList&lt;SingleLinkage, value_type&gt;::construct_from_iterator_range; using LinkedList&lt;SingleLinkage, value_type&gt;::swap; node_type* insert_node_before(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) override; node_type* insert_node_after(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) override; void merge(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) override; template&lt;typename T = value_type, std::enable_if_t&lt;supports_less_than&lt;T&gt;::value, int&gt; = 0&gt; void merge_helper(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size); template&lt;typename T = value_type, std::enable_if_t&lt;!supports_less_than&lt;T&gt;::value, int&gt; = 0&gt; void merge_helper(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) { } node_type* delete_node(node_type* node, bool is_reverse) override; public: SLinkedList() : LinkedList&lt;SingleLinkage, ValueType&gt;{} { } SLinkedList(const SLinkedList&lt;value_type&gt;&amp; other) : SLinkedList{other.cbegin(), other.cend()} { srtd = other.srtd; } SLinkedList(SLinkedList&lt;value_type&gt;&amp;&amp; other) noexcept : LinkedList&lt;SingleLinkage, value_type&gt;{std::forward&lt;SLinkedList&lt;value_type&gt;&gt;(other)} { } template&lt;typename InputIterator&gt; SLinkedList(InputIterator begin, InputIterator end) { construct_from_iterator_range(begin, end); } SLinkedList(std::initializer_list&lt;value_type&gt; li) : SLinkedList&lt;value_type&gt;{li.begin(), li.end()} { } ~SLinkedList() = default; SLinkedList&amp; operator=(const SLinkedList&lt;value_type&gt;&amp; other) = default; SLinkedList&amp; operator=(SLinkedList&lt;value_type&gt;&amp;&amp; other) noexcept = default; friend class ForwardListIterator&lt;value_type&gt;; friend class ConstForwardListIterator&lt;value_type&gt;; friend class NodeIterator&lt;node_type, value_type&gt;; }; /* Helper function that takes a new node and inserts it before an existing node in the list. */ template&lt;typename ValueType&gt; typename SLinkedList&lt;ValueType&gt;::node_type* SLinkedList&lt;ValueType&gt;::insert_node_before(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) { if (!node) { throw std::invalid_argument{"Non-empty list pointer can't be null."}; } using std::swap; swap(node-&gt;data, new_node-&gt;data); return insert_node_after(node, new_node, is_reverse); } /* Helper function that takes a new node and inserts it before an existing node in the list. */ template&lt;typename ValueType&gt; typename SLinkedList&lt;ValueType&gt;::node_type* SLinkedList&lt;ValueType&gt;::insert_node_after(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) { if (!node) { throw std::invalid_argument{"Non-empty list pointer can't be null."}; } ++sz; srtd = false; new_node-&gt;next = std::move(node-&gt;next); if (node == tail) { tail = new_node.get(); } node-&gt;next = std::move(new_node); return node-&gt;next.get(); } /* Mergesort function in the base class calls this function, which calls whichever merge_helper function was compiled using SFINAE. */ template&lt;typename ValueType&gt; void SLinkedList&lt;ValueType&gt;::merge(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) { merge_helper(left_owner, right_raw, right_size); } /* Helper function that merges two sublists (mostly) in-place. Does make a few moves because of the lack of prev pointers in a singly-linked list. */ template&lt;typename ValueType&gt; template&lt;typename T, std::enable_if_t&lt;supports_less_than&lt;T&gt;::value, int&gt;&gt; void SLinkedList&lt;ValueType&gt;::merge_helper(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) { auto left_raw = left_owner.get(); using std::swap; /* Explanation of the following while loop conditions: 1. right_size keeps track of the number of unmerged nodes in the right sublist. When right_size == 0, the last node to be merged was in the right sublist and the sublists have been merged. 2. If left_raw == right_raw, then all the nodes in the left sublist have been merged. Since the right sublist is already sorted, the merging is now complete. */ while(right_size &amp;&amp; left_raw != right_raw) { /* When the next node to be merged is from the left sublist, simply move the left_raw pointer to the next node. */ if (left_raw-&gt;data &lt;= right_raw-&gt;data) { left_raw = left_raw-&gt;next.get(); } /* When the next node to be merged is from the right sublist, put that node in front of the node pointed to by left_raw. */ else if (right_size == 1) { // only one element in right partition left; requires sequence of swaps --right_size; while (left_raw != right_raw) { swap(left_raw-&gt;data, right_raw-&gt;data); left_raw = left_raw-&gt;next.get(); } } else { --right_size; swap(left_raw-&gt;data, right_raw-&gt;data); // put the value from the right sublist in the correct place swap(right_raw-&gt;data, right_raw-&gt;next-&gt;data); // move the next value in the right sublist ahead auto current = std::move(right_raw-&gt;next); // put the value that was moved back where it should be right_raw-&gt;next = std::move(current-&gt;next); current-&gt;next = std::move(left_raw-&gt;next); left_raw-&gt;next = std::move(current); left_raw = left_raw-&gt;next.get(); } } } /* Helper function that removes a node from the list. */ template&lt;typename ValueType&gt; typename SLinkedList&lt;ValueType&gt;::node_type* SLinkedList&lt;ValueType&gt;::delete_node(node_type* node, bool is_reverse) { if (!node) { throw std::invalid_argument{"Can't delete null pointer."}; } node_type* return_node = nullptr; if (sz == 1) { head.release(); tail = nullptr; } else if (node == head.get()) { head = std::move(node-&gt;next); return_node = head.get(); } else if (node == tail) { // linear time operation auto search = head.get(); while (search-&gt;next.get() != tail) { search = search-&gt;next.get(); } tail = search; search-&gt;next.release(); } else { node-&gt;data = std::move(node-&gt;next-&gt;data); node-&gt;next = std::move(node-&gt;next-&gt;next); return_node = node; } --sz; return return_node; } } // end namespace #endif </code></pre> <p><br> <strong>DLinkedList.hpp</strong>:</p> <pre><code>#ifndef DLINKEDLIST_HPP #define DLINKEDLIST_HPP #include &lt;algorithm&gt; #include &lt;initializer_list&gt; #include &lt;memory&gt; #include &lt;stdexcept&gt; #include &lt;utility&gt; #include "LinkedList.hpp" #include "NodeIterator.hpp" namespace bork_lib { template&lt;typename ValueType&gt; class DLinkedList : public LinkedList&lt;DoubleLinkage, ValueType&gt; { public: using value_type = typename LinkedList&lt;DoubleLinkage, ValueType&gt;::value_type; using reference = typename LinkedList&lt;DoubleLinkage, value_type&gt;::reference; using const_reference = typename LinkedList&lt;DoubleLinkage, value_type&gt;::const_reference; using pointer = typename LinkedList&lt;DoubleLinkage, value_type&gt;::pointer; using const_pointer = typename LinkedList&lt;DoubleLinkage, value_type&gt;::const_pointer; using size_type = typename LinkedList&lt;DoubleLinkage, value_type&gt;::size_type; using difference_type = typename LinkedList&lt;DoubleLinkage, value_type&gt;::difference_type; using iterator = typename LinkedList&lt;DoubleLinkage, value_type&gt;::iterator; using const_iterator = typename LinkedList&lt;DoubleLinkage, value_type&gt;::const_iterator; using reverse_iterator = ReverseListIterator&lt;value_type&gt;; using const_reverse_iterator = ConstReverseListIterator&lt;value_type&gt;; using LinkedList&lt;DoubleLinkage, value_type&gt;::push_back; private: using node_iterator = typename LinkedList&lt;DoubleLinkage, value_type&gt;::node_iterator; using node_type = typename LinkedList&lt;DoubleLinkage, value_type&gt;::node_type; using LinkedList&lt;DoubleLinkage, value_type&gt;::head; using LinkedList&lt;DoubleLinkage, value_type&gt;::tail; using LinkedList&lt;DoubleLinkage, value_type&gt;::srtd; using LinkedList&lt;DoubleLinkage, value_type&gt;::sz; using LinkedList&lt;DoubleLinkage, value_type&gt;::LinkedList; using LinkedList&lt;DoubleLinkage, value_type&gt;::construct_from_iterator_range; node_type* insert_node_before(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) override; node_type* insert_node_after(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) override; void merge(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) override; template&lt;typename T = value_type, std::enable_if_t&lt;supports_less_than&lt;T&gt;::value, int&gt; = 0&gt; void merge_helper(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size); template&lt;typename T = value_type, std::enable_if_t&lt;!supports_less_than&lt;T&gt;::value, int&gt; = 0&gt; void merge_helper(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) { } node_type* delete_node(node_type* node, bool is_reverse) override; public: DLinkedList() : LinkedList&lt;DoubleLinkage, value_type&gt;{} { } DLinkedList(const DLinkedList&lt;value_type&gt;&amp; other) : DLinkedList{other.cbegin(), other.cend()} { srtd = other.srtd; } DLinkedList(DLinkedList&lt;value_type&gt;&amp;&amp; other) noexcept : LinkedList&lt;DoubleLinkage, value_type&gt;{std::forward&lt;DLinkedList&lt;value_type&gt;&gt;(other)} { } template&lt;typename InputIterator&gt; DLinkedList(InputIterator begin, InputIterator end) { construct_from_iterator_range(begin, end); } DLinkedList(std::initializer_list&lt;value_type&gt; li) : DLinkedList&lt;value_type&gt;{li.begin(), li.end()} { } ~DLinkedList() = default; DLinkedList&amp; operator=(const DLinkedList&lt;value_type&gt;&amp; other) = default; DLinkedList&amp; operator=(DLinkedList&lt;value_type&gt;&amp;&amp; other) noexcept = default; reverse_iterator rbegin() noexcept { return reverse_iterator{tail}; } const_reverse_iterator rbegin() const noexcept { return const_reverse_iterator{tail}; }; reverse_iterator rend() noexcept { return reverse_iterator{nullptr}; } const_reverse_iterator rend() const noexcept { return const_reverse_iterator{nullptr}; }; const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator{tail}; } const_reverse_iterator crend() const noexcept { return const_reverse_iterator{nullptr}; } friend class ListIterator&lt;value_type&gt;; friend class ConstListIterator&lt;value_type&gt;; friend class ReverseListIterator&lt;value_type&gt;; friend class ConstReverseListIterator&lt;value_type&gt;; friend class NodeIterator&lt;node_type, value_type&gt;; }; /* Helper function that takes a new node and inserts it before an existing node in the list. */ template&lt;typename ValueType&gt; typename DLinkedList&lt;ValueType&gt;::node_type* DLinkedList&lt;ValueType&gt;::insert_node_before(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) { if (!node) { throw std::invalid_argument{"Non-empty list pointer can't be null."}; } if (is_reverse) { return insert_node_after(node, new_node, false)-&gt;prev; } ++sz; srtd = false; new_node-&gt;prev = node-&gt;prev; node-&gt;prev = new_node.get(); if (node == head.get()) { // insert at front of list new_node-&gt;next = std::move(head); head = std::move(new_node); } else { new_node-&gt;next = std::move(new_node-&gt;prev-&gt;next); new_node-&gt;prev-&gt;next = std::move(new_node); } return node; } /* Helper function that takes a new node and inserts it after an existing node in the list. */ template&lt;typename ValueType&gt; typename DLinkedList&lt;ValueType&gt;::node_type* DLinkedList&lt;ValueType&gt;::insert_node_after(node_type *node, std::unique_ptr&lt;node_type&gt; &amp;new_node, bool is_reverse) { if (!node) { throw std::invalid_argument{"Non-empty list pointer can't be null."}; } if (is_reverse) { return insert_node_before(node, new_node, false)-&gt;prev; } ++sz; srtd = false; new_node-&gt;next = std::move(node-&gt;next); new_node-&gt;prev = node; if (node == tail) { // insert at back of list tail = new_node.get(); } else { new_node-&gt;next-&gt;prev = new_node.get(); } node-&gt;next = std::move(new_node); return node-&gt;next.get(); } /* Mergesort function in the base class calls this function, which calls whichever merge_helper function was compiled using SFINAE. */ template&lt;typename ValueType&gt; void DLinkedList&lt;ValueType&gt;::merge(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) { merge_helper(left_owner, right_raw, right_size); } /* Helper function that merges two sublists completely in-place. */ template&lt;typename ValueType&gt; template&lt;typename T, std::enable_if_t&lt;supports_less_than&lt;T&gt;::value, int&gt;&gt; void DLinkedList&lt;ValueType&gt;::merge_helper(std::unique_ptr&lt;node_type&gt;&amp; left_owner, node_type* right_raw, size_type right_size) { auto left_raw = left_owner.get(); /* Explanation of the following while loop conditions: 1. right_size keeps track of the number of unmerged nodes in the right sublist. When right_size == 0, the last node to be merged was in the right sublist and the sublists have been merged. 2. If left_raw == right_raw, then all the nodes in the left sublist have been merged. Since the right sublist is already sorted, the merging is now complete. */ while(right_size &amp;&amp; left_raw != right_raw) { /* When the next node to be merged is from the left sublist, simply move the left_raw pointer to the next node. */ if (left_raw-&gt;data &lt;= right_raw-&gt;data) { left_raw = left_raw-&gt;next.get(); } /* When the next node to be merged is from the right sublist, put that node in front of the node pointed to by left_raw. */ else { --right_size; auto current = std::move(right_raw-&gt;prev-&gt;next); // the node currently being moved right_raw = right_raw-&gt;next.get(); // point to the next node to be merged // remove the node if (current-&gt;next) { current-&gt;next-&gt;prev = current-&gt;prev; } else { // last node in list tail = current-&gt;prev; } current-&gt;prev-&gt;next = std::move(current-&gt;next); // insert the node current-&gt;prev = left_raw-&gt;prev; if (left_raw == left_owner.get()) { // move in front of first node in left sublist current-&gt;next = std::move(left_owner); left_owner = std::move(current); left_raw-&gt;prev = left_owner.get(); } else if (left_raw-&gt;prev) { current-&gt;next = std::move(left_raw-&gt;prev-&gt;next); left_raw-&gt;prev-&gt;next = std::move(current); left_raw-&gt;prev = left_raw-&gt;prev-&gt;next.get(); } } } } /* Helper function that removes a node from the list. */ template&lt;typename ValueType&gt; typename DLinkedList&lt;ValueType&gt;::node_type* DLinkedList&lt;ValueType&gt;::delete_node(node_type* node, bool is_reverse) { if (!node) { throw std::invalid_argument{"Can't delete null pointer."}; } auto return_node = is_reverse ? node-&gt;prev : node-&gt;next.get(); if (sz == 1) { head.release(); tail = nullptr; } else if (node == head.get()) { head = std::move(node-&gt;next); } else if (node == tail) { tail = node-&gt;prev; node-&gt;prev-&gt;next.release(); } else { node-&gt;next-&gt;prev = node-&gt;prev; node-&gt;prev-&gt;next = std::move(node-&gt;next); } --sz; return return_node; } } // end namespace #endif </code></pre> <p><br> <strong>NodeIterator.hpp</strong>:</p> <pre><code>#ifndef NODEITERATOR_HPP #define NODEITERATOR_HPP #include &lt;stdexcept&gt; #include &lt;utility&gt; namespace bork_lib { class SingleLinkage; class DoubleLinkage; template&lt;typename L, typename V&gt; class LinkedList; template&lt;typename V&gt; class DLinkedList; template&lt;typename V&gt; class SLinkedList; template&lt;typename NodeType, typename ValueType&gt; class NodeIterator { protected: NodeType* node; virtual bool is_reverse() = 0; public: using value_type = ValueType; using reference = value_type&amp;; using const_reference = const value_type&amp;; using pointer = value_type*; using const_pointer = const value_type*; using size_type = std::size_t; using difference_type = std::ptrdiff_t; explicit NodeIterator(NodeType* node = nullptr) : node{node} {} NodeIterator(const NodeIterator&lt;NodeType, value_type&gt;&amp; other) : node(other.node) {} NodeIterator&lt;NodeType, value_type&gt;&amp; operator=(const NodeIterator&lt;NodeType, value_type&gt;&amp; other) { node = other.node; return *this; } virtual NodeIterator&lt;NodeType, value_type&gt;&amp; operator++() = 0; virtual NodeIterator&lt;NodeType, value_type&gt;&amp; operator--() = 0; reference operator*() { return node-&gt;data; } pointer operator-&gt;() { return &amp;(node-&gt;data); } bool operator==(const NodeIterator&lt;NodeType, value_type&gt;&amp; other) const noexcept { return node == other.node; } bool operator!=(const NodeIterator&lt;NodeType, value_type&gt;&amp; other) const noexcept { return !operator==(other); } virtual ~NodeIterator() = default; template&lt;typename L, typename V&gt; friend class LinkedList; friend class DLinkedList&lt;value_type&gt;; friend class SLinkedList&lt;value_type&gt;; }; template&lt;typename NodeType, typename ValueType&gt; class ConstNodeIterator { protected: NodeType* node; virtual bool is_reverse() = 0; public: using value_type = ValueType; using reference = value_type&amp;; using const_reference = const value_type&amp;; using pointer = value_type*; using const_pointer = const value_type*; using size_type = std::size_t; using difference_type = std::ptrdiff_t; explicit ConstNodeIterator(NodeType* node = nullptr) : node{node} {} ConstNodeIterator(const ConstNodeIterator&lt;NodeType, value_type&gt;&amp; other) : node(other.node) {} ConstNodeIterator&lt;NodeType, value_type&gt;&amp; operator=(const ConstNodeIterator&lt;NodeType, value_type&gt;&amp; other) { node = other.node; return *this; } virtual ConstNodeIterator&lt;NodeType, value_type&gt;&amp; operator++() = 0; virtual ConstNodeIterator&lt;NodeType, value_type&gt;&amp; operator--() = 0; const_reference operator*() { return node-&gt;data; } const_pointer operator-&gt;() { return &amp;(node-&gt;data); } bool operator==(const ConstNodeIterator&lt;NodeType, value_type&gt;&amp; other) const noexcept { return node == other.node; } bool operator!=(const ConstNodeIterator&lt;NodeType, value_type&gt;&amp; other) const noexcept { return !operator==(other); } virtual ~ConstNodeIterator() = default; template&lt;typename L, typename V&gt; friend class LinkedList; template&lt;typename V&gt; friend class DLinkedList; template&lt;typename V&gt; friend class SLinkedList; }; template&lt;typename ValueType&gt; class ListIterator : public NodeIterator&lt;typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type, ValueType&gt; { bool is_reverse() override { return false; } using node_type = typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type; using NodeIterator&lt;node_type, ValueType&gt;::NodeIterator; using NodeIterator&lt;node_type, ValueType&gt;::node; public: using iterator_category = std::bidirectional_iterator_tag; using value_type = typename NodeIterator&lt;node_type, ValueType&gt;::value_type; using reference = typename NodeIterator&lt;node_type, value_type&gt;::reference; using const_reference = typename NodeIterator&lt;node_type, value_type&gt;::const_reference; using pointer = typename NodeIterator&lt;node_type, value_type&gt;::pointer; using const_pointer = typename NodeIterator&lt;node_type, value_type&gt;::const_pointer; using size_type = typename NodeIterator&lt;node_type, value_type&gt;::size_type; using difference_type = typename NodeIterator&lt;node_type, value_type&gt;::difference_type; ListIterator&lt;value_type&gt;&amp; operator=(const NodeIterator&lt;node_type, value_type&gt;&amp; other) { return *this = dynamic_cast&lt;ListIterator&lt;value_type&gt;&amp;&gt;(NodeIterator&lt;node_type, value_type&gt;::operator=(other)); } ListIterator&lt;value_type&gt;&amp; operator++() override { node = node-&gt;next.get(); return *this; } ListIterator&lt;value_type&gt;&amp; operator--() override { node = node-&gt;prev; return *this; } ListIterator&lt;value_type&gt; operator++(int) { ListIterator&lt;value_type&gt; temp{*this}; operator++(); return temp; } ListIterator&lt;value_type&gt; operator--(int) { ListIterator&lt;value_type&gt; temp{*this}; operator--(); return temp; } friend class DLinkedList&lt;value_type&gt;; }; template&lt;typename ValueType&gt; class ConstListIterator : public ConstNodeIterator&lt;typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type, ValueType&gt; { bool is_reverse() override { return false; } using node_type = typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type; using ConstNodeIterator&lt;node_type, ValueType&gt;::ConstNodeIterator; using ConstNodeIterator&lt;node_type, ValueType&gt;::node; public: using iterator_category = std::bidirectional_iterator_tag; using value_type = typename ConstNodeIterator&lt;node_type, ValueType&gt;::value_type; using reference = typename ConstNodeIterator&lt;node_type, value_type&gt;::reference; using const_reference = typename ConstNodeIterator&lt;node_type, value_type&gt;::const_reference; using pointer = typename ConstNodeIterator&lt;node_type, value_type&gt;::pointer; using const_pointer = typename ConstNodeIterator&lt;node_type, value_type&gt;::const_pointer; using size_type = typename ConstNodeIterator&lt;node_type, value_type&gt;::size_type; using difference_type = typename ConstNodeIterator&lt;node_type, value_type&gt;::difference_type; ConstListIterator&lt;value_type&gt;&amp; operator=(const ConstNodeIterator&lt;node_type, value_type&gt;&amp; other) { return *this = dynamic_cast&lt;ConstListIterator&lt;value_type&gt;&amp;&gt;(ConstNodeIterator&lt;node_type, value_type&gt;::operator=(other)); } ConstListIterator&lt;value_type&gt;&amp; operator++() override { node = node-&gt;next.get(); return *this; } ConstListIterator&lt;value_type&gt;&amp; operator--() override { node = node-&gt;prev; return *this; } ConstListIterator&lt;value_type&gt; operator++(int) { ConstListIterator&lt;value_type&gt; temp{*this}; operator++(); return temp; } ConstListIterator&lt;value_type&gt; operator--(int) { ConstListIterator&lt;value_type&gt; temp{*this}; operator--(); return temp; } friend class DLinkedList&lt;value_type&gt;; }; template&lt;typename ValueType&gt; class ReverseListIterator : public NodeIterator&lt;typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type, ValueType&gt; { bool is_reverse() override { return true; } using node_type = typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type; using NodeIterator&lt;node_type, ValueType&gt;::NodeIterator; using NodeIterator&lt;node_type, ValueType&gt;::node; public: using iterator_category = std::bidirectional_iterator_tag; using value_type = typename NodeIterator&lt;node_type, ValueType&gt;::value_type; using reference = typename NodeIterator&lt;node_type, value_type&gt;::reference; using const_reference = typename NodeIterator&lt;node_type, value_type&gt;::const_reference; using pointer = typename NodeIterator&lt;node_type, value_type&gt;::pointer; using const_pointer = typename NodeIterator&lt;node_type, value_type&gt;::const_pointer; using size_type = typename NodeIterator&lt;node_type, value_type&gt;::size_type; using difference_type = typename NodeIterator&lt;node_type, value_type&gt;::difference_type; ReverseListIterator&lt;value_type&gt;&amp; operator=(const NodeIterator&lt;node_type, value_type&gt;&amp; other) { return *this = dynamic_cast&lt;ReverseListIterator&lt;value_type&gt;&amp;&gt;(NodeIterator&lt;node_type, value_type&gt;::operator=(other)); } ReverseListIterator&lt;value_type&gt;&amp; operator++() override { node = node-&gt;prev; return *this; } ReverseListIterator&lt;value_type&gt;&amp; operator--() override { node = node-&gt;next.get(); return *this; } ReverseListIterator&lt;value_type&gt; operator++(int) { ReverseListIterator&lt;value_type&gt; temp{*this}; operator++(); return temp; } ReverseListIterator&lt;value_type&gt; operator--(int) { ReverseListIterator&lt;value_type&gt; temp{*this}; operator--(); return temp; } friend class DLinkedList&lt;value_type&gt;; }; template&lt;typename ValueType&gt; class ConstReverseListIterator : public ConstNodeIterator&lt;typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type, ValueType&gt; { bool is_reverse() override { return true; } using node_type = typename LinkedList&lt;DoubleLinkage, ValueType&gt;::node_type; using ConstNodeIterator&lt;node_type, ValueType&gt;::ConstNodeIterator; using ConstNodeIterator&lt;node_type, ValueType&gt;::node; public: using iterator_category = std::bidirectional_iterator_tag; using value_type = typename ConstNodeIterator&lt;node_type, ValueType&gt;::value_type; using reference = typename ConstNodeIterator&lt;node_type, value_type&gt;::reference; using const_reference = typename ConstNodeIterator&lt;node_type, value_type&gt;::const_reference; using pointer = typename ConstNodeIterator&lt;node_type, value_type&gt;::pointer; using const_pointer = typename ConstNodeIterator&lt;node_type, value_type&gt;::const_pointer; using size_type = typename ConstNodeIterator&lt;node_type, value_type&gt;::size_type; using difference_type = typename ConstNodeIterator&lt;node_type, value_type&gt;::difference_type; ConstReverseListIterator&lt;value_type&gt;&amp; operator=(const ConstNodeIterator&lt;node_type, value_type&gt;&amp; other) { return *this = dynamic_cast&lt;ConstReverseListIterator&lt;value_type&gt;&amp;&gt;(ConstNodeIterator&lt;node_type, value_type&gt;::operator=(other)); } ConstReverseListIterator&lt;value_type&gt;&amp; operator++() override { node = node-&gt;prev; return *this; } ConstReverseListIterator&lt;value_type&gt;&amp; operator--() override { node = node-&gt;next.get(); return *this; } ConstReverseListIterator&lt;value_type&gt; operator++(int) { ConstReverseListIterator&lt;value_type&gt; temp{*this}; operator++(); return temp; } ConstReverseListIterator&lt;value_type&gt; operator--(int) { ConstReverseListIterator&lt;value_type&gt; temp{*this}; operator--(); return temp; } friend class DLinkedList&lt;value_type&gt;; }; template&lt;typename ValueType&gt; class ForwardListIterator : public NodeIterator&lt;typename LinkedList&lt;SingleLinkage, ValueType&gt;::node_type, ValueType&gt; { bool is_reverse() override { return false; } using node_type = typename LinkedList&lt;SingleLinkage, ValueType&gt;::node_type; using NodeIterator&lt;node_type, ValueType&gt;::NodeIterator; using NodeIterator&lt;node_type, ValueType&gt;::node; public: using iterator_category = std::forward_iterator_tag; using value_type = typename NodeIterator&lt;node_type, ValueType&gt;::value_type; using reference = typename NodeIterator&lt;node_type, value_type&gt;::reference; using const_reference = typename NodeIterator&lt;node_type, value_type&gt;::const_reference; using pointer = typename NodeIterator&lt;node_type, value_type&gt;::pointer; using const_pointer = typename NodeIterator&lt;node_type, value_type&gt;::const_pointer; using size_type = typename NodeIterator&lt;node_type, value_type&gt;::size_type; using difference_type = typename NodeIterator&lt;node_type, value_type&gt;::difference_type; ForwardListIterator&lt;value_type&gt;&amp; operator=(const NodeIterator&lt;node_type, value_type&gt;&amp; other) { return *this = dynamic_cast&lt;ForwardListIterator&lt;value_type&gt;&amp;&gt;(NodeIterator&lt;node_type, value_type&gt;::operator=(other)); } ForwardListIterator&lt;value_type&gt;&amp; operator++() override { node = node-&gt;next.get(); return *this; } ForwardListIterator&lt;value_type&gt;&amp; operator--() override { throw std::logic_error("Cannot decrement forward iterator."); } ForwardListIterator&lt;value_type&gt; operator++(int) { ForwardListIterator&lt;value_type&gt; temp{*this}; operator++(); return temp; } ForwardListIterator&lt;value_type&gt; operator--(int) { throw std::logic_error("Cannot decrement forward iterator."); } friend class SLinkedList&lt;value_type&gt;; }; template&lt;typename ValueType&gt; class ConstForwardListIterator : public ConstNodeIterator&lt;typename LinkedList&lt;SingleLinkage, ValueType&gt;::node_type, ValueType&gt; { bool is_reverse() override { return false; } using node_type = typename LinkedList&lt;SingleLinkage, ValueType&gt;::node_type; using ConstNodeIterator&lt;node_type, ValueType&gt;::ConstNodeIterator; using ConstNodeIterator&lt;node_type, ValueType&gt;::node; public: using iterator_category = std::forward_iterator_tag; using value_type = typename ConstNodeIterator&lt;node_type, ValueType&gt;::value_type; using reference = typename ConstNodeIterator&lt;node_type, value_type&gt;::reference; using const_reference = typename ConstNodeIterator&lt;node_type, value_type&gt;::const_reference; using pointer = typename ConstNodeIterator&lt;node_type, value_type&gt;::pointer; using const_pointer = typename ConstNodeIterator&lt;node_type, value_type&gt;::const_pointer; using size_type = typename ConstNodeIterator&lt;node_type, value_type&gt;::size_type; using difference_type = typename ConstNodeIterator&lt;node_type, value_type&gt;::difference_type; ConstForwardListIterator&lt;value_type&gt;&amp; operator=(const ConstNodeIterator&lt;node_type, value_type&gt;&amp; other) { return *this = dynamic_cast&lt;ConstForwardListIterator&lt;value_type&gt;&amp;&gt;(ConstNodeIterator&lt;node_type, value_type&gt;::operator=(other)); } ConstForwardListIterator&lt;value_type&gt;&amp; operator++() override { node = node-&gt;next.get(); return *this; } ConstForwardListIterator&lt;value_type&gt;&amp; operator--() override { throw std::logic_error("Cannot decrement forward iterator."); } ConstForwardListIterator&lt;value_type&gt; operator++(int) { ConstForwardListIterator&lt;value_type&gt; temp{*this}; operator++(); return temp; } ConstForwardListIterator&lt;value_type&gt; operator--(int) { throw std::logic_error("Cannot decrement forward iterator."); } friend class SLinkedList&lt;value_type&gt;; }; } // end namespace #endif </code></pre> <p><br> For testing I used the Catch2 framework. However, attempting to post the code for my tests causes me to exceed the 65535 character limit. You can access my test code using the following links:</p> <ul> <li><a href="https://github.com/mborkland/borkland.net/blob/master/data-structures/test/tests-SLinkedList.cpp" rel="nofollow noreferrer">SLinkedList test code</a></li> <li><a href="https://github.com/mborkland/borkland.net/blob/master/data-structures/test/tests-DLinkedList.cpp" rel="nofollow noreferrer">DLinkedList test code</a></li> </ul>
[]
[ { "body": "<p>This is indeed fairly large and will take a while to review.</p>\n\n<p>Just glancing through it, two big things jumped at me immediatelly, so I'll jot them down right away, and update this answer as I make myu way further down the code.</p>\n\n<h2>Don't use tag types for bounded lists.</h2>\n\n<p>...
{ "AcceptedAnswerId": "203449", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T19:24:10.977", "Id": "203202", "Score": "4", "Tags": [ "c++", "linked-list", "reinventing-the-wheel", "c++14", "inheritance" ], "Title": "C++ linked list inheritance hierarchy" }
203202
<p>Jst to clarify, teams and groups are the same thing in this case.</p> <p><code>$data</code> comes from a database and is an array of objects. Each object contains information about a user including what team/group they are in. I want to convert this to an array of groups which includes an array of users belonging to that group inside. Users can be in multiple groups too so in the original list of users, a lot of entries will have repeating group id's.</p> <p>The code I have works but it's very blocky and I feel like it could be shortened a lot.</p> <pre><code>$groups = []; foreach($data as $user) { $userGroupId = $user['GroupId']; $exists = false; foreach($groups as &amp;$group) { $groupId = $group['GroupId']; if ($groupId == $userGroupId) { $users = &amp;$group['users']; $currentUser = array( 'UserId'=&gt;$user['UserId'], 'UserName'=&gt;$user['UserName'], 'Surname'=&gt;$user['Surname'] ); array_push($users, $currentUser); $exists = true; break; } } if (!$exists) { $addGroup = array( 'GroupId'=&gt;$user['GroupId'], 'GroupName'=&gt;$user['GroupName'], 'users'=&gt;[array( 'UserId'=&gt;$user['UserId'], 'UserName'=&gt;$user['UserName'], 'Surname'=&gt;$user['Surname'] )] ); array_push($groups, $addGroup); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T20:06:41.130", "Id": "203205", "Score": "1", "Tags": [ "php", "array" ], "Title": "Converting an array of users into an array of teams with an array property for listing the users" }
203205
<p>I have the following Java code used to retry a certain actions/methods</p> <pre><code>package helpers; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public final class Retry { public static &lt;V&gt; V execute(Callable&lt;V&gt; action, Duration retryInterval, int retryCount) throws AggregateException { List&lt;Throwable&gt; exceptions = new ArrayList&lt;&gt;(); for (int retry = 0; retry &lt; retryCount; ++retry) { try { if (retry &gt; 0) Thread.sleep(retryInterval.toMillis()); return action.call(); } catch (Throwable t) { exceptions.add(t); } } throw new AggregateException(exceptions); } public static &lt;V&gt; Future executeAsync(Callable&lt;V&gt; action, Duration retryInterval, int retryCount) throws AggregateException { FutureTask&lt;V&gt; task = new FutureTask&lt;&gt;(action); ExecutorService executor = Executors.newSingleThreadExecutor(); return executor.submit(task); } } </code></pre> <p>Q1. Can this code be improved?</p> <p>Q2. Am I using the <code>Future</code> interface correctly in the asynchronous version of execute? </p> <p>I am also attempting to test this class using </p> <pre><code>package helpers; import org.junit.Before; import org.junit.Test; import java.text.MessageFormat; import java.time.Duration; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; public class RetryTest { private Integer counter = 0; private Callable&lt;Integer&gt; calculator = null; @Before public void init() { calculator = () -&gt; { for (int i = 0; i &lt; 3; ++i) { counter++; System.out.println(MessageFormat.format( "Counter = {0}", Integer.toString(counter))); } if (counter &lt; 9) throw new Exception(); return counter; }; } @Test public void execute() throws AggregateException { Integer result = Retry.execute(calculator, Duration.ofMillis(50), 9); assertEquals(9, (int)result); } @Test public void executeAsync() throws AggregateException, ExecutionException, InterruptedException { Future future = Retry.executeAsync(calculator, Duration.ofMillis(500), 9); while (!future.isDone()) { System.out.println("Churn"); } assertEquals(9, (int)future.get()); } } </code></pre> <p>Q3. Is this the correct way to test that my async version is actually async?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T05:59:47.693", "Id": "391663", "Score": "1", "body": "There must be a flaw in your test, as your async variant does not perform any retry action thus failing with an exception and no result. Try to reset the counter before each test...
[ { "body": "<p>Some thoughts about your implementation:</p>\n\n<p>As stated by @mtj, <code>executeAsync()</code> doesn’t actually retry.</p>\n\n<p>Don’t ever catch <code>Throwable</code>. You do want to catch <code>Exception</code>, but <code>Throwable</code> is things like <code>OutOfMemoryError</code>. You’re ...
{ "AcceptedAnswerId": "203236", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T20:49:35.113", "Id": "203206", "Score": "2", "Tags": [ "java", "unit-testing", "error-handling", "asynchronous" ], "Title": "Retry Class in Java" }
203206
<p>This is a random frequency audio generator made with the Web Audio API by Mozilla. The end-goal is an audio frequency trainer: the website plays an audio frequency and the user tries to guess which frequency it is. The frequencies will be limited to those found on 31 band graphical equalisers, and I'll include multiple difficulties.</p> <p>This is my first step: the generator for the 'easy' difficulty (4 frequencies).</p> <pre><code>// create web audio api context var audioCtx = new AudioContext(); // create oscillator (tone) and gain (volume) node var tone = audioCtx.createOscillator(); var volume = audioCtx.createGain(); // create array of frequency values var frequencies = ["100", "400", "1600", "6300"]; // pick a random frequency var frequency = frequencies[Math.floor(Math.random() * frequencies.length)]; // set oscillator type (sine, square, sawtooth or triangle) tone.type = 'sine'; // set oscillator frequency in Hz tone.frequency.value = frequency; // set gain volume (above 1 will clip) volume.gain.value = 0.5; // set tone destination to go through volume tone.connect(volume); // set volume destination to output volume.connect(audioCtx.destination); // start oscillator x seconds after timestamp tone.start(1); // stop oscillator x seconds after timestamp tone.stop(4); </code></pre> <p>Don't mind the excessive commentation, I've only just started using JavaScript and don't trust myself to remember what every line of code does after a few days.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T02:06:03.927", "Id": "391655", "Score": "1", "body": "I mean, this is all look spretty straight forward. You should probably be using ES6 features, like `const`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2...
[ { "body": "<h2>Reusable code</h2>\n\n<p>You code is not very flexible, and the frequencies somewhat arbitrary and spanning a large 6 octaves. </p>\n\n<p>You can encapsulate the code in a function that creates an object you use to play the random tone as needed, allowing you to add features as you need.</p>\n\n<...
{ "AcceptedAnswerId": "203223", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T21:38:02.573", "Id": "203209", "Score": "5", "Tags": [ "javascript", "random", "html5", "audio" ], "Title": "Random tone generator using Web Audio API" }
203209
<p>I'm trying to build an Excel workbook to automate and aid in the creation of a weekly work schedule.</p> <p>My current workbook is functional, but it's slow - especially on one task where I have a list of people with an annual schedule that I'm searching two sheets at the same time.</p> <p>I think there's a better and more efficient way than the one I'm using.</p> <pre><code>Option Explicit 'Global variable that will be in another module where i store all general config Public Const PlanningAgentEmptyRange As String = "C12:G58,F74:G78" 'Range agent present Public Const PosteWeekDayRange As String = "B12:B72" 'Range agent present Public Const PosteWeekEndRange As String = "B73:B78" 'Range agent present Sub DraftFromCycle() 'If range is empty (to prevent the lost of approved schedule) If Application.WorksheetFunction.CountA(Range(PlanningAgentEmptyRange)) = 0 Then 'list of day/col Weekday in weekly schedule Dim aWeekDay(1 To 5) As String aWeekDay(1) = "C": aWeekDay(2) = "D": aWeekDay(3) = "E": aWeekDay(4) = "F": aWeekDay(5) = "G" 'List of day/col weekEnd in weekly schedule Dim aWeekEnd(1 To 2) As String aWeekEnd(1) = "F": aWeekEnd(2) = "G" Dim DayDate As Range Dim cel As Range Dim Col As Variant Dim DayRangeCycle As Range Dim DayCycleCol As String Dim DayCycleRow As Integer Dim AgentName Dim p, s, poste, x As variant Dim Cycle_lastrow As Integer Dim Cycle_lastcol As String Cycle_lastrow = LastRow(Feuil55) Cycle_lastcol = LastCol(Feuil55) 'Loop col/Day of weekday For Each Col In aWeekDay Set DayDate = Range(Col &amp; "11") Set s = Worksheets("Cycle").Range("A5:OA5").Find(What:=DayDate, Lookat:=xlWhole) If Not s Is Nothing Then DayCycleCol = ColLetter(s.Column) For Each poste In Worksheets("Cycle").Range(DayCycleCol &amp; "6:" &amp; DayCycleCol &amp; Cycle_lastrow) Select Case poste Case Is = "AM" Set x = ActiveSheet.Range(PosteWeekDayRange).Find(What:="Après-midi", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekDayRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "N" Set x = ActiveSheet.Range(PosteWeekDayRange).Find(What:="Nuit", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekDayRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "R N" Set x = ActiveSheet.Range(PosteWeekDayRange).Find(What:="Récup Nuit", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekDayRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "R Av" Set x = ActiveSheet.Range(PosteWeekDayRange).Find(What:="R.H. Avant Garde", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekDayRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "R Ap" Set x = ActiveSheet.Range(PosteWeekDayRange).Find(What:="R.H. Après Garde", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekDayRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "RTP" Set x = ActiveSheet.Range(PosteWeekDayRange).Find(What:="R.T.P.", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekDayRange).FindNext(x) Loop While Not x Is Nothing End If Case Else End Select Next poste End If Next Col 'Loop col du Week End For Each Col In aWeekEnd Set DayDate = Range(Col &amp; "73") Set s = Worksheets("Cycle").Range("A5:OA5").Find(What:=DayDate, Lookat:=xlWhole) If Not s Is Nothing Then DayCycleCol = ColLetter(s.Column) For Each poste In Worksheets("Cycle").Range(DayCycleCol &amp; "6:" &amp; DayCycleCol &amp; Cycle_lastrow) Select Case poste Case Is = "AM" Set x = ActiveSheet.Range(PosteWeekEndRange).Find(What:="Après-midi", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekEndRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "N" Set x = ActiveSheet.Range(PosteWeekEndRange).Find(What:="Nuit", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekEndRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "6h25" Set x = ActiveSheet.Range(PosteWeekEndRange).Find(What:="6h25 - 13h25", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekEndRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "7h30" Set x = ActiveSheet.Range(PosteWeekEndRange).Find(What:="7h30 - 14h30", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekEndRange).FindNext(x) Loop While Not x Is Nothing End If Case Is = "7h45" Set x = ActiveSheet.Range(PosteWeekEndRange).Find(What:="7h45 - 14h45", Lookat:=xlWhole) If Not x Is Nothing Then Do If ActiveSheet.Range(Col &amp; x.Row) = "" Then ActiveSheet.Range(Col &amp; x.Row) = Worksheets("Cycle").Range("A" &amp; poste.Row).Value ActiveSheet.Range(Col &amp; x.Row).Font.Italic = True End If Set x = ActiveSheet.Range(PosteWeekEndRange).FindNext(x) Loop While Not x Is Nothing End If Case Else End Select Next poste End If Next Col End If End Sub </code></pre> <p>Here's a screen of what the sheets look like. The module takes the data from the annual schedule and autofilled the weekly schedule if it's empty:</p> <p><strong>Annual Schedule (Worksheets("Cycle"))</strong></p> <p><a href="https://i.stack.imgur.com/gEqiM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gEqiM.png" alt="Annual Schedule (Worksheets(&quot;Cycle&quot;)"></a></p> <p><strong>Weekly Schedule (Worksheets("1"))</strong></p> <p><a href="https://i.stack.imgur.com/PPje2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PPje2.png" alt="Weekly Schedule (Worksheets(&quot;1&quot;)"></a></p>
[]
[ { "body": "<h2>General Observations</h2>\n\n<hr>\n\n<p><strong>Indentation</strong></p>\n\n<p>The first thing that I did when I loaded your code up in the VBE was to run an indenter on it. Without consistent indentation of logical blocks of code (<code>If</code> statements, <code>For Each</code> bodies, etc.),...
{ "AcceptedAnswerId": "203214", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-05T21:44:48.957", "Id": "203210", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Automating the creation of a weekly schedule" }
203210
<p>I'm interested in some feedback for a custom <code>TaskScheduler</code> implementation I wrote today for use on a game server - I wanted to be able to have a single-threaded scheduler for tasks since the game is relatively lightweight and its logic doesn't need to be multi-threaded. However, I wanted to handle networking/IO concurrently to avoid blocking the main thread running game logic, and still wanted the ability to easily schedule tasks onto it, jumping back and forth between executors (e.g. game server receives a request, does some logic, then requires something from a database, makes a call on some other thread pool, then executes a callback on the original thread again). Anyway, that's probably too much about why I wanted to do this; Here's how I attempted it:</p> <pre><code>public class CustomTaskScheduler : TaskScheduler { private readonly int maxThreads; private readonly ConcurrentQueue&lt;Task&gt; tasks; private readonly bool unbounded; private int threadsRunning; private CustomTaskScheduler(int concurrencyLevel, bool unboundedThreads) { maxThreads = concurrencyLevel; tasks = new ConcurrentQueue&lt;Task&gt;(); threadsRunning = 0; unbounded = unboundedThreads; } protected override IEnumerable&lt;Task&gt; GetScheduledTasks() { return tasks; } protected override void QueueTask(Task task) { tasks.Enqueue(task); if (unbounded || Interlocked.Increment(ref threadsRunning) &lt;= maxThreads) { ThreadPool.UnsafeQueueUserWorkItem(_ =&gt; { try { while (tasks.TryDequeue(out Task toRun)) { TryExecuteTask(toRun); } } catch (Exception ex) { Console.WriteLine(ex); } finally { Interlocked.Decrement(ref threadsRunning); } }, null); } else { Interlocked.Decrement(ref threadsRunning); } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; } public static CustomTaskScheduler MakeSingleThreaded() =&gt; new CustomTaskScheduler(1, false); public static CustomTaskScheduler MakeMultiThreaded(int threads) =&gt; new CustomTaskScheduler(threads, false); public static CustomTaskScheduler MakeUnbounded() =&gt; new CustomTaskScheduler(0, true); } </code></pre> <p>It isn't that complicated, but there are a few things I was wondering about - It is based off of the sample code <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskscheduler?view=netframework-4.7.2" rel="nofollow noreferrer">here</a>, but elects to use a <code>ConcurrentQueue</code> instead of locking on a <code>LinkedList</code>. From what I can see, this causes no issues. Then, I did an interlocked increment on the number of threads running to make sure it was not exceeding the limit, decrementing it immediately if another thread could not be run. This, too, I <em>think</em> is safe and correct, but it still makes me uncomfortable, and I was wondering if there was a more elegant solution to this. I found the <code>Interlocked.CompareExchange</code> function, but what i'm more looking for is being able to compare if something is less than something else.</p> <p>Finally, I have tried doing some research on <code>TryExecuteTaskInline</code>, and it seems that this allows you to run a task directly from the thread creating the task, which seems like what I don't want. For now I've set it to always return false, but i'm not sure if this is what i'm supposed to do, or if i'm misunderstanding what it is actually doing.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T14:58:05.857", "Id": "391945", "Score": "1", "body": "Nope, this is incorrect. It is possible for the running thread to complete all tasks, then have a new one be queued, fail to start a thread, then have the running thread complete...
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T00:36:10.783", "Id": "203213", "Score": "5", "Tags": [ "c#", "multithreading", ".net", "asynchronous", "concurrency" ], "Title": "Custom TaskScheduler: Limited concurrency level" }
203213
<p>For a project I'm working on I have a set of number sets, and I need all unique permutations of them. I want to return only one copy of each unique number set, and I'm struggling to figure out how without some really funky design patterns. Maybe I had a moment of genius, but I doubt it, it really seems like there's a better way. To clarify the problem, my very initial effort yielded this unacceptable output (i.e. redundant, deep-equal slices):</p> <pre><code>[22 4] [4 22] [21 5] [5 21] [20 6] [6 20] [19 7] [7 19] [18 8] [8 18] [18 4 4] [4 18 4] [4 4 18] [4 4 18] [4 18 4] [18 4 4] [17 9] [9 17] [17 4 5] [4 17 5] [5 4 17] [4 5 17] [5 17 4] [17 5 4] [16 10] [10 16] [16 4 6] [4 16 6] [6 4 16] [4 6 16] [6 16 4] [16 6 4] [16 5 5] [5 16 5] [5 5 16] [5 5 16] [5 16 5] [16 5 5] [15 11] [11 15] [15 4 7] [4 15 7] [7 4 15] [4 7 15] [7 15 4] [15 7 4] [15 5 6] [5 15 6] [6 5 15] [5 6 15] [6 15 5] [15 6 5] [14 12] [12 14] [14 4 8] [4 14 8] [8 4 14] [4 8 14] [8 14 4] [14 8 4] [14 5 7] [5 14 7] [7 5 14] [5 7 14] [7 14 5] [14 7 5] [14 6 6] [6 14 6] [6 6 14] [6 6 14] [6 14 6] [14 6 6] [13 13] [13 13] [13 4 9] [4 13 9] [9 4 13] [4 9 13] [9 13 4] [13 9 4] [13 5 8] [5 13 8] [8 5 13] [5 8 13] [8 13 5] [13 8 5] [13 6 7] [6 13 7] [7 6 13] [6 7 13] [7 13 6] [13 7 6] [12 4 10] [4 12 10] [10 4 12] [4 10 12] [10 12 4] [12 10 4] [12 5 9] [5 12 9] [9 5 12] [5 9 12] [9 12 5] [12 9 5] [12 6 8] [6 12 8] [8 6 12] [6 8 12] [8 12 6] [12 8 6] [12 7 7] [7 12 7] [7 7 12] [7 7 12] [7 12 7] [12 7 7] [11 4 11] [4 11 11] [11 4 11] [4 11 11] [11 11 4] [11 11 4] [11 5 10] [5 11 10] [10 5 11] [5 10 11] [10 11 5] [11 10 5] [11 6 9] [6 11 9] [9 6 11] [6 9 11] [9 11 6] [11 9 6] [11 7 8] [7 11 8] [8 7 11] [7 8 11] [8 11 7] [11 8 7] </code></pre> <p>My goal, which I accomplished was to make it look like:</p> <pre><code>[22 4] [4 22] [21 5] [5 21] [20 6] [6 20] [19 7] [7 19] [18 8] [8 18] [4 4 18] [4 18 4] [18 4 4] [17 9] [9 17] [17 4 5] [4 17 5] [5 4 17] [4 5 17] [5 17 4] [17 5 4] [16 10] [10 16] [16 4 6] [4 16 6] [6 4 16] [4 6 16] [6 16 4] [16 6 4] [5 5 16] [5 16 5] [16 5 5] [15 11] [11 15] [15 4 7] [4 15 7] [7 4 15] [4 7 15] [7 15 4] [15 7 4] [15 5 6] [5 15 6] [6 5 15] [5 6 15] [6 15 5] [15 6 5] [14 12] [12 14] [14 4 8] [4 14 8] [8 4 14] [4 8 14] [8 14 4] [14 8 4] [14 5 7] [5 14 7] [7 5 14] [5 7 14] [7 14 5] [14 7 5] [6 6 14] [6 14 6] [14 6 6] [13 13] [13 4 9] [4 13 9] [9 4 13] [4 9 13] [9 13 4] [13 9 4] [13 5 8] [5 13 8] [8 5 13] [5 8 13] [8 13 5] [13 8 5] [13 6 7] [6 13 7] [7 6 13] [6 7 13] [7 13 6] [13 7 6] [12 4 10] [4 12 10] [10 4 12] [4 10 12] [10 12 4] [12 10 4] [12 5 9] [5 12 9] [9 5 12] [5 9 12] [9 12 5] [12 9 5] [12 6 8] [6 12 8] [8 6 12] [6 8 12] [8 12 6] [12 8 6] [7 7 12] [7 12 7] [12 7 7] [11 4 11] [4 11 11] [11 11 4] [11 5 10] [5 11 10] [10 5 11] [5 10 11] [10 11 5] [11 10 5] [11 6 9] [6 11 9] [9 6 11] [6 9 11] [9 11 6] [11 9 6] [11 7 8] [7 11 8] [8 7 11] [7 8 11] [8 11 7] [11 8 7] </code></pre> <p>But I'm pretty confident that there must be a better way than what I did. There is also a possibility I'm solving this in the wrong place. The <code>permutations</code> function is a shameless copy+paste+amend, and maybe I could be doing something there to avoid the messy output. At the very least, I have to be using way too much control flow here: </p> <pre><code>func main() { (...) sets := [][]int{ []int{22, 4}, []int{21, 5}, []int{20, 6}, []int{19, 7}, []int{18, 8}, []int{18, 4, 4}, []int{17, 9}, []int{17, 4, 5}, []int{16, 10}, []int{16, 4, 6}, []int{16, 5, 5}, []int{15, 11}, []int{15, 4, 7}, []int{15, 5, 6}, []int{14, 12}, []int{14, 4, 8}, []int{14, 5, 7}, []int{14, 6, 6}, []int{13, 13}, []int{13, 4, 9}, []int{13, 5, 8}, []int{13, 6, 7}, []int{12, 4, 10}, []int{12, 5, 9}, []int{12, 6, 8}, []int{12, 7, 7}, []int{11, 4, 11}, []int{11, 5, 10}, []int{11, 6, 9}, []int{11, 7, 8}, } for _, set := range sets { nextIntSlice := permutations(set) clean := false for clean == false { nextIntSlice, clean = myBadWannaBeRecursiveFilter(nextIntSlice) } for _, iSlice := range nextIntSlice { cleanSlice = append(cleanSlice, iSlice) } } (...) } func myBadWannaBeRecursiveFilter(dirtySliceOfSlices [][]int) ([][]int, bool) { stillDirty := false var stillDirtySlice [][]int for i, sliceA := range dirtySliceOfSlices { counter := 0 for _, sliceB := range dirtySliceOfSlices { dup := testSliceIntEq(sliceA, sliceB) if dup { counter++ } if counter &gt; 1 { stillDirty = true p1 := dirtySliceOfSlices[:i] p2 := dirtySliceOfSlices[i+1:] if len(p1) &gt; 0 { for _, s := range p1 { stillDirtySlice = append(stillDirtySlice, s) } } if len(p2) &gt; 0 { for _, s := range p2 { stillDirtySlice = append(stillDirtySlice, s) } } // ORIGINALLY TRIED: // dirtySliceOfSlices = append(dirtySliceOfSlices[:i], dirtySliceOfSlices[i+1:]) // ^^^^^^^^^^^ THIS GENERATES THE COMPILE TIME ERR: // cannot use dirtySliceOfSlices[i + 1:] (type [][]int) as type []int in append // Which makes sense, but I don't know how to get around when using slices of slices other than control flow within control flow. break } } if stillDirty { break } } if stillDirty { return stillDirtySlice, false } return dirtySliceOfSlices, true } func testSliceIntEq(a, b []int) bool { // If one is nil, the other must also be nil. if (a == nil) != (b == nil) { return false } if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } func permutations(arr []int) [][]int { var helper func([]int, int) res := [][]int{} helper = func(arr []int, n int) { if n == 1 { tmp := make([]int, len(arr)) copy(tmp, arr) res = append(res, tmp) } else { for i := 0; i &lt; n; i++ { helper(arr, n-1) if n%2 == 1 { tmp := arr[i] arr[i] = arr[n-1] arr[n-1] = tmp } else { tmp := arr[0] arr[0] = arr[n-1] arr[n-1] = tmp } } } } helper(arr, len(arr)) return res } </code></pre> <p>Special thanks to StackOverflow for the slice comparison func, and some random internet article for <code>permutations</code>. Bottom line, my program works, but I don't feel like I learned anything good from it. Maybe you guys can help.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T03:25:54.787", "Id": "203217", "Score": "3", "Tags": [ "array", "go" ], "Title": "Getting all unique permutations from a slice of integers slices in golang," }
203217
<p>I'm new to React.js and this code came from <a href="https://github.com/fullstackreact/30-days-of-react/blob/master/day-07/post.md" rel="nofollow noreferrer" title="30 Days of React - Day 7">30 Days of React - Day 7</a>. However the given code example wasn't working so I rewrote it myself. My biggest issue here is how to make the component work without function getTime() using both setState and return. Any other suggestions are appreciated.</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>class Clock extends React.Component { constructor(props) { super(props); this.state = {currentTime: this.getTime()}; } getTime() { const currentTime = new Date(), hours = currentTime.getHours(), minutes = currentTime.getMinutes(), seconds = currentTime.getSeconds(), ampm = hours &gt;= 12 ? 'pm' : 'am'; this.setState({currentTime: {hours, minutes, seconds, ampm}}); return {hours, minutes, seconds, ampm}; } componentDidMount() { const intervalId = setInterval(this.getTime.bind(this), 1000); this.setState({intervalId: intervalId}); } componentWillDisMount() { clearInterval(this.state.intervalId); } render() { const {hours, minutes, seconds, ampm} = this.state.currentTime; return ( &lt;div className="clock"&gt; {hours == 0 ? 12 : (hours &gt; 12) ? hours - 12 : hours}: {minutes &gt; 9 ? minutes : `0${minutes}`}: {seconds &gt; 9 ? seconds : `0${seconds}`} {ampm} &lt;/div&gt; ) } } ReactDOM.render(&lt;Clock /&gt;, document.querySelector("#app"));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"&gt;&lt;/script&gt; &lt;body&gt; &lt;div id="app"&gt;&lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>If it's assigning to the state, you don't need to assign it at the beginning.</p>\n\n<pre><code>this.setState({currentTime: {hours, minutes, seconds, ampm}}); // you don't need to return at all.\n</code></pre>\n\n<p>You can replace this with some value that indicates that it hasn't loaded yet, wh...
{ "AcceptedAnswerId": "203232", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T07:05:03.570", "Id": "203221", "Score": "3", "Tags": [ "beginner", "datetime", "react.js", "timer", "jsx" ], "Title": "React clock component" }
203221
<p>I came across the following code snippet:</p> <pre><code>static private volatile ConfigUserCredentails maintenanceUserCred = null; static private Object maintenanceUserLock = new Object(); /** * This method is slower. Recommend use the one from cache. * * @return The username/password credentials of the maintenance user. * @throws IOException */ public static ConfigUserCredentails getMaintenanceUserCredentials() throws IOException { return readCredentialsFromFile(MAINTENANCE_CREDENTIALS_PROPS, Crypt.getDefaultCrypt()); } /** * * @return The username/password credentials of the maintenance user. * @throws IOException */ public static ConfigUserCredentails getMaintenanceUserCredentialsFromCache() throws IOException { if (maintenanceUserCred != null) { return maintenanceUserCred; } synchronized(maintenanceUserLock) { if (maintenanceUserCred == null) { maintenanceUserCred = getMaintenanceUserCredentials(); } } return maintenanceUserCred; } </code></pre> <p>'getMaintenanceUserCredentials()' just reads the user credentials from file and creates new user object.</p> <p>My questions are:</p> <ol> <li>What is the purpose of 'volatile'?</li> <li>Why would one need the 'synchronized' block?</li> </ol> <p>Thanks, Rafik</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T08:25:47.773", "Id": "391680", "Score": "2", "body": "Hey, welcome to Code Review! Unfortunately your question does not match what this site is about. One of our requirements for questions is: \"**Authorship of code**: Since Code Re...
[ { "body": "<ol>\n<li><p>When a variable is <code>volatile</code>, then the code that access that variable is forced to read/write the value of variable from/to the memory. Without <code>volatile</code>, the value of variable can be (temporarily) stored to place (like register/cache) where changes are not immedi...
{ "AcceptedAnswerId": "203224", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T07:15:53.990", "Id": "203222", "Score": "0", "Tags": [ "java", "concurrency" ], "Title": "Reading a user credentials from file concurrently" }
203222
<p>Is it my queue mechanism thread safe? I just wonder if I need concurrent collections. Need I lock Enqueue method? Console displays queue count in incorrect order, Does it affect on maxQueueCount at Load method? Can I improve it in some way?</p> <pre><code>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using System.Timers; class Program { public class Document : IItem { public Guid Id { get; set; } } static void Main() { var queueProvider = new Provider(); var docs = new List&lt;IItem&gt; { new Document { Id = Guid.NewGuid() }, new Document { Id = Guid.NewGuid() }, new Document { Id = Guid.NewGuid() }, new Document { Id = Guid.NewGuid() }, new Document { Id = Guid.NewGuid() } }; try { var tasks = new List&lt;Task&gt;(); var task1 = Task.Factory.StartNew(() =&gt; { var timer1 = new Timer(1000) { Interval = 1000 }; timer1.Elapsed += (object sender, ElapsedEventArgs e) =&gt; { queueProvider.Load(docs, 1); }; timer1.Enabled = true; timer1.Start(); }); tasks.Add(task1); var task2 = Task.Factory.StartNew(() =&gt; { var timer1 = new Timer(1000) { Interval = 1000 }; timer1.Elapsed += (object sender, ElapsedEventArgs e) =&gt; { queueProvider.Load(docs, 2); }; timer1.Enabled = true; timer1.Start(); }); tasks.Add(task2); //Dequeue //var task3 = Task.Factory.StartNew(() =&gt; //{ // var timer1 = new Timer(3000) { Interval = 1000 }; // timer1.Elapsed += (object sender, ElapsedEventArgs e) =&gt; // { // queueProvider.Dequeue(); // }; // timer1.Enabled = true; // timer1.Start(); //}); //tasks.Add(task3); Task.WaitAll(tasks.ToArray()); } catch (Exception e) { Console.WriteLine(e); } Console.ReadKey(); } } public interface IItem { Guid Id { get; set; } } public interface IProvider { void Enqueue(IItem feedingItem, int id); } public class Provider : IProvider { private readonly ConcurrentQueue&lt;IItem&gt; queue; private readonly ConcurrentDictionary&lt;Guid, DateTime&gt; inputBuffor; private readonly object locker = new object(); private int maxQueueCount = 3; public Provider() { queue = new ConcurrentQueue&lt;IItem&gt;(); inputBuffor = new ConcurrentDictionary&lt;Guid, DateTime&gt;(); } public IItem Dequeue() { queue.TryDequeue(out var item); Console.WriteLine("Dequeue: " + item.Id); return item; } public void Enqueue(IItem item, int id) { //lock (locker) //{ if (inputBuffor.TryAdd(item.Id, DateTime.Now)) { queue.Enqueue(item); Console.WriteLine("Enqueue: " + item.Id + "taskId: " + id); Console.WriteLine("Count: " + queue.Count + " Buffor: " + inputBuffor.Count); } else { Console.WriteLine("Not Enqueue: " + item.Id + "taskId: " + id); } //} } public void Load(IEnumerable&lt;IItem&gt; data, int id) { foreach (var item in data) { if (queue.Count &lt; maxQueueCount) Enqueue(item, id); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T21:16:15.570", "Id": "391764", "Score": "2", "body": "Welcome to the site. Just for your information: Answers here usually takes a bit of time, sometimes several days or weeks. If you improve your question you can make it easier for...
[ { "body": "<p>So you want a queue with a maximum size, and you don't want the same item to be enqueued again.</p>\n\n<p>There are a few problems with the code:</p>\n\n<ul>\n<li><code>Load</code> is not thread-safe: it's not preventing other threads from enqueuing items after the queue-count check, so it's possi...
{ "AcceptedAnswerId": "203283", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T09:17:01.487", "Id": "203225", "Score": "-1", "Tags": [ "c#", "multithreading", "thread-safety", "queue" ], "Title": "Thread-safe queue mechanism" }
203225
<p>Stuck with the <a href="https://github.com/joblib/joblib/issues/167" rel="nofollow noreferrer">issue</a> with memory consumption - after running joblib's Parallel, deleting results and gc.collect() -ing I still have increased memory (checking by htop for process line). Found no way to free memory back. To broaden <strong>yangqch</strong> <a href="https://github.com/joblib/joblib/issues/167#issuecomment-60874719" rel="nofollow noreferrer">answer</a> I use such code to isolate memory for parallel computations:</p> <p>Imports -</p> <pre><code>import multiprocessing as mp n_cores = mp.cpu_count() import time import datetime from sklearn.externals.joblib import Parallel, delayed import sklearn from functools import partial import pickle </code></pre> <p>joblib progress bar -</p> <pre><code>class BatchCompletionCallBack(object): # Added code - start global total_n_jobs global jobs_start_time # Added code - end def __init__(self, dispatch_timestamp, batch_size, parallel): self.dispatch_timestamp = dispatch_timestamp self.batch_size = batch_size self.parallel = parallel def __call__(self, out): self.parallel.n_completed_tasks += self.batch_size this_batch_duration = time.time() - self.dispatch_timestamp self.parallel._backend.batch_completed(self.batch_size, this_batch_duration) self.parallel.print_progress() # Added code - start progress = self.parallel.n_completed_tasks / total_n_jobs elapsed = int((time.time() - jobs_start_time) / self.parallel.n_completed_tasks * (total_n_jobs - self.parallel.n_completed_tasks)) print( "\r[{:50s}] {:.1f}% - Elapsed time {} ".format( '#' * int(progress * 50) , progress*100 , datetime.timedelta(seconds=elapsed)) , end="", flush=True) if self.parallel.n_completed_tasks == total_n_jobs: print('\n') # Added code - end if self.parallel._original_iterator is not None: self.parallel.dispatch_next() sklearn.externals.joblib.parallel.BatchCompletionCallBack = BatchCompletionCallBack </code></pre> <p>Parallel wrapper -</p> <pre><code>def parallel_wrapper(func, *args, **kwargs): global total_n_jobs, jobs_start_time total_n_jobs = len(args[0]) jobs_start_time = time.time() if kwargs: mapfunc = partial(func, **kwargs) else: mapfunc = func with open('file.pkl', 'wb') as file: pickle.dump(Parallel(n_jobs=n_cores)(map(delayed(mapfunc), *args)), file) print('Operating time - ', datetime.timedelta(seconds=int(time.time() - jobs_start_time))) </code></pre> <p>Class to use in 'with' construction -</p> <pre><code>class isolate: def __init__(self, func): self.func = func def __enter__(self): return self def run(self, func, *args, **kwargs): self.p = mp.Process(target=self.func, args=(func, *args), kwargs=kwargs) self.p.start() def __exit__(self, exc_type, exc_val, exc_tb): self.p.join() </code></pre> <p>Example -</p> <pre><code>def dummy(i, keyword_argument=None): return (i.shape, keyword_argument) import numpy as np tmp = np.ones((5,5)) with isolate(parallel_wrapper) as isolated: isolated.run(dummy, [tmp, tmp], keyword_argument=2) with open('file.pkl', 'rb') as file: tmp = pickle.load(file) tmp import importlib importlib.reload(sklearn.externals.joblib.parallel) </code></pre> <p>So questions are:</p> <ul> <li>is there an easier way</li> <li>how to make local variable 'total_n_jobs' from 'parallel_wrapper' viewable in 'BatchCompletionCallBack' without 'global'</li> <li>any improvements</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T10:09:23.403", "Id": "203229", "Score": "3", "Tags": [ "python", "python-3.x", "memory-management", "scope" ], "Title": "Memory release after joblib.Parallel [python]" }
203229
<h3>Environment details</h3> <ul> <li>Python 3.6.5</li> <li>Django 2.0 (which is not necessarily needed for this review)</li> </ul> <hr /> <h3>Class details</h3> <p>I have a small class which holds 3 <code>staticmethod</code>s (I know they should be avoided and use simple functions instead, but I decided to have them all together under the same class).</p> <p>Each of these methods generates a description based on some information (<code>validated_data</code> and <code>vm_x, .., db_x, ..,</code>). The last method decides what description get's returned based on a dropdown.</p> <hr /> <h3>Code</h3> <pre><code>class OrderDescription: @staticmethod def standalone(validated_data): vm_1, db_1 = UsdDBActions().reserve_ci(2) payload = [ { 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'hostname': vm_1, 'number_of_cpu': validated_data['cpu_licenses'], 'ram_gb': validated_data['compute_units'] * 7, 'resolver_group': 'SSC.Computing &amp; Internal Outsourcing', 'twenty_four_team': '24H STAID Computing and Internal Outsourcing', 'service_window': 'businesshours', 'ci': vm_1, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Virtual Server', }, { 'hostname': validated_data['database_name'], 'attached_to_server': vm_1, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': 'businesshours', 'model': 'Oracle 12.1.0.1', 'ci': db_1, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, } ] created_vm_1 = UsdDBActions().create_ci(vm_1, payload[0]) created_db_1 = UsdDBActions().create_ci(db_1, payload[1]) if created_vm_1 and created_db_1: description = f&quot;&quot;&quot; Created VM: {vm_1} Created DB: {db_1} - Portal information - Create network assets and log IP information in CMDB. -&gt; 1x IP address in VLAN {validated_data['environment'].vlan} - Create 1 x OVM type {validated_data['level']} -&gt; VLAN: {validated_data['environment'].vlan} -&gt; Primary Location: {validated_data['primary_location']} -&gt; vCPU = {validated_data['cpu_licenses']} -&gt; vMEm = {validated_data['compute_units'] * 7} -&gt; vStorage = {validated_data['storage_capacity']} - Create 1 x Database type {validated_data['level']} -&gt; Name: {validated_data['database_name']} -&gt; Character set: {validated_data['character_set']} -&gt; National Character set: {validated_data['national_character_set']} -&gt; Type: {validated_data['level']} -&gt; License: {validated_data['licence']} -&gt; DNS information: {validated_data['dns'].server} - {validated_data['dns'].domain} - CSC request to enable monitoring - CSC to enable backup with retention {validated_data['backup'].retention} - Feedback -&gt; Database Name (SID) -&gt; Database port -&gt; IP addresses -&gt; Host name -&gt; User/password &quot;&quot;&quot; else: description = 'Could not create ci' response = { 'description': textwrap.dedent(description), 'created_vms': [vm_1], 'created_dbs': [db_1], 'created_clusters': [], } return response @staticmethod def cluster_dr(validated_data): vm_1, vm_2, db_1, db_2 = UsdDBActions().reserve_ci(4) payload = [ { 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'hostname': vm_1, 'number_of_cpu': validated_data['cpu_licenses'], 'ram_gb': validated_data['compute_units'] * 7, 'resolver_group': 'SSC.Computing &amp; Internal Outsourcing', 'twenty_four_team': '24H STAID Computing and Internal Outsourcing', 'service_window': 'businesshours', 'ci': vm_1, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Virtual Server', }, { 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'hostname': vm_2, 'number_of_cpu': validated_data['cpu_licenses'], 'ram_gb': validated_data['compute_units'] * 7, 'resolver_group': 'SSC.Computing &amp; Internal Outsourcing', 'twenty_four_team': '24H STAID Computing and Internal Outsourcing', 'service_window': 'businesshours', 'ci': vm_2, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Virtual Server', }, { 'hostname': validated_data['database_name'], 'attached_to_server': vm_1, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': '247', 'model': 'Oracle 12.1.0.1', 'ci': db_1, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, }, { 'hostname': validated_data['database_name'], 'attached_to_server': vm_2, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': '247', 'model': 'Oracle 12.1.0.1', 'ci': db_2, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, } ] created_vm_1 = UsdDBActions().create_ci(vm_1, payload[0]) created_vm_2 = UsdDBActions().create_ci(vm_2, payload[1]) created_db_1 = UsdDBActions().create_ci(db_1, payload[2]) created_db_2 = UsdDBActions().create_ci(db_2, payload[3]) if created_vm_1 and created_vm_2 and created_db_1 and created_db_2: description = f&quot;&quot;&quot; Created VMs: {vm_1, vm_2} Created DBs: {db_1, db_2} - Portal information - Create network assets and log IP information in CMDB. -&gt; 2 x IP address in VLAN {validated_data['environment'].vlan} - Create Virtual server 1 -&gt; VLAN: {validated_data['environment'].vlan} -&gt; Primary Location: {validated_data['primary_location']} -&gt; vCPU = {validated_data['cpu_licenses']} -&gt; vMEm = {validated_data['compute_units'] * 7} -&gt; vStorage = {validated_data['storage_capacity']} - Create Virtual server 2 -&gt; VLAN: {validated_data['environment'].vlan} -&gt; Primary Location: {validated_data['secondary_location']} -&gt; vCPU = {validated_data['cpu_licenses']} -&gt; vMEm = {validated_data['compute_units'] * 7} -&gt; vStorage = {validated_data['storage_capacity']} - Create 1 x Database type {validated_data['level']} -&gt; Name: {validated_data['database_name']} -&gt; Character set: {validated_data['character_set']} -&gt; National Character set: {validated_data['national_character_set']} -&gt; Location: {validated_data['primary_location']} -&gt; Type: {validated_data['level']} -&gt; License: {validated_data['licence']} -&gt; DNS information: {validated_data['dns'].server} - {validated_data['dns'].domain} - Create 1 x Database type {validated_data['level']} -&gt; Name: {validated_data['database_name']} -&gt; Character set: {validated_data['character_set']} -&gt; National Character set: {validated_data['national_character_set']} -&gt; Location: {validated_data['secondary_location']} -&gt; Type: {validated_data['level']} -&gt; License: {validated_data['licence']} -&gt; DNS information: {validated_data['dns'].server} - {validated_data['dns'].domain} - CSC request to enable monitoring - CSC request to enable backup with retention {validated_data['backup'].retention} - Feedback -&gt; Database Names (SID) -&gt; Database ports -&gt; IP addresses -&gt; Host names -&gt; 1 x User/password &quot;&quot;&quot; else: description = 'Could not create ci' response = { 'description': textwrap.dedent(description), 'created_vms': [vm_1, vm_2], 'created_dbs': [db_1, db_2], 'created_clusters': [], } return response @staticmethod def geocluster_ha_dr(validated_data): cl_1, cl_2, vm_1, vm_2, vm_3, vm_4, db_1, db_2, db_3, db_4, db_5, db_6 = UsdDBActions().reserve_ci(12) payload = [ { 'organization': validated_data['environment'].organization_cgkprimarykey, 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'class': 'Cluster', 'status': 'To be installed', 'ci': cl_1, 'hostname': f&quot;{validated_data['database_name']} Active&quot;, }, { 'organization': validated_data['environment'].organization_cgkprimarykey, 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'class': 'Cluster', 'status': 'To be installed', 'ci': cl_2, 'hostname': f&quot;{validated_data['database_name']} Standby&quot;, }, { 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'hostname': vm_1, 'number_of_cpu': validated_data['cpu_licenses'], 'ram_gb': validated_data['compute_units'] * 7, 'resolver_group': 'SSC.Computing &amp; Internal Outsourcing', 'twenty_four_team': '24H STAID Computing and Internal Outsourcing', 'service_window': 'businesshours', 'ci': vm_1, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Virtual Server', 'attached_to_server': cl_1 }, { 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'hostname': vm_2, 'number_of_cpu': validated_data['cpu_licenses'], 'ram_gb': validated_data['compute_units'] * 7, 'resolver_group': 'SSC.Computing &amp; Internal Outsourcing', 'twenty_four_team': '24H STAID Computing and Internal Outsourcing', 'service_window': 'businesshours', 'ci': vm_2, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Virtual Server', 'attached_to_server': cl_1, }, { 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'hostname': vm_3, 'number_of_cpu': validated_data['cpu_licenses'], 'ram_gb': validated_data['compute_units'] * 7, 'resolver_group': 'SSC.Computing &amp; Internal Outsourcing', 'twenty_four_team': '24H STAID Computing and Internal Outsourcing', 'service_window': 'businesshours', 'ci': vm_3, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Virtual Server', 'attached_to_server': cl_2, }, { 'configuration': validated_data['environment'].configuration_cgkprimarykey, 'hostname': vm_4, 'number_of_cpu': validated_data['cpu_licenses'], 'ram_gb': validated_data['compute_units'] * 7, 'resolver_group': 'SSC.Computing &amp; Internal Outsourcing', 'twenty_four_team': '24H STAID Computing and Internal Outsourcing', 'service_window': 'businesshours', 'ci': vm_4, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Virtual Server', 'attached_to_server': cl_2, }, { 'hostname': f&quot;{validated_data['database_name']}A1&quot;, 'attached_to_server': vm_1, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': 'businesshours', 'model': 'Oracle 12.1.0.1', 'ci': db_1, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, }, { 'hostname': f&quot;{validated_data['database_name']}A2&quot;, 'attached_to_server': vm_3, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': 'businesshours', 'model': 'Oracle 12.1.0.1', 'ci': db_2, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, }, { 'hostname': f&quot;{validated_data['database_name']}S1&quot;, 'attached_to_server': vm_1, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': 'businesshours', 'model': 'Oracle 12.1.0.1', 'ci': db_3, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, }, { 'hostname': f&quot;{validated_data['database_name']}S2&quot;, 'attached_to_server': vm_1, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': 'businesshours', 'model': 'Oracle 12.1.0.1', 'ci': db_4, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, }, { 'hostname': f&quot;{validated_data['database_name']}A&quot;, 'attached_to_server': cl_1, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': 'businesshours', 'model': 'Oracle 12.1.0.1', 'ci': db_5, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, }, { 'hostname': f&quot;{validated_data['database_name']}S&quot;, 'attached_to_server': cl_2, 'resolver_group': 'SSC.Database Oracle', 'roleflagmanagement': 1, 'service_window': 'businesshours', 'model': 'Oracle 12.1.0.1', 'ci': db_6, 'status': 'To be installed', 'organization': validated_data['environment'].organization_cgkprimarykey, 'class': 'Database', 'configuration': validated_data['environment'].configuration_cgkprimarykey, } ] created_cl_1 = UsdDBActions().create_ci(cl_1, payload[0]) created_cl_2 = UsdDBActions().create_ci(cl_2, payload[1]) created_vm_1 = UsdDBActions().create_ci(vm_1, payload[2]) created_vm_2 = UsdDBActions().create_ci(vm_2, payload[3]) created_vm_3 = UsdDBActions().create_ci(vm_3, payload[4]) created_vm_4 = UsdDBActions().create_ci(vm_4, payload[5]) created_db_1 = UsdDBActions().create_ci(db_1, payload[6]) created_db_2 = UsdDBActions().create_ci(db_2, payload[7]) created_db_3 = UsdDBActions().create_ci(db_3, payload[8]) created_db_4 = UsdDBActions().create_ci(db_4, payload[9]) created_db_5 = UsdDBActions().create_ci(db_5, payload[10]) created_db_6 = UsdDBActions().create_ci(db_6, payload[11]) if (created_cl_1 and created_cl_2 and created_vm_1 and created_vm_2 and created_vm_3 and created_vm_4 and created_db_1 and created_db_2 and created_db_3 and created_db_4 and created_db_5 and created_db_6): description = f&quot;&quot;&quot; Created VM: {vm_1, vm_2, vm_3, vm_4} Created DB: {db_1, db_2, db_3, db_4, db_5, db_6} Created Clusters: {cl_1, cl_2} - Portal information - Create network assets and log IP information in CMDB. -&gt; 14 x IP address in VLAN {validated_data['environment'].vlan} -&gt; IP range in VLAN {validated_data['environment'].vlan} (/29) + 4 IP addresses in range {validated_data['environment'].ip_range} - Create Virtual server 1 -&gt; VLAN: {validated_data['environment'].vlan} -&gt; Primary Location: {validated_data['primary_location']} -&gt; vCPU = {validated_data['cpu_licenses']} -&gt; vMEm = {validated_data['compute_units'] * 7} -&gt; vStorage = {validated_data['storage_capacity']} - Create Virtual server 2 -&gt; VLAN: {validated_data['environment'].vlan} -&gt; Primary Location: {validated_data['primary_location']} -&gt; vCPU = {validated_data['cpu_licenses']} -&gt; vMEm = {validated_data['compute_units'] * 7} -&gt; vStorage = {validated_data['storage_capacity']} - Create Virtual server 3 -&gt; VLAN: {validated_data['environment'].vlan} -&gt; Primary Location: {validated_data['secondary_location']} -&gt; vCPU = {validated_data['cpu_licenses']} -&gt; vMEm = {validated_data['compute_units'] * 7} -&gt; vStorage = {validated_data['storage_capacity']} - Create Virtual server 4 -&gt; VLAN: {validated_data['environment'].vlan} -&gt; Primary Location: {validated_data['secondary_location']} -&gt; vCPU = {validated_data['cpu_licenses']} -&gt; vMEm = {validated_data['compute_units'] * 7} -&gt; vStorage = {validated_data['storage_capacity']} - Create 1 x Database type {validated_data['level']} -&gt; Name: {validated_data['database_name']} -&gt; Character set: {validated_data['character_set']} -&gt; National Character set: {validated_data['national_character_set']} -&gt; Use RAC: {validated_data['use_rac']} -&gt; Location: {validated_data['primary_location']} -&gt; Type: {validated_data['level']} -&gt; License: {validated_data['licence']} -&gt; DNS information: {validated_data['dns'].server} - {validated_data['dns'].domain} - CSC request to enable monitoring - CSC request to enable backup with retention {validated_data['backup'].retention} - Feedback -&gt; Database Names (SID) -&gt; Database ports -&gt; IP addresses: SCAN address -&gt; 1 x User/password &quot;&quot;&quot; else: description = 'Could not create ci' response = { 'description': textwrap.dedent(description), 'created_vms': [vm_1, vm_2, vm_3, vm_4], 'created_dbs': [db_1, db_2, db_3, db_4, db_5, db_6], 'created_clusters': [cl_1, cl_2], } return response def get_description(self, validated_data): level = validated_data['level'] if level == 'Standalone': return self.standalone(validated_data) elif level == 'Cluster (DR)': return self.cluster_dr(validated_data) elif level == 'Geocluster (HA + DR)': return self.geocluster_ha_dr(validated_data) else: return 'No description available' </code></pre> <hr /> <h3>Review</h3> <p>What <strong>I'm looking</strong> for in this review is to make this code a bit more abstract as it became a bit messy. It looks like if I were to add more options this would become hardly maintainable in the future.</p> <p>What I'm <strong>not looking</strong> for in a review:</p> <ul> <li>docstrings (I'll put those after I'll have the final version done)</li> <li>tests</li> </ul> <p>Any other improvements / ideas / constructive critiques are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T15:24:22.710", "Id": "391714", "Score": "0", "body": "What is `UsdDBActions().reserve_ci(num)` doing? Returning a tuple of strings?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T15:28:00.850", "...
[ { "body": "<ul>\n<li>There's a lot of duplication here for like items. A sign that loops and templates will\nreduce redundancy.</li>\n<li>There's a few distinct steps here. Better to separate each step to separate concerns. For example, there's 1. creating the payload 2. creating the CI, 3. describing what was ...
{ "AcceptedAnswerId": "203256", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T11:22:16.040", "Id": "203231", "Score": "1", "Tags": [ "python", "python-3.x", "django" ], "Title": "Let's make this Order nicer" }
203231
<p>I apologise if the title is not very descriptive. If someone can recommend a clearer one I'll edit it. I have an exercise question as:</p> <blockquote> <p>The language L={a<sup><i>n</i></sup>b<sup><i>n</i></sup>} where <i>n</i> ≥ 1, is a language of all words with the following properties:</p> <ul> <li>The words consist of strings of a’s followed by b’s.</li> <li>The number of b’s is equal the number of a’s. </li> <li>Examples of words that belong to L are:</li> </ul> <p>ab, where <em>n</em>=1;</p> <p>aabb, where <em>n</em>=2;</p> <p>aaabbb, where <em>n</em>=3;</p> <p>aaaabbbb, where <em>n</em>=4.</p> <p>One way to test if a word <em>w</em> belong to this language L is to use a stack to check if the number of a’s balances the number of b’s. Use the following header and write a function <strong><em>isInLanguageL2</em></strong> that uses a stack to test if any word belongs to L. If <em>w</em> belongs to L then the <strong><em>isInLanguageL2</em></strong> should return true otherwise <strong><em>isInLanguageL2</em></strong> should return false.</p> <p><strong><em>bool isInLanguageL(string w);</em></strong></p> <p>Note the following:</p> <ul> <li>Only words belonging to L should be accepted.</li> <li>The word bbaa does not belong to L.</li> <li>Do not count the number of a’s or b’s.</li> </ul> </blockquote> <p>I've written the following code which solves the problem. </p> <pre><code>bool isInLanguageL2(string w){ linkedStackType&lt;string&gt; wordStack; int size = w.length(); int a = 0; int b = 0; if(size % 2 != 0) //word length must be an equal number return false; else{ //read first half of word for(int i = 0; i &lt; size/2; i++){ //check if the first half consists of A's if(w[i] != 'a' &amp;&amp; w[i] != 'A') return false; else wordStack.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid } //read second half of word for(int i = size/2; i &lt; size; i++){ //check if the second half consists of B's if(w[i] != 'b' &amp;&amp; w[i] != 'B') return false; else wordStack.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid } } //check number of A's and B's in the stack while(!wordStack.isEmptyStack()){ if(wordStack.top() == "b" || wordStack.top() == "B"){ b++; wordStack.pop(); } else{ a++; wordStack.pop(); } } //check if number of B's is equal to number of A's if(b==a) return true; } </code></pre> <p>However, since the question says "Do not count the number of a’s or b’s.", I've instead created two stacks and just compared their lengths. Is there a way to do this using a single stack since the question mentions using <em>a</em> stack without explicitly counting the A's and B's to test the word.</p> <pre><code>bool isInLanguageL2(string w){ linkedStackType&lt;string&gt; wordStackA, wordStackB; int size = w.length(); int a = 0; int b = 0; if(size % 2 != 0) //word length must be an equal number return false; else{ //read first half of word for(int i = 0; i &lt; size/2; i++){ //check if the first half consists of A's if(w[i] != 'a' &amp;&amp; w[i] != 'A') return false; else wordStackA.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid } //read second half of word for(int i = size/2; i &lt; size; i++){ //check if the second half consists of B's if(w[i] != 'b' &amp;&amp; w[i] != 'B') return false; else wordStackB.push(string(1, w[i])); //convert char to string and push to stack if the letter is valid } } //check if number of B's is equal to number of A's if(wordStackA.length() == wordStackB.length()); return true; } </code></pre> <p>Also, I have a follow up to this question. A sort of extension. Should I add it here or create a new question for it as it might make this question rather long.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T13:54:05.443", "Id": "391700", "Score": "0", "body": "I wonder if the intent of the exercise is for you to push when you see an `a`, and pop when you see a `b`. It's an error if the stack underflows or is not empty at the end. But...
[ { "body": "<p>This exercise is somewhat unsettling. On the one hand, a <code>stack</code>, as part of a <a href=\"https://en.wikipedia.org/wiki/Pushdown_automaton\" rel=\"nofollow noreferrer\">pushdown automaton</a>, is the canonical way to decide balanced languages such as this one; on the other hand, there ar...
{ "AcceptedAnswerId": "203237", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T13:28:32.937", "Id": "203234", "Score": "9", "Tags": [ "c++", "parsing" ], "Title": "Match a simple balanced language" }
203234
<p>I created a function that checks to see if a particular set of data has been added to a listbox and returns a boolean to indicate if the value was found or not.</p> <p>I am asking for critiques on my code.</p> <p>EDIT: I just noticed the BasicInclude.DebugMode variable, I use that so that users see a standard messagebox, where when I run through the code, I want to know the line it fails on and the state of variables etc.</p> <pre><code>Public Function checklist2(ByVal argValue As Variant, ByRef argControl As Control, Optional ByVal argColumn As Variant = 0) As Boolean If Not BasicInclude.DebugMode Then On Error GoTo Error_Handler Else On Error GoTo 0 Dim i As Long Dim j As Long Dim u1 As Long Dim u2 As Long Dim start As Long Dim b As Boolean If argControl.ControlType = acComboBox Or argControl.ControlType = acListBox Then If argControl.ColumnHeads Then start = 1 Else start = 0 If VarType(argValue) &gt;= vbArray And VarType(argColumn) &gt;= vbArray Then u1 = UBound2(argValue) u2 = UBound2(argColumn) If u1 &gt; 0 And u2 &gt; 0 Then If u1 = u2 Then For i = start To argControl.ListCount - 1 b = True For j = 0 To u1 If Not (argControl.Column(argColumn(j), i) Like argValue(j)) Then b = False End If Next If b Then checklist2 = True Exit Function End If Next ElseIf u1 &gt; u2 Then For i = start To argControl.ListCount - 1 b = True For j = 0 To u2 If Not (argControl.Column(argColumn(j), i) Like argValue(j)) Then b = False End If Next If b Then checklist2 = True Exit Function End If Next Else For i = start To argControl.ListCount - 1 b = True For j = 0 To u1 If Not (argControl.Column(argColumn(j), i) Like argValue(j)) Then b = False End If Next If b Then checklist2 = True Exit Function End If Next End If Else checklist2 = False Exit Function End If ElseIf VarType(argValue) &gt;= vbArray Then For i = start To argControl.ListCount - 1 If argControl.Column(argColumn, i) Like argValue(0) Then checklist2 = True Exit Function End If Next ElseIf VarType(argColumn) &gt;= vbArray Then For i = start To argControl.ListCount - 1 If argControl.Column(argColumn(0), i) Like argValue Then checklist2 = True Exit Function End If Next Else For i = start To argControl.ListCount - 1 If argControl.Column(argColumn, i) Like argValue Then checklist2 = True Exit Function End If Next End If End If checklist2 = False Error_Exit: Exit Function Error_Handler: StandardErrorBox "checklist2", Err checklist2 = False Resume Error_Exit End Function </code></pre> <p>It uses two helper functions, Ubound2 which is just a wrapper to catch the error if it has an invalid array, </p> <pre><code>Public Function UBound2(ByVal argArray As Variant, Optional ByVal argRank As Long = 1) As Long On Error GoTo Error_Handler 'Error wrapped version of ubound Dim out As Long out = UBound(argArray, argRank) Error_Exit: UBound2 = out Exit Function Error_Handler: out = -1 Resume Error_Exit End Function </code></pre> <p>and StandardErrorBox because i current cant get vbWatchdog.</p> <pre><code>Public Sub StandardErrorBox(ByVal argSource As String, ByRef e As ErrObject, Optional ByRef daoE As DAO.Errors = Nothing, Optional ByVal argExtra As String = "", Optional ByVal argSilent As Boolean = False) Dim msg As String Dim er As DAO.Error msg = "The following error(s) has/have occured" &amp; vbCrLf &amp; vbCrLf &amp; "Error Number: " &amp; e.Number &amp; vbCrLf &amp; _ "Error Source: " &amp; e.Source &amp; vbCrLf &amp; _ "Error Description: " &amp; e.Description If Not daoE Is Nothing Then If e.Source Like "*[oO][dD][bB][cC]*" Then msg = msg &amp; vbCrLf &amp; vbCrLf &amp; "DAO errors" &amp; vbCrLf For Each er In daoE msg = msg &amp; vbCrLf &amp; "Error Number: " &amp; er.Number &amp; vbCrLf &amp; _ "Error Source: " &amp; er.Source &amp; vbCrLf &amp; _ "Error Description: " &amp; er.Description Next End If End If If argExtra &lt;&gt; "" Then msg = msg &amp; vbCrLf &amp; vbCrLf &amp; "Additional Information: " &amp; argExtra End If msg = msg &amp; vbCrLf &amp; vbCrLf &amp; "Function: " &amp; argSource If argSilent Then MsgBox msg, vbOKOnly + vbCritical, "An Error has Occured!" Else Debug.Print msg End If End Sub </code></pre>
[]
[ { "body": "<h2>Errors and Omissions</h2>\n\n<p>The <code>UBound2</code> function is simply incorrect. You are operating on the assumption that every array is base zero with positive indexing...</p>\n\n<pre><code>Private Sub ExampleOne()\n Dim bar() As Long\n ReDim bar(-10 To -5)\n\n Dim idx As Long\n ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T16:20:56.720", "Id": "203240", "Score": "2", "Tags": [ "vba" ], "Title": "A function that tells you if a particular set of data exists in a listbox" }
203240
<p>I have an image cropper that crops the uploaded image, Before sending it to the server using PHP and AJAX.</p> <p>Here is a <a href="http://jsfiddle.net/zmt2pxva/1/" rel="noreferrer">live fiddle</a> to preview a working cropping example.</p> <p>Here is the code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Create cropped part. function getRoundedCanvas(sourceCanvas) { var canvas = document.createElement('canvas'); var context = canvas.getContext('2d'); var width = sourceCanvas.width; var height = sourceCanvas.height; canvas.width = width; canvas.height = height; context.imageSmoothingEnabled = true; context.drawImage(sourceCanvas, 0, 0, width, height); context.globalCompositeOperation = 'destination-in'; context.beginPath(); context.arc(width / 2, height / 2, Math.min(width, height) / 2, 0, 2 * Math.PI, true); context.fill(); return canvas; } // On uploading a file $("#input").on("change", function(e) { var _URL = window.URL || window.webkitURL, file = this.files[0], image = new Image(); image.src = _URL.createObjectURL(file); image.onload = function(e) { var image = document.getElementById('image'), button = document.getElementById('button'); $('#image').attr('src', _URL.createObjectURL(file)); $('#image').show(); $('#button').show(); var cropper = new Cropper(image, { aspectRatio: 1, movable: false, cropBoxResizable: true, dragMode: 'move', ready: function () { croppable = true; button.onclick = function () { var croppedCanvas; var roundedCanvas; var roundedImage; if (!croppable) { return; } // Crop croppedCanvas = cropper.getCroppedCanvas(); cropper.getCroppedCanvas({ fillColor: '#fff', imageSmoothingEnabled: true, imageSmoothingQuality: 'high', }); // Round roundedCanvas = getRoundedCanvas(croppedCanvas); // Show roundedImage = document.createElement('img'); roundedImage.src = roundedCanvas.toDataURL(); result.innerHTML = ''; result.appendChild(roundedImage); } } }); } }); </code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#image, #button{ display:none }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Cropper CSS --&gt; &lt;link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.css"&gt; &lt;!-- Cropper JS --&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.4.1/cropper.min.js"&gt;&lt;/script&gt; &lt;script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"&gt;&lt;/script&gt; &lt;!-- File input --&gt; &lt;input type="file" id="input" name="image"&gt; &lt;!-- Selected image will be displayed here --&gt; &lt;img id="image" src="" alt="Picture"&gt; &lt;!-- Button to scrop the image --&gt; &lt;button type="button" id="button"&gt;Crop&lt;/button&gt; &lt;!-- Preview cropped part --&gt; &lt;div id="result"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Upload an image and click <kbd>crop</kbd>, The cropped part would be displayed beneath it.</p> <p>Then I use the following code to send a <code>blob</code> to PHP using Ajax:</p> <pre><code>cropper.getCroppedCanvas().toBlob(function (blob) { var formData = new FormData(); formData.append('avatar', blob); // Use `jQuery.ajax` method $.ajax('upload.php', { method: "POST", data: formData, processData: false, contentType: false, success: function (response) { }, error: function () { } }); }); </code></pre> <p>In <code>upload.php</code>:</p> <pre><code>if( isset($_FILES['avatar']) and !$_FILES['avatar']['error'] ){ file_put_contents( "uploads/image.png", file_get_contents($_FILES['avatar']['tmp_name']) ); } </code></pre> <p>Should I make some checks for security or just the dimensions and size checks?</p>
[]
[ { "body": "<blockquote>\n <p><strong>Should I make some checks for security or just the dimensions and size checks?</strong></p>\n</blockquote>\n\n<p>It would be simple to check the type of the file uploaded. For example, you could check if the type is an image. For example, if the user uploads a PNG file, <co...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T16:51:54.127", "Id": "203244", "Score": "6", "Tags": [ "javascript", "php", "jquery", "image", "ajax" ], "Title": "Send blob image using Ajax/PHP" }
203244
<p>I've found myself today really struggling with this subject and I'm pretty sure that there must be a better way to do this.</p> <p>First of all my arrays have the same layout, I need to merge them and <strong>sum every value by <em>domain</em></strong>. </p> <p>Let me give you an example:</p> <pre><code>$array[0]['X1']['Y1'] = 1; $array[0]['X1']['Y2'] = 2; $array[0]['INFO']['DOMAIN'] = 'example1.com'; $array[1]['X1']['Y1'] = 1; $array[1]['X1']['Y2'] = 2; $array[1]['INFO']['DOMAIN'] = 'example1.com'; $array[2]['X1']['Y1'] = 2; $array[2]['X1']['Y2'] = 5; $array[2]['INFO']['DOMAIN'] = 'example2.com'; $array[3]['X1']['Y1'] = 2; $array[3]['X1']['Y2'] = 5; $array[3]['INFO']['DOMAIN'] = 'example2.com'; </code></pre> <p>I need to produce the following new array:</p> <pre><code>$mergedArray[0]['X1']['Y1'] = 2; $mergedArray[0]['X1']['Y2'] = 4; $mergedArray[0]['INFO']['DOMAIN'] = 'example1.com'; $mergedArray[1]['X1']['Y1'] = 4; $mergedArray[1]['X1']['Y2'] = 10; $mergedArray[1]['INFO']['DOMAIN'] = 'example2.com'; </code></pre> <p>I'm using the following code to achieve this (forgive me for the bad namings).</p> <pre><code>foreach($array as $subKey =&gt; $subValue) { foreach($subValue as $key =&gt; $value) { foreach($value as $key2 =&gt; $value2) { if($key2=='DOMAIN' &amp;&amp; !isset($merged[$value2])) { $merged[$value2] = $subValue; } else if ($key2=='DOMAIN' &amp;&amp; isset($merged[$value2])) { foreach($subValue as $key3=&gt;$value3) { foreach($value3 as $key4=&gt;$value4) { if($key4!='DOMAIN') $merged[$value2][$key3][$key4] += $value4; } } } } } } </code></pre> <p>How could I improve this piece of code? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T06:13:13.957", "Id": "391801", "Score": "0", "body": "Where does this data come from? Do you have control of the input or output format?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T22:58:18.660", ...
[ { "body": "<p>Presuming that the format will be consistent, you could remove one <code>foreach</code> loop and extract the domain to use as the key of the merged array, and also only either set the sub array (with keys <code>X1</code>, <code>Y1</code> and <code>Y2</code>) or add to the sub array items. </p>\n\n...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T17:22:54.593", "Id": "203245", "Score": "1", "Tags": [ "php", "array", "php5", "iteration" ], "Title": "Merging and summing multi-dimensional arrays" }
203245
<p>After a long break I took the suggestions from <a href="https://codereview.stackexchange.com/questions/197007/console-based-vocabulary-trainer">Console based Vocabulary Trainer</a> and reworked the Trainer.</p> <p>It contains of the following parts</p> <ul> <li><p><strong>Vocabulary.h/cpp:</strong> Save and read vocabulary from/to text file</p></li> <li><p><strong>Settings.h/cpp:</strong> Save and read some basic settings like color and languages from / to text file</p></li> <li><p><strong>Menu.h/cpp:</strong> The Text based menus of the programm.</p></li> <li><p><strong>Menu_utility.h/cpp:</strong> Helper functions used in the menu functions</p></li> <li><p><strong>Init_to_wide_char.h/cpp:</strong> Commands to init the console into wide char. According to my research the first time wcin /wcout facilities are used the console has to turned to wide char with these commands.</p></li> </ul> <p>The biggest things changed since the last Version: - All Vocabulary gets readed and writed at once. This drastically simplifies the management of the vocabulary - Eliminated all Menu classes. Now all submenus can be used on its own theoretically</p> <p>Now the the questions I have.</p> <ul> <li><p>Do I really have to use wchar everywere in the program? I introduced it in the first Version to enable the correct display of special signs which are language dependend. For example <code>öäüß</code> in german language or <code>ñ</code> in spanish language. From my understanding operating under Windows i have to use widechar to display these correct which is quite a mess. Also i would like to know if I really need the commands in <code>Init_to_wide_char.h</code></p></li> <li><p>Im using Microsoft Visual Studio 2017 with Core guidelines checker turned on. I get two warnings from it which I cant get rid of:</p> <p>Severity Code Description Project File Line Suppression State Warning C26495 Variable 'settings::Settings::m_threshold_learnd' is uninitialized. Always initialize a member variable (type.6). </p> <p>Severity Code Description Project File Line Suppression State Warning C26495 Variable 'vocabulary::Vocabulary::m_practice_right' is uninitialized. Always initialize a member variable (type.6). </p></li> </ul> <p>Is this a bug? I see everything initalized in the Settings and Vocabulary Classes.</p> <ul> <li><p>In <code>menu_show_vocabulary</code> I use a call to _getch() (it is hidden in the function <code>read_single_char()</code> which is called) to achieve that I can move the pages with the arrow keys &lt;- -> or enter number 1 to start searching for a word. Is there a better way to archieve this in c++?</p></li> <li><p>Anything else you would do to improve the code?</p></li> <li>Can it be more simplified and made cleaner?</li> </ul> <p>And here is the full code.</p> <p><b> Vocabulary.h </b></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;vector&gt; namespace vocabulary { std::vector&lt;std::wstring&gt; line_to_words(const std::wstring&amp; line); std::wstring words_to_line(const std::vector&lt;std::wstring&gt;&amp; words); class Vocabulary { public: Vocabulary() = default; Vocabulary(const std::vector&lt;std::wstring&gt;&amp; source_words, const std::vector&lt;std::wstring&gt;&amp; target_words) :m_source_words{source_words},m_target_words{target_words} { } Vocabulary(const std::wstring&amp; source_words_as_line, const std::wstring&amp; target_words_as_line) :m_source_words(line_to_words(source_words_as_line)), m_target_words(line_to_words(target_words_as_line)) { } std::vector&lt;std::wstring&gt; get_source_words()const { return m_source_words; } std::vector&lt;std::wstring&gt; get_target_words()const { return m_target_words; } std::wstring get_source_word_as_line()const { return words_to_line(m_source_words); } std::wstring get_target_word_as_line()const { return words_to_line(m_target_words); } int get_practiced_right() const { return m_practice_right; } void set_source_words(const std::vector&lt;std::wstring&gt;&amp; source_words) { m_source_words = source_words; } void set_target_words(const std::vector&lt;std::wstring&gt;&amp; target_words) { m_target_words = target_words; } void set_practiced_right(int practice_right) { m_practice_right = practice_right; } private: std::vector&lt;std::wstring&gt; m_source_words{}; std::vector&lt;std::wstring&gt; m_target_words{}; int m_practice_right{ 0 }; //practiced_right }; std::wostream&amp; operator&lt;&lt;(std::wostream&amp; os, const Vocabulary&amp; obj); std::wistream&amp; operator&gt;&gt;(std::wistream&amp; is, Vocabulary&amp; obj); inline bool operator==(const Vocabulary&amp; lhs, const Vocabulary&amp; rhs) // practiced right is not considered and may differ { return (lhs.get_source_words() == rhs.get_target_words()) &amp;&amp; (lhs.get_target_words() == rhs.get_target_words()); } std::vector&lt;Vocabulary&gt; read_from_file(const std::string&amp; filename); void write_to_file(const std::string&amp; filename, std::vector&lt;Vocabulary&gt; vocabulary); } </code></pre> <p><b> Vocabulary.cpp </b></p> <pre><code>#include "Vocabulary.h" #include "Init_to_wide_char.h" #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;cstdio&gt; namespace vocabulary { //____________________________Helper functions std::wostream&amp; operator&lt;&lt;(std::wostream&amp; os, const Vocabulary&amp; obj) { init_wchar::init_stdout(); for (const auto&amp; word : obj.get_source_words()) { os &lt;&lt; word + L" "; } os &lt;&lt; "# "; for (const auto&amp; word : obj.get_target_words()) { os &lt;&lt; word + L" "; } os &lt;&lt; "# "; os &lt;&lt; obj.get_practiced_right(); return os; } std::wistream&amp; operator&gt;&gt;(std::wistream&amp; is, Vocabulary&amp; obj) // vocabulary format source name # target name # practiced // e.g //así es # genau # 0 //atrás # hinter # 0 //bonito pero no práctico # schön aber nicht praktisch # 0 { init_wchar::init_stdin(); std::wstring line; std::getline(is,line); std::wistringstream ifs{ line }; Vocabulary tmp; std::vector&lt;std::wstring&gt; source_word; bool first = false; for (std::wstring s; ifs &gt;&gt; s;) { if (s == L"#") { first = true; break; } source_word.push_back(s); } if (!first) { // end of stream but first # not found is.setstate(std::ios::failbit); return is; } tmp.set_source_words(source_word); std::vector&lt;std::wstring&gt; target_word; bool second = false; for (std::wstring s; ifs &gt;&gt; s;) { if (s == L"#") { second = true; break; } target_word.push_back(s); } if (!second) { // same for second is.setstate(std::ios::failbit); return is; } std::wstring practiced_right; ifs &gt;&gt; practiced_right; tmp.set_target_words(target_word); try { tmp.set_practiced_right(std::stoi(practiced_right)); } catch (...) { is.setstate(std::ios::failbit); return is; } obj = tmp; return is; } std::vector&lt;std::wstring&gt; line_to_words(const std::wstring&amp; line) { std::wistringstream ifs{ line }; std::vector&lt;std::wstring&gt; words; for (std::wstring word; ifs &gt;&gt; word;) { words.push_back(word); } return words; } std::wstring words_to_line(const std::vector&lt;std::wstring&gt;&amp; words) //makes a vector of strings to a line seperated by whitespace { std::wstring line; for (const auto&amp;word : words) { line = line + word + L' '; } if (!line.empty()) { // remove last ' ' line.pop_back(); } return line; } std::vector&lt;Vocabulary&gt; read_from_file(const std::string&amp; filename) { init_wchar::init_stdin(); std::wifstream ifs{ filename }; if (!ifs) { throw std::runtime_error( "std::vector&lt;Vocabulary&gt; read_from_file(const std::wstring&amp; filename)\n" "File " + filename + " could not be opened\n" ); } std::vector&lt;Vocabulary&gt; vocabularys; for (Vocabulary vocabulary; ifs &gt;&gt; vocabulary;) { vocabularys.push_back(vocabulary); } return vocabularys; } void write_to_file(const std::string&amp; filename, std::vector&lt;Vocabulary&gt; vocabularys) { init_wchar::init_stdout(); std::wofstream ofs{ filename }; for (const auto&amp; vocabulary : vocabularys) { ofs &lt;&lt; vocabulary &lt;&lt; '\n'; } } } </code></pre> <p><b> settings.h </b></p> <pre><code>#pragma once #include &lt;string&gt; namespace settings { class Settings { public: Settings() = default; Settings(int threshold_learned, const std::wstring&amp; source_language, const std::wstring&amp; target_language, char color_background, char color_font); void set_threshold_learned(int threshold_learned) { m_threshold_learnd = threshold_learned; } void set_name_of_source_language(const std::wstring&amp; source_language) { m_source_language = source_language; } void set_name_of_target_language(const std::wstring&amp; target_language) { m_target_language = target_language; } void set_color_background(int color_background) { m_color_background = static_cast&lt;char&gt;(color_background); } void set_color_font(int color_font) { m_color_font = static_cast&lt;char&gt;(color_font); } int get_threshold_learned() const { return m_threshold_learnd; } std::wstring get_source_language() const { return m_source_language; } std::wstring get_target_language() const { return m_target_language; } char get_color_background() const { return m_color_background; } char get_color_font() const { return m_color_font; } private: int m_threshold_learnd{ 10 }; std::wstring m_source_language{ L"spanish" }; std::wstring m_target_language{ L"german" }; char m_color_background{ 0 }; char m_color_font{ 15 }; }; std::wostream&amp; operator&lt;&lt;(std::wostream&amp; os, const Settings&amp; obj); std::wistream&amp; operator&gt;&gt;(std::wistream&amp; is, Settings&amp; obj); Settings read_from_file(const std::string&amp; filename); void write_to_file(const std::string&amp; filename, Settings&amp; settings); } </code></pre> <p><b> settings.cpp </b></p> <pre><code>#include "Settings.h" #include "Init_to_wide_char.h" #include &lt;fstream&gt; namespace settings { Settings::Settings(int threshold_learned, const std::wstring&amp; source_language, const std::wstring&amp; target_language, char color_background, char color_font) :m_threshold_learnd{ threshold_learned }, m_source_language{ source_language }, m_target_language{ target_language }, m_color_background{ color_background }, m_color_font{ color_font } { init_wchar::init_stdin(); init_wchar::init_stdout(); if (threshold_learned &lt; 0) throw std::runtime_error("Settings(int threshold_learned, const std::wstring&amp; source_language, const std::wstring&amp; target_language, char color_background, char color_font)\n" "tthreshold_learned &lt; 0\n"); if(color_background &lt; 0 || color_background &gt; 15 || color_font &lt; 0 || color_font &gt; 15) throw std::runtime_error("Settings(int threshold_learned, const std::wstring&amp; source_language, const std::wstring&amp; target_language, char color_background, char color_font)\n" "(color_background &lt; 0 || color_background &gt; 15 || color_font &lt; 0 || color_font &gt; 15)"); } //____________________________Helper functions std::wostream&amp; operator&lt;&lt;(std::wostream&amp; os, const Settings&amp; obj) { os &lt;&lt; obj.get_threshold_learned() &lt;&lt; '\t' &lt;&lt; obj.get_source_language() &lt;&lt; '\t' &lt;&lt; obj.get_target_language() &lt;&lt; '\t' &lt;&lt; static_cast&lt;int&gt;(obj.get_color_background()) &lt;&lt; '\t' &lt;&lt; static_cast&lt;int&gt;(obj.get_color_font()); return os; } std::wistream&amp; operator&gt;&gt;(std::wistream&amp; is, Settings&amp; obj) { int threshold_learned; is &gt;&gt; threshold_learned; if (!is) { is.setstate(std::ios::failbit); return is; } std::wstring source_language; is &gt;&gt; source_language; if (!is) { is.setstate(std::ios::failbit); return is; } std::wstring target_language; is &gt;&gt; target_language; if (!is) { is.setstate(std::ios::failbit); return is; } int color_background; is &gt;&gt; color_background; if (!is) { is.setstate(std::ios::failbit); return is; } int color_font; is &gt;&gt; color_font; if (!is) { is.setstate(std::ios::failbit); return is; } Settings tmp(threshold_learned, source_language, target_language, static_cast&lt;char&gt;(color_background), static_cast&lt;char&gt;(color_font)); obj = tmp; return is; } Settings read_from_file(const std::string&amp; filename) { init_wchar::init_stdin(); std::wifstream ifs{ filename }; if (!ifs) { throw std::runtime_error( "Settings read_from_file(const std::string&amp; filename)\n" "File " + filename + " could not be opened\n" ); } Settings settings; ifs &gt;&gt; settings; return settings; } void write_to_file(const std::string&amp; filename, Settings&amp; settings) { init_wchar::init_stdout(); std::wofstream ofs{ filename }; ofs &lt;&lt; settings; } } </code></pre> <p><b> Menu.h </b></p> <pre><code> #pragma once #include "Vocabulary.h" namespace menu { void menu_main(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings); void menu_practice_vocabulary(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings); void menu_add_vocabulary(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings); void menu_show_vocabulary(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings); void menu_search_vocabulary(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings); void menu_erase_vocabulary(const std::vector&lt;vocabulary::Vocabulary&gt;::iterator&amp; it_delete, std::vector&lt;vocabulary::Vocabulary&gt;&amp; vocabulary, const std::string&amp; filename_settings); void menu_settings(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings); void menu_change_color(const std::string&amp; filename_settings); void menu_set_threshold_vocabulary_learned(const std::string&amp; filename_settings); void menu_reset_vocabulary_learned(const std::string&amp; filename_vocabulary); void menu_set_languages(const std::string&amp; filename_settings); } &lt;b&gt; Menu.cpp &lt;/b&gt; #include"Menu.h" #include "Menu_utility.h" #include "Settings.h" #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;sstream&gt; #include "Init_to_wide_char.h" namespace menu { void menu_main(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); settings::Settings settings; if (file_exists(filename_settings)) { // overwrite default settings if there is a settings file settings = settings::read_from_file(filename_settings); } else { settings::write_to_file(filename_settings,settings); } change_color(settings.get_color_background(), settings.get_color_font()); enum class Menu_main_choice { practice = 1, add = 2, show = 3, settings = 4, exit = 5 }; while (true) { Menu_main_choice choice = static_cast&lt;Menu_main_choice&gt;(get_int(1, 5, bissmann_print + L"\n Enter a number to choose an option:" "\n [1] Practice vocabulary" "\n [2] Add new vocabulary to database" "\n [3] Show all words currently in the database. Delete words in database" "\n [4] Settings" "\n [5] End program" "\n")); switch (choice) { case Menu_main_choice::practice: menu_practice_vocabulary(filename_vocabulary,filename_settings); break; case Menu_main_choice::add: menu_add_vocabulary(filename_vocabulary, filename_settings); break; case Menu_main_choice::show: { menu_show_vocabulary(filename_vocabulary, filename_settings); break; } case Menu_main_choice::settings: { menu_settings(filename_vocabulary, filename_settings); break; } case Menu_main_choice::exit: return; } } } void menu_practice_vocabulary(const std::string&amp; filename_vocabulary,const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); clear_screen(); if (!file_exists(filename_vocabulary)) { std::wcout &lt;&lt; "\n Error: Database is empty. Fill database first with vocabulary\n"; keep_window_open(L"q"); return; } auto vocabulary = vocabulary::read_from_file(filename_vocabulary); if (vocabulary.empty()) { clear_screen(); std::wcout &lt;&lt; "\n Error: Database is empty. Fill database first with vocabulary\n"; keep_window_open(L"q"); return; } const auto settings = settings::read_from_file(filename_settings); int amount = get_int(1, 1000, bissmann_print + L"\n Enter how many words you want to practice.Range 1 - 1000 \n"); int correct_words = 0; for (int i = 1; i &lt;= amount; ++i) { clear_screen(); std::wcout &lt;&lt;bissmann_print; auto repeat_random_generator{ 0 }; auto index{ 0 }; do { index = get_random(0, static_cast&lt;int&gt;(vocabulary.size()) - 1); ++repeat_random_generator; if (repeat_random_generator == 1000) { //assuming after 1000 rolls no valid word could be found so all are "learned" std::wcout &lt;&lt; "\n You learned all vocabulary by repeating each word " &lt;&lt; settings.get_threshold_learned() &lt;&lt; " times correct \n"; keep_window_open(L"q"); return; } } while (vocabulary[index].get_practiced_right() &gt;= settings.get_threshold_learned()); clear_screen(); std::wcout &lt;&lt; bissmann_print &lt;&lt; "\n Word nummber " &lt;&lt; i &lt;&lt; " out of " &lt;&lt; amount &lt;&lt; ":\n" &lt;&lt; "\n The " &lt;&lt; settings.get_source_language() &lt;&lt; " word is:\n\n " &lt;&lt; vocabulary[index].get_source_word_as_line() &lt;&lt; "\n" &lt;&lt; "\n Enter the translation in " &lt;&lt; settings.get_target_language() &lt;&lt; ":\n\n"; std::wcin.ignore(); std::vector&lt;std::wstring&gt; input_words = get_words(); if (input_words == vocabulary[index].get_target_words()) { //word translated right ++correct_words; auto practiced_right = vocabulary[index].get_practiced_right(); ++practiced_right; vocabulary[index].set_practiced_right(practiced_right); std::wcout &lt;&lt; "\n That is correct!!!\n"; if (vocabulary[index].get_practiced_right() &gt;= settings.get_threshold_learned()) std::wcout &lt;&lt; "\n You learned the word. You answered it correct " &lt;&lt; vocabulary[index].get_practiced_right() &lt;&lt; " times\n"; } else { //translated wrong vocabulary[index].set_practiced_right(0); std::wcout &lt;&lt; "\n That is wrong !!!" &lt;&lt; "\n The correct translation is: " &lt;&lt; vocabulary[index].get_target_word_as_line() &lt;&lt; '\n'; } keep_window_open(L"q"); } clear_screen(); std::wcout &lt;&lt; bissmann_print &lt;&lt; "\n You translatet " &lt;&lt; correct_words &lt;&lt; " out of " &lt;&lt; amount &lt;&lt; " words correctly to " &lt;&lt; settings.get_target_language()&lt;&lt;'\n'; keep_window_open(L"q"); vocabulary::write_to_file(filename_vocabulary, vocabulary); return; } void menu_add_vocabulary(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); std::vector&lt;vocabulary::Vocabulary&gt; vocabulary; if (file_exists(filename_vocabulary)) { vocabulary = vocabulary::read_from_file(filename_vocabulary); } const auto settings = settings::read_from_file(filename_settings); while (true) { clear_screen(); int choice = get_int(1, 2, bissmann_print + L"\n [1] Add a new word to the database" "\n [2] Return to main menue" "\n"); if (choice == 2) return; clear_screen(); std::wcout &lt;&lt; bissmann_print &lt;&lt; "\n Enter the " &lt;&lt; settings.get_source_language() &lt;&lt; " word\n"; std::wcin.ignore(); vocabulary::Vocabulary new_vocabulary; std::vector&lt;std::wstring&gt; source_language_words = get_words(); new_vocabulary.set_source_words(source_language_words); clear_screen(); std::wcout &lt;&lt; bissmann_print &lt;&lt; "\n Enter the translation for '" &lt;&lt; new_vocabulary.get_source_word_as_line() &lt;&lt; "' in " &lt;&lt; settings.get_target_language() &lt;&lt; '\n'; std::vector&lt;std::wstring&gt; target_language_words = get_words(); new_vocabulary.set_target_words(target_language_words); vocabulary.push_back(new_vocabulary); std::sort(vocabulary.begin(), vocabulary.end(), [](const vocabulary::Vocabulary&amp; a, const vocabulary::Vocabulary&amp; b) { return a.get_source_word_as_line() &lt; b.get_source_word_as_line(); }); vocabulary::write_to_file(filename_vocabulary,vocabulary); } } void menu_show_vocabulary(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); if (!file_exists(filename_vocabulary)) { clear_screen(); std::wcout &lt;&lt; "\n Database is empty\n"; keep_window_open(L"q"); return; } auto vocabulary = vocabulary::read_from_file(filename_vocabulary); if (vocabulary.empty()) { clear_screen(); std::wcout &lt;&lt; "\n Database is empty\n"; keep_window_open(L"q"); return; } const auto settings = settings::read_from_file(filename_settings); constexpr auto vocabulary_per_page{ 15 }; constexpr char keyboard_button_left_arrow{ 75 }; constexpr char keyboard_button_right_arrow{ 77 }; constexpr auto max_displayed_signs{ 35 }; // complete window = 80 constexpr auto ASCII_smilie{ 2 }; //auto step = Menu_show_choice::start; auto page = 1; while (true) { auto count_of_pages = vocabulary.size() / vocabulary_per_page; if ((vocabulary.size() % vocabulary_per_page) != 0) { //if fracture there must be one more page ++count_of_pages; } clear_screen(); std::wcout &lt;&lt; "row "; std::wcout &lt;&lt; settings.get_source_language() &lt;&lt; ':'; // check what is possible max len and then break to the next line for (size_t i = 0; i &lt; max_displayed_signs - settings.get_source_language().size(); ++i) { std::wcout &lt;&lt; ' '; } std::wcout &lt;&lt; settings.get_target_language() &lt;&lt; ':'; for (size_t i = 0; i &lt; max_displayed_signs - settings.get_target_language().size(); ++i) { std::wcout &lt;&lt; ' '; } std::wcout &lt;&lt; "OK "; for (auto i = 0; i &lt; 80; ++i) { std::wcout &lt;&lt; '-'; } auto start_row = 0 + (page - 1) * vocabulary_per_page; auto end_row{ 0 }; if (page == count_of_pages) { end_row = static_cast&lt;int&gt;(vocabulary.size()); } else { end_row = start_row + vocabulary_per_page; } for (auto i = start_row; i &lt; end_row; ++i) { std::wcout &lt;&lt; std::setw(4) &lt;&lt; std::left &lt;&lt; i+1 &lt;&lt; "|" &lt;&lt; std::setw(max_displayed_signs) &lt;&lt; std::left &lt;&lt; vocabulary[i].get_source_word_as_line().substr(0, max_displayed_signs) &lt;&lt; "|" &lt;&lt; std::setw(max_displayed_signs) &lt;&lt; std::left &lt;&lt; vocabulary[i].get_target_word_as_line().substr(0, max_displayed_signs) &lt;&lt; "|" &lt;&lt; std::setw(2) &lt;&lt; std::left &lt;&lt; vocabulary[i].get_practiced_right(); if (vocabulary[i].get_practiced_right() &gt;= settings.get_threshold_learned()) { std::wcout &lt;&lt; static_cast&lt;char&gt;(ASCII_smilie); } else { std::wcout &lt;&lt; '\n'; } } for (int i = 0; i &lt; 80; ++i) { std::wcout &lt;&lt; '-'; } if (page != 1) { std::wcout &lt;&lt; "&lt;-"; } else { std::wcout &lt;&lt; " "; } if (page != count_of_pages) { std::wcout &lt;&lt; " -&gt;"; } else { std::wcout &lt;&lt; " "; } std::wcout &lt;&lt; " page " &lt;&lt; page &lt;&lt; " of " &lt;&lt; count_of_pages; std::wcout &lt;&lt; "\n Choose an option:" "\n [1] Search for a word to delete it" "\n [2] Return to main menue" "\n"; int choice = read_single_char(); if (choice == '1') { menu_search_vocabulary(filename_vocabulary, filename_settings); vocabulary = vocabulary::read_from_file(filename_vocabulary); read_single_char(); // dirty hack? somehow has to be there to make &lt;- and -&gt; work after going back } else if (choice == '2') { // Back to main Menue vocabulary::write_to_file(filename_vocabulary, vocabulary); return; } else { choice = read_single_char(); //Call twice because first time return always 0xE0 second returns code if (choice == keyboard_button_left_arrow &amp;&amp; page != 1) { --page; } else if (choice == keyboard_button_right_arrow &amp;&amp; page != count_of_pages) { ++page; } } } } void menu_search_vocabulary(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); auto vocabulary = vocabulary::read_from_file(filename_vocabulary); std::wcout &lt;&lt; "\n Enter a word or the specific row to search\n a entry in the vocabulary database:\n"; std::wstring input; std::wcin.ignore(); std::getline(std::wcin, input); auto is_number{ true }; auto delete_row{ 0 }; try { delete_row = std::stoi(input); --delete_row; } catch (...) { is_number = false; } if (is_number) { if (delete_row &lt; 0 || delete_row &gt;= vocabulary.size()) { std::wcout &lt;&lt; "\n Error: No match. Invalid row number enterd\n"; keep_window_open(L"q"); } else { auto source_words = vocabulary[delete_row].get_source_words(); auto it_erase = std::find_if(vocabulary.begin(), vocabulary.end(), [&amp;source_words](const vocabulary::Vocabulary&amp; a) {return a.get_source_words() == source_words; }); menu_erase_vocabulary(it_erase, vocabulary, filename_settings); } } else { // erase by name of vocabulary auto it_erase = std::find_if( vocabulary.begin(), vocabulary.end(), [&amp;input](const vocabulary::Vocabulary&amp; voc) { return voc.get_source_words() == vocabulary::line_to_words(input); } ); if (it_erase == vocabulary.end()) { it_erase = std::find_if( vocabulary.begin(), vocabulary.end(), [&amp;input](const vocabulary::Vocabulary&amp; voc) { return voc.get_target_words() == vocabulary::line_to_words(input); } ); if (it_erase == vocabulary.end()) { std::wcout &lt;&lt; "\n No match found in file\n"; keep_window_open(L"q"); } else { menu_erase_vocabulary(it_erase,vocabulary, filename_settings); } } else { menu_erase_vocabulary(it_erase, vocabulary, filename_settings); } } vocabulary::write_to_file(filename_vocabulary, vocabulary); } void menu_erase_vocabulary(const std::vector&lt;vocabulary::Vocabulary&gt;::iterator&amp; it_delete, std::vector&lt;vocabulary::Vocabulary&gt;&amp; vocabulary, const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); auto choice{ 0 }; constexpr auto max_displayed_signs{ 35 }; // complete window = 80 constexpr auto ASCII_smilie = 2; const auto settings = settings::read_from_file(filename_settings); for (int i = 0; i &lt; 2; ++i) { clear_screen(); std::wostringstream ost; ost &lt;&lt; "Found an entry:\n"; ost &lt;&lt; std::setw(4) &lt;&lt; std::left &lt;&lt; (it_delete - vocabulary.begin()) + 1 &lt;&lt; "|" &lt;&lt; std::setw(max_displayed_signs) &lt;&lt; std::left &lt;&lt; it_delete-&gt;get_source_word_as_line().substr(0, max_displayed_signs) &lt;&lt; "|" &lt;&lt; std::setw(max_displayed_signs) &lt;&lt; std::left &lt;&lt; it_delete-&gt;get_target_word_as_line().substr(0, max_displayed_signs) &lt;&lt; "|" &lt;&lt; std::setw(2) &lt;&lt; std::left &lt;&lt; it_delete-&gt;get_practiced_right(); if (it_delete-&gt;get_practiced_right() &gt;= settings.get_threshold_learned()) { ost &lt;&lt; static_cast&lt;char&gt;(ASCII_smilie); } else { ost &lt;&lt; '\n'; } if (i == 0) { ost &lt;&lt; "\n Choose an option:"; } else if (i == 1) { ost &lt;&lt; "\n ARE YOU SUPER SUPER SURE????"; } ost &lt;&lt; "\n [1] Delete found entry" &lt;&lt; "\n [2] Cancel" &lt;&lt; "\n"; choice = get_int(1, 2, ost.str()); if (choice == 2) { //return to start menue return; } } vocabulary.erase(it_delete); std::wcout &lt;&lt; "\n Hasta la vista baby!!!!!" &lt;&lt; "\n Entry has been terminated.\n"; keep_window_open(L"q"); } void menu_settings(const std::string&amp; filename_vocabulary, const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); enum class Menu_settings_choice { change_color = 1, set_learned = 2, reset_learned = 3, set_languges = 4, exit = 5 }; while (true) { Menu_settings_choice choice = static_cast&lt;Menu_settings_choice&gt;( get_int(1, 5,bissmann_print + L"\n Enter a number to choose an option:" "\n [1] Change color of the background or the letters" "\n [2] Define how often to repeat a word until it counts as learned" "\n [3] Set all vocabulary to not learned" "\n [4] Define target and source language" "\n [5] Return to main menue" "\n" ) ); switch (choice) { case Menu_settings_choice::change_color: menu_change_color(filename_settings); break; case Menu_settings_choice::set_learned: menu_set_threshold_vocabulary_learned(filename_settings); break; case Menu_settings_choice::reset_learned: menu_reset_vocabulary_learned(filename_vocabulary); break; case Menu_settings_choice::set_languges: menu_set_languages(filename_settings); break; case Menu_settings_choice::exit: return; } } } void menu_change_color(const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); auto settings = settings::read_from_file(filename_settings); enum class Menu_change_color_choice { change_background = 1, change_letters = 2, return_to_settings = 3 }; Menu_change_color_choice menu_choice = static_cast&lt;Menu_change_color_choice&gt;(get_int(1, 3, bissmann_print + L"\n Enter a number to choose an option:" "\n [1] Change the color of the background" "\n [2] Change the color of the letters" "\n [3] Return to settings\n") ); if (menu_choice == Menu_change_color_choice::return_to_settings) { return; } std::wstring color_name; std::wostringstream ost; if (menu_choice == Menu_change_color_choice::change_letters) { color_name = hex_to_color(settings.get_color_font()); ost &lt;&lt; "\n The current color of the letters is [" &lt;&lt; static_cast&lt;int&gt;(settings.get_color_font()) &lt;&lt; "] " &lt;&lt; color_name &lt;&lt; "\n Choose a color to change the font by selecting an option:"; } else { // change background color_name = hex_to_color(settings.get_color_background()); ost &lt;&lt; "\n The current color of the background is [" &lt;&lt; static_cast&lt;int&gt;(settings.get_color_background()) &lt;&lt; "] " &lt;&lt; color_name &lt;&lt; "\n Choose a color to change the background by selecting an option:"; } ost &lt;&lt; "\n" "\n [0] Black \t [4] Red \t [8] Gray \t [12] Light Red" "\n [1] Blue \t [5] Purple\t [9] Light Blue \t [13] Light Purple" "\n [2] Green \t [6] Yellow\t [10] Light Green\t [14] Light Yellow" "\n [3] Aqua \t [7] White \t [11] Light Aqua \t [15] Bright White\n\n"; char color_choice = static_cast&lt;char&gt;(get_int(0, 15, bissmann_print + ost.str())); //prevent both have same color == invisible screen if ((menu_choice == Menu_change_color_choice::change_letters &amp;&amp; color_choice == settings.get_color_background()) || (menu_choice == Menu_change_color_choice::change_background &amp;&amp; color_choice == settings.get_color_font())) { std::wcout &lt;&lt; "\n Invalid Input. Back and font color can't be the same!\n"; keep_window_open(L"q"); return; } if (menu_choice == Menu_change_color_choice::change_letters) { settings.set_color_font(color_choice); } else { //change color back settings.set_color_background(color_choice); } change_color(settings.get_color_background(), settings.get_color_font()); settings::write_to_file(filename_settings, settings); } void menu_set_threshold_vocabulary_learned(const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); auto settings = settings::read_from_file(filename_settings); std::wostringstream ost; ost &lt;&lt; "\n Currently each vocabulary has to be translated right" "\n " &lt;&lt; settings.get_threshold_learned() &lt;&lt; " times in a row to make it count as learned." "\n Enter a new value for practiced right. Range: 1 - 99\n"; settings.set_threshold_learned(get_int(1, 99, bissmann_print + ost.str())); settings::write_to_file(filename_settings, settings); } void menu_reset_vocabulary_learned(const std::string&amp; filename_vocabulary) { init_wchar::init_stdin(); init_wchar::init_stdout(); auto vocabulary = vocabulary::read_from_file(filename_vocabulary); auto choice = get_int(1, 2, bissmann_print + L"\n Choose an option:" "\n [1] Reset all words to not learned. Practice right = 0" "\n [2] Return to settings\n"); if (choice == 2) return; choice = get_int(1, 2, bissmann_print + L"\n Are you SUPER SUPER SURE??" "\n [1] Reset all words to not learned. Practice right = 0" "\n [2] Return to settings\n"); if (choice == 2) return; for (auto&amp; entry : vocabulary) { entry.set_practiced_right(0); } std::wcout &lt;&lt; "\n All words changed to not learned\n"; keep_window_open(L"q"); vocabulary::write_to_file(filename_vocabulary, vocabulary); } void menu_set_languages(const std::string&amp; filename_settings) { init_wchar::init_stdin(); init_wchar::init_stdout(); auto settings = settings::read_from_file(filename_settings); enum class Menu_change_language_choice { change_source_language = 1, change_target_language = 2, return_to_settings = 3 }; std::wostringstream ost; ost &lt;&lt; "\n Currently all words need to be translated from " &lt;&lt; settings.get_source_language() &lt;&lt; " to " &lt;&lt; settings.get_target_language() &lt;&lt; "\n Choose an option to change the language" "\n [1] Change the source language (" &lt;&lt; settings.get_source_language() &lt;&lt; ")" "\n [2] Change the target language (" &lt;&lt; settings.get_target_language() &lt;&lt; ")" "\n [3] Return to settings\n"; Menu_change_language_choice choice = static_cast&lt;Menu_change_language_choice&gt;(get_int(1, 3, bissmann_print + ost.str())); if (choice == Menu_change_language_choice::return_to_settings) return; std::wcin.ignore(); switch (choice) { case Menu_change_language_choice::change_source_language: { std::wcout &lt;&lt; "Enter the new source language:\n"; std::wstring new_source_language; std::getline(std::wcin, new_source_language); if (new_source_language.empty()) { std::wcerr &lt;&lt; "Invalid empty string entered\n"; } else { settings.set_name_of_source_language(new_source_language); settings::write_to_file(filename_settings, settings); std::wcout &lt;&lt; "\n New source language saved to settings"; } keep_window_open(L"q"); break; } case Menu_change_language_choice::change_target_language: { std::wcout &lt;&lt; "Enter the new target language:\n"; std::wstring new_target_language; std::getline(std::wcin, new_target_language); if (new_target_language.empty()) { std::wcerr &lt;&lt; "Invalid empty string entered\n"; } else { settings.set_name_of_target_language(new_target_language); settings::write_to_file(filename_settings, settings); std::wcout &lt;&lt; "\n New target language saved to settings"; } keep_window_open(L"q"); break; } } } } </code></pre> <p><b> Menu_utility.h </b></p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include "Init_to_wide_char.h" #include &lt;conio.h&gt; namespace menu { const std::wstring bissmann_print = { L"\n--------Bißmann's-------" "\n---Vocabulary Trainer---" "\n---------V3.0-----------" "\n" }; inline void clear_screen() //Windows only not portable { system("cls"); //WINDOWS ONLY } inline int read_single_char() //Windows only not portable { return _getch(); //WINDOWS ONLY } void change_color(char background, char font); //Windows only not portable std::wstring hex_to_color(int hex); inline char hex_to_ascii(char c) // convert number from hex to ascii. different offsets for 1-9 and a-z in ascii file { c &lt; 10 ? c += 48 : c += 55; return c; } // functions to safely read in an integer void skip_to_int(); int get_int(); int get_int(int low, int high, const std::wstring&amp; greeting, const std::wstring&amp; sorry = L""); std::vector&lt;std::wstring&gt; get_words(); inline void keep_window_open() { init_wchar::init_stdin(); init_wchar::init_stdout(); std::wcin.clear(); std::wcin.ignore(120, '\n'); std::wcout &lt;&lt; "Please enter a character to exit\n"; wchar_t ch; std::wcin &gt;&gt; ch; } inline void keep_window_open(std::wstring s) { init_wchar::init_stdin(); init_wchar::init_stdout(); if (s == L"") return; std::wcin.clear(); std::wcin.ignore(120, '\n'); for (;;) { std::wcout &lt;&lt; "Please enter " &lt;&lt; s &lt;&lt; "to continue"; std::wstring ss; while (std::wcin &gt;&gt; ss &amp;&amp; ss != s) std::wcout &lt;&lt; "Please enter " &lt;&lt; s &lt;&lt; " to exit\n"; return; } } int get_random(int min, int max); inline bool file_exists(const std::string&amp; filename) { std::ifstream ifs(filename.c_str()); return ifs.good(); } } </code></pre> <p><b> Menu_utility.cpp </b></p> <pre><code>include "Menu_utility.h" #include &lt;cwctype&gt; #include &lt;random&gt; #include &lt;sstream&gt; #include &lt;Windows.h&gt; namespace menu { void change_color(char background, char font) { std::string color = "COLOR "; color.push_back(hex_to_ascii(background)); color.push_back(hex_to_ascii(font)); system(color.c_str()); //WINDOWS ONLY } std::wstring hex_to_color(int hex) { const std::vector&lt;std::wstring&gt; color_hex = { { L"Black"}, { L"Blue"}, { L"Green"}, { L"Aqua"}, { L"Red"}, { L"Purple"}, { L"Yellow"}, { L"White"}, { L"Gray"}, { L"Light Blue"}, { L"Light Green"}, { L"Light Aqua"}, { L"Light Red"}, { L"Light Purple"}, { L"Light Yellow"}, { L"Bright White"} }; return color_hex[hex]; } void skip_to_int() { init_wchar::init_stdin(); init_wchar::init_stdout(); if (std::wcin.fail()) { // we found sth that wasnt an integer std::wcin.clear(); // wed like to look at the characters for (wchar_t ch; std::wcin &gt;&gt; ch;) { //throw away non digits if (std::iswdigit(ch) || ch == '-') { std::wcin.unget(); //put the digit back so that we can read the number return; } } } } int get_int() { auto n{ 0 }; while (true) { if (std::wcin &gt;&gt; n) return n; skip_to_int(); } } int get_int(int low, int high, const std::wstring&amp; greeting, const std::wstring&amp; sorry) { init_wchar::init_stdin(); init_wchar::init_stdout(); while (true) { clear_screen(); std::wcout &lt;&lt; greeting; auto n = get_int(); if (low &lt;= n &amp;&amp; n &lt;= high) return n; if (!sorry.empty()) { std::wcout &lt;&lt; sorry; keep_window_open(); } } } std::vector&lt;std::wstring&gt; get_words() //reads in line and returns the individual words of it { init_wchar::init_stdin(); init_wchar::init_stdout(); std::wstring line; std::getline(std::wcin, line); std::wistringstream iss{ line }; std::vector&lt;std::wstring&gt; ret; for (std::wstring in; iss &gt;&gt; in;) { ret.push_back(in); } return ret; } int get_random(int min, int max) { static std::random_device rd; static std::mt19937 mt(rd()); std::uniform_int_distribution&lt;int&gt; distribution(min, max); return distribution(mt); } } </code></pre> <p><b> Init_to_wide_char.h </b></p> <pre><code>#pragma once #include &lt;exception&gt; #include &lt;fcntl.h&gt; #include &lt;io.h&gt; namespace init_wchar { inline void init_stdout() { if (_setmode(_fileno(stdout), _O_U16TEXT) == -1) {//wcout instead of cout throw std::runtime_error("void init_stdout_to_wstring()\nCould not init stdout to wide char"); } } inline void init_stdin() { if (_setmode(_fileno(stdin), _O_U16TEXT) == -1) //wcin instead of cin{ throw std::runtime_error("void init_stdout_to_wstring()\nCould not init stdin to wide char"); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T17:43:00.677", "Id": "203246", "Score": "3", "Tags": [ "c++", "console", "windows", "quiz", "c++17" ], "Title": "Console based Vocabulary Trainer Version 2" }
203246
<p>I'm just trying to get the common values from two distinct files called <code>file1.txt</code> and <code>file2.txt</code> where I'm using Python's <code>set</code> method to get the results and this works.</p> <p>However, I'm looking forward to see if there is better way to do this.</p> <pre><code>#!/grid/common/pkgs/python/v3.6.1/bin/python3 def common_member(): a_set = dataset1 b_set = dataset2 if (a_set &amp; b_set): print(a_set &amp; b_set) else: print("No common elements") with open('file1.txt', 'r') as a: dataset1 = set(a) with open('file2.txt', 'r') as b: dataset2 = set(b) common_member() </code></pre> <h3>file1.txt</h3> <pre><code>teraform101 azure233 teraform221 teraform223 teraform224 </code></pre> <h3>file2.txt</h3> <pre><code>teraform101 azure109 teraform223 teraform226 teraform225 azure233 </code></pre> <h3>Result:</h3> <pre><code>{ 'teraform101\n', 'azure233\n', 'teraform223\n' } </code></pre>
[]
[ { "body": "<p>Global variables (<code>dataset1</code> and <code>dataset2</code>) are bad. I'd rather see you write no function at all than a function that accepts its inputs through global variables:</p>\n\n<pre><code>with open('file1.txt') as file1, open('file2.txt') as file2:\n print((set(file1) &amp; set...
{ "AcceptedAnswerId": "203248", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T18:02:16.330", "Id": "203247", "Score": "3", "Tags": [ "python", "python-3.x", "file" ], "Title": "Get the common values between two text files" }
203247
<p>I wrote this Powershell script years ago for updating AD from a CSV file. I'd like to try to optimize to run quicker and be more efficient... but I'm not sure where to start / what could improve it. Any suggestions are welcome.</p> <p>EDIT: I've updated my original script to this:</p> <pre><code>$users = Import-Csv C:\Scripts\Employees.csv foreach ($user in $users) { $employeeNumber = $User.employeeNumber $Department = $User.department $Title = $User.title $Office = $User.office $Address = $User.address $City = $User.city $State = $User.state $PostalCode = $User.postalCode $Company = $User.company $Telephone = $User.telephone $Mobile = $User.mobile $Fax = $User.fax $Custom1 = $User.custom1 $Custom2 = $User.custom2 $Custom3 = $User.custom3 $Custom4 = $User.custom4 Get-ADUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" ` -SearchBase "OU=Logins,DC=domain,DC=com" | Set-ADUser -Replace @{ ` employeeNumber=$EmployeeNumber; department=$Department; title=$Title; Office=$office; streetAddress=$Address; l=$City; st=$State; postalCode=$PostalCode; company=$Company; telephoneNumber=$telephone; mobile=$cell; facsimileTelephoneNumber=$Fax; ExtensionAttribute1=($user.custom1); ExtensionAttribute2=($user.custom2); ExtensionAttribute3=($user.custom3); ExtensionAttribute4=($user.custom4) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T20:29:44.407", "Id": "391753", "Score": "0", "body": "Can you add some of the errors you're receiving?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T15:17:56.947", "Id": "391873", "Score": "...
[ { "body": "<p>Here are a few comments:</p>\n\n<pre><code># -3. No parameters to the script and hard-coded path to the input CSV\n# This makes the script harder for others to reuse\n# -2. No error handling\n# if an employee in the CSV doesn't exist in AD, for instance,\n# you might want to know about...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T19:33:56.927", "Id": "203252", "Score": "2", "Tags": [ "powershell", "active-directory" ], "Title": "Powershell script that updates Active Directory user information" }
203252
<p>This is an OOP question and probably answerable even if you don’t have PHP knowledge. (A side note – we are learning PHP OOP and decided to create a github to hopefully help others learn this and other best practices a bit easier, <a href="https://github.com/nizamani/PHPBestPractices1-OOP" rel="noreferrer">https://github.com/nizamani/PHPBestPractices1-OOP</a> if you are interested. PRs, issues etc are very welcome)</p> <p>I think we have two questions that are intertwined, but if you think I should split this up into a single question please let me know.</p> <p><strong>Overview</strong></p> <p>A simple app with 3 database tables, containing users’ name, age, favorite food and favorite restaurant.</p> <p><strong>Goal/Output</strong></p> <p>Our current goal (exact question will be listed below) is to use OOP and a <code>user</code> object to <em>get and display</em> a single user's name, age, favorite food, and favorite restaurant.</p> <p>Example output:</p> <p><em>"User's name is Jenn, age is 28, favorite restaurant is KFC and favorite food is Fried Chicken"</em></p> <p><strong>Database</strong></p> <p>To make this as simple as possible for beginners to try out, we’ve created a "fake db" using php arrays. The db “tables” are:</p> <pre><code>users id name age favoriteRestaurantId favoriteFoodId 1 Mike 30 1 1 2 Jenn 28 3 3 restaurants id name 1 McDonalds 2 Taco Bell 3 KFC foods id name 1 French Fries 2 Hamburger 3 Fried Chicken </code></pre> <p>Faked as php arrays:</p> <pre><code>// this represents a sql table named `users` $users = array( array("id" =&gt; 1, "name" =&gt; "Mike", "age" =&gt; 30, "favoriteRestaurantId" =&gt; 1, "favoriteFoodId" =&gt; 1), array("id" =&gt; 2, "name" =&gt; "Jenn", "age" =&gt; 28, "favoriteRestaurantId" =&gt; 3, "favoriteFoodId" =&gt; 3) ); // this represents a sql table named `restaurants` $resturants = array( array("id" =&gt; 1, "name" =&gt; "McDonalds"), array("id" =&gt; 2, "name" =&gt; "Taco Bell"), array("id" =&gt; 3, "name" =&gt; "KFC") ); // this represents a sql table named `foods` $foods = array( array("id" =&gt; 1, "name" =&gt; "French Fries"), array("id" =&gt; 2, "name" =&gt; "Hamburger"), array("id" =&gt; 3, "name" =&gt; "Fried Chicken") ); </code></pre> <p>(<a href="https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/fakedatabase/db.php" rel="noreferrer">https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/fakedatabase/db.php</a>)</p> <p><strong>Classes</strong></p> <p>Three classes, one for each table. Each column (except id) in the db maps to a property of the object.</p> <pre><code>class User { private $name; private $age; private $favoriteRestaurantId; private $favoriteFoodId; //...setter and getter methods, nothing more } class Restaurant { private $name; //...setter and getter methods, nothing more } class Food { private $name; //...setter and getter methods, nothing more } </code></pre> <p>(<a href="https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Domain/User/User.php" rel="noreferrer">https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Domain/User/User.php</a></p> <p><a href="https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Domain/Restaurant/Restaurant.php" rel="noreferrer">https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Domain/Restaurant/Restaurant.php</a></p> <p><a href="https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Domain/Food/Food.php" rel="noreferrer">https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Domain/Food/Food.php</a>)</p> <p><strong>Current Usage</strong></p> <p>On a simple page, we want to display user 2's info. Their name, age, <em>name</em> of their favorite food and <em>name</em> of their favorite restaurant. This is how we do that, which we think is way too "manual" of a process:</p> <pre><code> // create user object $userObject = UserFactory::createUser(); // get user data from the db and set to User object $userRow = $this-&gt;usersTransactions-&gt;getUserById(2); $userObject-&gt;setName($userRow["userRow"]["name"]); $userObject-&gt;setAge($userRow["userRow"]["age"]); $userObject-&gt;setFavoriteRestaurantId($userRow["userRow"]["favoriteRestaurantId"]); $userObject-&gt;setFavoriteFoodId($userRow["userRow"]["favoriteFoodId"]); // create restaurant object $restaurantObject = RestaurantFactory::createResturant(); // get restaurant data from the db and set to Restaurant object $userfavoriteRestaurantIdRow = $this-&gt;restaurantsTransactions-&gt;getRestaurantById($userObject-&gt;getFavoriteResturantId()); $restaurantObject-&gt;setName($userfavoriteRestaurantIdRow["restaurantRow"]["name"]); // create food object $foodObject = FoodFactory::createFood(); // get food data from the db and set to Food object $userfavoriteFoodIdRow = $this-&gt;foodsTransactions-&gt;getFoodById($userObject-&gt;getFavoriteFoodId()); $foodObject-&gt;setName($userfavoriteFoodIdRow["foodRow"]["name"]); // this will display the user's information $this-&gt;response-&gt;setView('displayUserInformation/index.php'); $this-&gt;response-&gt;setVars( array( "name" =&gt; $userObject-&gt;getName(), "age" =&gt; $userObject-&gt;getAge(), "restaurant" =&gt; $restaurantObject-&gt;getName(), "food" =&gt; $foodObject-&gt;getName() ) ); </code></pre> <p>(<a href="https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Controller/DisplayUserInformationPage.php" rel="noreferrer">https://github.com/nizamani/PHPBestPractices1-OOP/blob/master/src/classes/Controller/DisplayUserInformationPage.php</a>)</p> <p><strong>Questions</strong></p> <p><strong>Question #1</strong> Would you agree that modifying the user object to contain favorite restaurant <em>name</em> and favorite food <em>name</em> would be best? That is the primary information we are going to be concerned with displaying throughout the app, so we think it logical:</p> <pre><code>class User { private $name; private $age; private $favoriteRestaurantId; private $favoriteFoodId; private $favoriteRestaurantName; private $favoriteFoodName; //...setter and getter methods, nothing more } </code></pre> <p><strong>Question #2</strong> Currently, anywhere we want a user's info, we have to do a lot manually to create a user object, food object, and restaurant object. Seems ripe for mistakes. Imagining a new page where we want to display info of all of the users in our db, we will loop through user ids and then have all this manual stuff inside that loop. That doesn't seem logical, doesn't seem DRY. We think something like this would be very useful to, for example, get user id 2's info:</p> <pre><code>$user = createUserObjectByUserId(2); </code></pre> <p>Then on our hypothetical page where we want to display every user's info, we simply loop through user ids and call this createUserObjectById method. Would you agree? We don't know how best to do this. In our codebase we have a UsersTransactions class, but it is concerned with getting info from the <code>users</code> table. What is the best practice here? We want to follow dependency injection best practices and OOP best practices, and can't really come up with a good way to accomplish this.</p> <p>--</p> <p>Thank you for taking the time to read all of that, and please feel free to tell us everything you would do differently here and in our github if you want to take a look at that. We want to learn best practices and get this right, and hopefully have a decent example for others to learn from.</p>
[]
[ { "body": "<h2>Question 1</h2>\n\n<p>I would agree with this statement, and would actually take it further to follow \"proper OOP practices\". If you choose to implement your classes this way, you do not need to store the IDs of other classes - you can just store a variable that references the other class direc...
{ "AcceptedAnswerId": "203264", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T20:52:04.253", "Id": "203261", "Score": "5", "Tags": [ "php", "object-oriented" ], "Title": "OOP, one class from multiple database tables" }
203261
<p>I wrote this algorithm but i was wondering if there was any way i can make it less 'expensive'. The algorithm needs to transform this data structure:</p> <pre><code>const deliveryHours = { monday: [ { start: { hour: 3, minute: 0, }, end: { hour: 6, minute: 0, }, }, ], tuesday: [ { start: { hour: 3, minute: 0, }, end: { hour: 6, minute: 0, }, }, { start: { hour: 5, minute: 0, }, end: { hour: 3, minute: 0, }, }, ], wednesday: [ { start: { hour: 3, minute: 0, }, end: { hour: 4, minute: 0, }, }, { start: { hour: 5, minute: 0, }, end: { hour: 1, minute: 0, }, }, ], } </code></pre> <p>to:</p> <pre><code>[ { hours: { from: 3, to: 4 }, wednesday: true }, { hours: { from: 3, to: 6 }, tuesday: true, monday: true }, { hours: { from: 5, to: 1 }, wednesday: true }, { hours: { from: 5, to: 3 }, tuesday: true } ] </code></pre> <p>This is my attempt, it is clearly not the best way to go about it but im having a hard time finding another way:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const deliveryHours = { monday: [ { start: { hour: 3, minute: 0, }, end: { hour: 6, minute: 0, }, }, ], tuesday: [ { start: { hour: 3, minute: 0, }, end: { hour: 6, minute: 0, }, }, { start: { hour: 5, minute: 0, }, end: { hour: 3, minute: 0, }, }, ], wednesday: [ { start: { hour: 3, minute: 0, }, end: { hour: 4, minute: 0, }, }, { start: { hour: 5, minute: 0, }, end: { hour: 1, minute: 0, }, }, ], } const mapDeliveryHours = (deliveryHours) =&gt; { const result = {}; for (let i = 0; i &lt; Object.keys(deliveryHours).length; i += 1) { const day = Object.keys(deliveryHours)[i]; const ranges = deliveryHours[day]; for (let j = 0; j &lt; ranges.length; j++) { const range = ranges[j]; result[range.start.hour.toString() + range.end.hour.toString()] = { hours: { from: range.start.hour, to: range.end.hour, }, [day]: true, }; for (let k = 0; k &lt; Object.keys(deliveryHours).length; k++) { const innerDay = Object.keys(deliveryHours)[k]; const innerRanges = deliveryHours[innerDay]; for (let l = 0; l &lt; innerRanges.length; l++) { const innerRange = innerRanges[l]; if (day !== innerDay &amp;&amp; innerRange.start.hour === range.start.hour &amp;&amp; innerRange.end.hour === range.end.hour ) { result[range.start.hour.toString() + range.end.hour.toString()] = { ...result[range.start.hour.toString() + range.end.hour.toString()], [innerDay]: true, }; } } } } } return Object.values(result); }; console.log(mapDeliveryHours(deliveryHours))</code></pre> </div> </div> </p>
[]
[ { "body": "<p>It is not much less code but I believe it is clearer and easier to reason about:</p>\n\n<pre><code>function forEach(target, fn) {\n var keys = Object.keys(target);\n var key;\n var i = -1;\n while (++i &lt; keys.length) {\n key = keys[i];\n fn(target[key], key);\n }\n}...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T01:11:40.330", "Id": "203268", "Score": "2", "Tags": [ "javascript" ], "Title": "Algorithm that combines same objects to single common key" }
203268
<p>I am trying to <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler014/problem" rel="nofollow noreferrer">find the longest Collatz Sequence</a>:</p> <blockquote> <p>Which starting number, ≤ <em>N</em>, produces the longest chain? If many possible such numbers are there print the maximum one. (1 ≤ <em>N</em> ≤ 5×10<sup>6</sup>)</p> </blockquote> <p>I tried optimizing the code to include memoization still getting Time Limit Exceeded, for these solutions. Wanted some help to understand where the method is consuming time.</p> <p><strong>Implementation Using HashMap As Memoized Cache:</strong></p> <pre><code>object CollatzSeq { private final val mapOfCollatzSequence = scala.collection.mutable.HashMap[BigInt, BigInt]() .withDefaultValue(0) def longestCollatzSeq(n: BigInt): BigInt = { def longestCollatzSeqHelper(n: BigInt, count: BigInt = 0): BigInt = { val mapValueOfN = mapOfCollatzSequence(n) n match { case n if n == 1 =&gt; count case _ if mapValueOfN != 0 =&gt; count + mapValueOfN case n if n % 2 == 0 =&gt; val updateForEven = longestCollatzSeqHelper(n/2, count + 1) mapOfCollatzSequence.update(n, updateForEven - count) updateForEven case n if n % 2 != 0 =&gt; val c = longestCollatzSeqHelper(3 * n + 1 , count + 1) mapOfCollatzSequence.update(n, c - count) c } } longestCollatzSeqHelper(n) } } </code></pre> <p><strong>Implementation Using Array As Memoized Cache:</strong></p> <pre><code>object CollatzSeq { // Using Array As Performance Is Better Than Map private final val collatzSeq = Array.fill[BigInt](5* 1000 * 1000)(0) def longestCollatzSeq(n: BigInt): BigInt = { def longestCollatzSeqHelper(n: BigInt, count: BigInt = 0): BigInt = { val countOfN = collatzSeq((n - 1).toInt) n match { case n if n == 1 =&gt; count case _ if countOfN != 0 =&gt; count + countOfN case n if n % 2 == 0 =&gt; val updateForEven = longestCollatzSeqHelper(n/2, count + 1) collatzSeq.update((n-1).toInt, updateForEven - count) updateForEven case n if n % 2 != 0 =&gt; val updateForOdd = longestCollatzSeqHelper(3 * n + 1 , count + 1) collatzSeq.update((n-1).toInt, updateForOdd - count) updateForOdd } } longestCollatzSeqHelper(n) } } </code></pre> <p><a href="https://docs.scala-lang.org/overviews/collections/performance-characteristics.html" rel="nofollow noreferrer"><strong>Performance Reference</strong></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T07:51:58.000", "Id": "391811", "Score": "0", "body": "Hey welcome to Code Review! Please add some description about what problem your code solves (i.e. a quote from the the problem description). This is because links can rot and a q...
[ { "body": "<p>There are a few things you could do to make what you've got a bit faster:</p>\n\n<ol>\n<li>The numbers get quite big but <code>BigInt</code> is overkill (and slow). The <code>longestCollatzSeqHelper()</code> method will have to deal with values in the <code>Long</code> domain, but the problem set,...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T03:46:35.510", "Id": "203271", "Score": "1", "Tags": [ "time-limit-exceeded", "comparative-review", "scala", "memoization", "collatz-sequence" ], "Title": "Longest Collatz sequence in Scala" }
203271
<p>Going to take a look at Rasta's comment below tonight and just realized I am using byref to pass everything again - DUHOH - Old habits die hard</p> <hr> <p>I have revamped with some of Comintern's improvements particularly re naming, interfaces, how to reference game pieces, etc. I still need time re his presenter class.</p> <p>EDIT: This is now - Fully Functional - but a bit lame. I am thinking shields, a type of missile that moves like it is "heat seeking" and a boss.</p> <p>BIG O ANALYSIS incoming to re collisionchecker.</p> <p>I have stripped some stuff and made much cleaner. Should be easier to evaluate. Will add everything to github:</p> <p><a href="https://github.com/Evanml2030/Excel-SpaceInvader" rel="nofollow noreferrer">https://github.com/Evanml2030/Excel-SpaceInvader</a></p> <p>StopWatch was put together by the fellow who runs bytecomb, a great site for vba tips. Link: <a href="https://bytecomb.com/accurate-performance-timers-in-vba/" rel="nofollow noreferrer">https://bytecomb.com/accurate-performance-timers-in-vba/</a></p> <p>The userForm .frm file can be imported. the .frx file must be in the same directory as the frm for it to work.</p> <p><a href="https://i.stack.imgur.com/53ERp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/53ERp.png" alt="enter image description here"></a></p> <p><strong>GAMELOGIC:</strong></p> <pre><code>Attribute VB_Name = "GameLogic" Option Explicit Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr) Sub RunGame() Dim board As GameBoard Dim sleepWatch As StopWatch Dim generateIncSpaceObjectsRound1 As StopWatch Dim generateIncSpaceObjectsRound2 As StopWatch Const interval = 3 Set board = New GameBoard board.Show vbModeless CreateGameItem.CreateGameItem board, objectType.Ship Set generateIncSpaceObjectsRound1 = New StopWatch generateIncSpaceObjectsRound1.Start Set generateIncSpaceObjectsRound2 = New StopWatch generateIncSpaceObjectsRound2.Start Set sleepWatch = New StopWatch sleepWatch.Start Do If CheckCollisions.HandleShipIncSpaceObjectCollisions Then Exit Do CheckCollisions.HandleMissileIncSpaceObjectCollisions board MoveSpaceObjects.MoveIncomingSpaceObjects board MoveSpaceObjects.MoveMissiles board If Format(generateIncSpaceObjectsRound1.Elapsed, "0.000000") &gt; 1.25 Then CreateGameItem.CreateGameItem board, Application.WorksheetFunction.RandBetween(1, 3) CreateGameItem.CreateGameItem board, Application.WorksheetFunction.RandBetween(1, 3) CreateGameItem.CreateGameItem board, Application.WorksheetFunction.RandBetween(1, 3) generateIncSpaceObjectsRound1.Restart Score.IncrementScore Score.UpdateGameBoard board End If If Format(generateIncSpaceObjectsRound2.Elapsed, "0.000000") &gt; 4.25 Then CreateGameItem.CreateGameItem board, Application.WorksheetFunction.RandBetween(1, 3) CreateGameItem.CreateGameItem board, Application.WorksheetFunction.RandBetween(1, 3) CreateGameItem.CreateGameItem board, Application.WorksheetFunction.RandBetween(1, 3) CreateGameItem.CreateGameItem board, Application.WorksheetFunction.RandBetween(1, 3) generateIncSpaceObjectsRound2.Restart End If If Format(sleepWatch.Elapsed, "0.000000") &lt; interval Then Sleep interval - Format(sleepWatch.Elapsed, "0.000000") sleepWatch.Restart End If DoEvents Loop End Sub Public Sub HandleSendKeys(ByRef board As GameBoard, ByRef caseNum As Long) Select Case caseNum Case 37 MoveSpaceObjects.MoveShip left, board Case 39 MoveSpaceObjects.MoveShip Right, board Case 32 If MissileCount.Count &lt; 25 Then CreateGameItem.CreateGameItem board, objectType.missile End If End Select End Sub </code></pre> <p><strong>CHECKCOLLISIONS:</strong></p> <pre><code> Sub HandleMissileIncSpaceObjectCollisions(ByVal board As GameBoard) Dim MissileIterator As IBoundControl Dim IncSpaceObjectIterator As IBoundControl Dim MissileController As Control Dim SpaceObjectController As Control Dim x As Long Dim y As Long For x = CollectionMissiles.Count To 1 Step -1 Set MissileIterator = CollectionMissiles.Item(x) For y = CollectionIncomingSpaceObjects.Count To 1 Step -1 Set IncSpaceObjectIterator = CollectionIncomingSpaceObjects.Item(y) If CheckIfCollided(MissileIterator, IncSpaceObjectIterator) Then DestroyObject.DestroySpaceObject board, MissileIterator CollectionMissiles.remove x DestroyObject.DestroySpaceObject board, IncSpaceObjectIterator CollectionIncomingSpaceObjects.remove y Exit For End If Next y Next x End Sub Function HandleShipIncSpaceObjectCollisions() As Boolean Dim Ship As IBoundControl Dim IncSpaceObjectIterator As IBoundControl Set Ship = CollectionShips.Item(1) For Each IncSpaceObjectIterator In CollectionIncomingSpaceObjects If CheckIfCollided(Ship, IncSpaceObjectIterator) Then HandleShipIncSpaceObjectCollisions = True Exit For End If Next IncSpaceObjectIterator End Function Private Function CheckIfCollided(ByVal first As IBoundControl, ByVal second As IBoundControl) As Boolean Dim hOverlap As Boolean Dim vOverlap As Boolean hOverlap = (first.spaceObject.left - second.spaceObject.width &lt; second.spaceObject.left) And (second.spaceObject.left &lt; first.spaceObject.left + first.spaceObject.width) vOverlap = (first.spaceObject.top - second.spaceObject.height &lt; second.spaceObject.top) And (second.spaceObject.top &lt; first.spaceObject.top + first.spaceObject.height) CheckIfCollided = hOverlap And vOverlap End Function </code></pre> <p><strong>CREATEGAMEITEM:</strong></p> <pre><code>Option Explicit Public Enum objectType alien = 1 comet = 2 star = 3 missile = 4 Ship = 5 End Enum Public Sub CreateGameItem(ByVal board As GameBoard, ByVal val As objectType) Dim CreateGameItem As IBoundControl Select Case val Case objectType.alien Set CreateGameItem = New SpaceObjectAlien Set CreateGameItem.spaceObject = SpaceObjectFactory.NewSpaceObjectAlien(board) CollectionIncomingSpaceObjects.Add CreateGameItem Case objectType.comet Set CreateGameItem = New SpaceObjectComet Set CreateGameItem.spaceObject = SpaceObjectFactory.NewSpaceObjectComet(board) CollectionIncomingSpaceObjects.Add CreateGameItem Case objectType.star Set CreateGameItem = New SpaceObjectStar Set CreateGameItem.spaceObject = SpaceObjectFactory.NewSpaceObjectStar(board) CollectionIncomingSpaceObjects.Add CreateGameItem Case objectType.Ship Set CreateGameItem = New SpaceObjectShip Set CreateGameItem.spaceObject = SpaceObjectFactory.NewSpaceObjectShip(board) CollectionShips.Add CreateGameItem Case objectType.missile Set CreateGameItem = New SpaceObjectMissile Set CreateGameItem.spaceObject = SpaceObjectFactory.NewSpaceObjectMissile(board) CollectionMissiles.Add CreateGameItem MissileCount.UpdateGameBoard board End Select Set CreateGameItem.Control = LoadControl(board, CreateGameItem) InitializeControl CreateGameItem End Sub Private Function LoadControl(ByVal board As GameBoard, ByVal gameItem As IBoundControl) As Control Set LoadControl = board.Controls.Add("Forms.Image.1", gameItem.spaceObject.ImageName) End Function Private Sub InitializeControl(ByVal gameItem As IBoundControl) With gameItem .Control.left = gameItem.spaceObject.left .Control.top = gameItem.spaceObject.top .Control.height = gameItem.spaceObject.height .Control.width = gameItem.spaceObject.width .Control.Picture = LoadPicture(gameItem.spaceObject.ImagePathway) .Control.PictureSizeMode = 1 End With End Sub </code></pre> <p><strong>DESTROYOBJECT:</strong></p> <pre><code>Public Sub DestroySpaceObject(ByVal board As GameBoard, ByRef objectToDestroy As IBoundControl) board.Controls.remove objectToDestroy.spaceObject.ImageName End Sub </code></pre> <p><strong>MOVESPACEOBJECTS:</strong></p> <pre><code>Option Explicit Public Enum Direction left = 0 Right = 1 End Enum Sub MoveIncomingSpaceObjects(ByVal board As GameBoard) Dim iterator As IBoundControl Dim index As Long For index = CollectionIncomingSpaceObjects.Count To 1 Step -1 Set iterator = CollectionIncomingSpaceObjects.Item(index) If iterator.spaceObject.top + 1 &gt;= board.height Then DestroyObject.DestroySpaceObject board, iterator CollectionIncomingSpaceObjects.remove index Else iterator.spaceObject.top = iterator.spaceObject.top + 1 iterator.Control.top = iterator.spaceObject.top End If Next index End Sub Sub MoveMissiles(ByVal board As GameBoard) Dim iterator As IBoundControl Dim index As Long For index = CollectionMissiles.Count To 1 Step -1 Set iterator = CollectionMissiles.Item(index) If iterator.spaceObject.top - 1 &lt;= 0 Then DestroyObject.DestroySpaceObject board, iterator CollectionMissiles.remove index Else iterator.spaceObject.top = iterator.spaceObject.top - 1 iterator.Control.top = iterator.spaceObject.top End If Next index End Sub Sub MoveShip(ByVal val As Direction, ByVal board As GameBoard) Select Case val Case Direction.left If CollectionShips.Item(1).spaceObject.left - 5 &gt;= 0 Then CollectionShips.Item(1).spaceObject.left = CollectionShips.Item(1).spaceObject.left - 4 CollectionShips.Item(1).Control.left = CollectionShips.Item(1).spaceObject.left Else CollectionShips.Item(1).spaceObject.left = 0 CollectionShips.Item(1).Control.left = CollectionShips.Item(1).spaceObject.left End If Case Direction.Right If (CollectionShips.Item(1).spaceObject.left + CollectionShips.Item(1).spaceObject.width) &lt; board.InsideWidth Then CollectionShips.Item(1).spaceObject.left = CollectionShips.Item(1).spaceObject.left + 4 CollectionShips.Item(1).Control.left = CollectionShips.Item(1).spaceObject.left Else CollectionShips.Item(1).spaceObject.left = board.InsideWidth - CollectionShips.Item(1).spaceObject.width CollectionShips.Item(1).Control.left = CollectionShips.Item(1).spaceObject.left End If End Select End Sub </code></pre> <p><strong>MOVESPACEOBJECTFACTORY:</strong></p> <pre><code>Option Explicit Public Function NewSpaceObjectShip(ByVal board As GameBoard) As SpaceObjectShip Dim width As Long Dim height As Long width = 15 height = 30 With New SpaceObjectShip .ImgPathWay = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\SpaceShip.jpg" .SetInitialLeft board.width / 2 .SetInitialTop board.height - (board.height / 8.5) .height = height .width = width .ImageName = "Ship" Set NewSpaceObjectShip = .Self End With End Function Public Function NewSpaceObjectMissile(ByVal board As GameBoard) As SpaceObjectMissile Dim width As Long Dim height As Long width = 15 height = 30 IncrementMissileCount With New SpaceObjectMissile .ImgPathWay = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Missile.jpg" .SetInitialLeft ((CollectionShips.Item(1).spaceObject.width - width) / 2) + CollectionShips.Item(1).spaceObject.left .SetInitialTop CollectionShips.Item(1).spaceObject.top - height .height = height .width = width .ImageName = "Missile" &amp; CStr(MissileCount.Count) Set NewSpaceObjectMissile = .Self End With End Function Private Sub IncrementMissileCount() MissileCount.IncrementMissileCount End Sub Public Function NewSpaceObjectAlien(ByRef board As GameBoard) As SpaceObjectAlien Dim width As Long Dim height As Long width = 20 height = 20 IncrementIncSpaceObjectCount With New SpaceObjectAlien .ImgPathWay = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\AlienShip.jpg" .SetInitialLeft Application.WorksheetFunction.RandBetween(0, board.InsideWidth - width) .SetInitialTop 0 .height = height .width = width .ImageName = "SpaceObject" &amp; CStr(SpaceObjectCount.Count) Set NewSpaceObjectAlien = .Self End With End Function Public Function NewSpaceObjectComet(ByRef board As GameBoard) As SpaceObjectComet Dim width As Long Dim height As Long width = 20 height = 20 IncrementIncSpaceObjectCount With New SpaceObjectComet .ImgPathWay = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Comet.jpg" .SetInitialLeft Application.WorksheetFunction.RandBetween(0, board.InsideWidth - width) .SetInitialTop 0 .width = width .height = height .ImageName = "SpaceObject" &amp; CStr(SpaceObjectCount.Count) Set NewSpaceObjectComet = .Self End With End Function Public Function NewSpaceObjectStar(ByRef board As GameBoard) As SpaceObjectStar Dim width As Long Dim height As Long width = 40 height = 40 IncrementIncSpaceObjectCount With New SpaceObjectStar .ImgPathWay = "C:\Users\evanm\OneDrive\Desktop\Excel\SpaceInvader\Star.jpg" .SetInitialLeft Application.WorksheetFunction.RandBetween(0, board.InsideWidth - width) .SetInitialTop 0 .width = width .height = height .ImageName = "SpaceObject" &amp; CStr(SpaceObjectCount.Count) Set NewSpaceObjectStar = .Self End With End Function Private Sub IncrementIncSpaceObjectCount() SpaceObjectCount.IncrementCount End Sub </code></pre> <p>**CLASSES|SCORE|COLLECTIONS|MISSILECOUNT HAVE Attribute VB_PredeclaredId = True **</p> <p><strong>CollectionIncomingSpaceObjects:</strong></p> <pre><code>Option Explicit Private CollectionIncSpaceObjects As Collection Private Sub Class_Initialize() Set CollectionIncSpaceObjects = New Collection End Sub Private Sub Class_Terminate() Set CollectionIncSpaceObjects = Nothing End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = CollectionIncSpaceObjects.[_NewEnum] End Property Public Sub Add(obj As IBoundControl) CollectionIncSpaceObjects.Add obj End Sub Public Sub remove(index As Variant) CollectionIncSpaceObjects.remove index End Sub Public Property Get Item(index As Variant) As IBoundControl Set Item = CollectionIncSpaceObjects.Item(index) End Property Property Get Count() As Long Count = CollectionIncSpaceObjects.Count End Property Public Sub Clear() Set CollectionIncSpaceObjects = New Collection End Sub </code></pre> <p><strong>COLLECTIONMISSILES:</strong></p> <pre><code>Option Explicit Private CollectionMissles As Collection Private Sub Class_Initialize() Set CollectionMissles = New Collection End Sub Private Sub Class_Terminate() Set CollectionMissles = Nothing End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = CollectionMissles.[_NewEnum] End Property Public Sub Add(obj As IBoundControl) CollectionMissles.Add obj End Sub Public Sub remove(index As Variant) CollectionMissles.remove index End Sub Public Property Get Item(index As Variant) As IBoundControl Set Item = CollectionMissles.Item(index) End Property Property Get Count() As Long Count = CollectionMissles.Count End Property Public Sub Clear() Set CollectionMissles = New Collection End Sub </code></pre> <p><strong>COLLECTIONSHIPS:</strong></p> <pre><code>Option Explicit Private CollectionShips As Collection Private Sub Class_Initialize() Set CollectionShips = New Collection End Sub Private Sub Class_Terminate() Set CollectionShips = Nothing End Sub Public Property Get NewEnum() As IUnknown Set NewEnum = CollectionShips.[_NewEnum] End Property Public Sub Add(obj As IBoundControl) CollectionShips.Add obj End Sub Public Sub remove(index As Variant) CollectionShips.remove index End Sub Public Property Get Item(index As Variant) As IBoundControl Set Item = CollectionShips.Item(index) End Property Property Get Count() As Long Count = CollectionShips.Count End Property Public Sub Clear() Set CollectionShips = New Collection End Sub </code></pre> <p><strong>IBOUNDCONTROL:</strong></p> <pre><code>Option Explicit Public Property Get Control() As Control End Property Public Property Set Control(bound As Control) End Property Public Property Get spaceObject() As ISpaceObject End Property Public Property Set spaceObject(bound As ISpaceObject) End Property </code></pre> <p><strong>ISPACEOBJECT:</strong></p> <pre><code>Option Explicit Public Property Let left(ByRef changeLeft As Long) End Property Public Property Get left() As Long End Property Public Property Let top(ByRef changeTop As Long) End Property Public Property Get top() As Long End Property Public Property Get width() As Long End Property Public Property Get height() As Long End Property Public Property Get ImageName() As String End Property Public Property Get ImagePathway() As String End Property </code></pre> <p><strong>MISSILECOUNT:</strong></p> <pre><code>Option Explicit Private pcount As Long Public Property Get Count() As Long Count = pcount End Property Public Property Let Count(ByRef value As Long) pcount = value End Property Public Sub IncrementMissileCount() pcount = pcount + 1 End Sub Public Sub UpdateGameBoard(ByVal board As GameBoard) board.Controls.Item("MissileCount").Caption = 25 - pcount End Sub </code></pre> <p><strong>SCORE:</strong></p> <pre><code>Option Explicit Private pscore As Long Public Property Get Score() As Long Score = pscore End Property Public Property Let Score(ByRef value As Long) pscore = value End Property Public Sub IncrementScore() pscore = pscore + 1 End Sub Public Sub UpdateGameBoard(ByVal board As GameBoard) board.Controls.Item("Score").Caption = pscore End Sub </code></pre> <p><strong>SPACEOBJECTALIEN:</strong></p> <pre><code>Option Explicit Implements IBoundControl Implements ISpaceObject Private Type AlienData left As Long top As Long width As Long height As Long ImgPathWay As String ImageName As String MyControl As Control MySpaceObj As SpaceObjectAlien End Type Private this As AlienData Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Property Get Self() As SpaceObjectAlien Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Get ISpaceObject_ImageName() As String ISpaceObject_ImageName = this.ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property Public Property Set IBoundControl_Control(ByRef form As Control) Set this.MyControl = form End Property Public Property Get IBoundControl_Control() As Control Set IBoundControl_Control = this.MyControl End Property Public Property Set IBoundControl_SpaceObject(ByRef spcObj As ISpaceObject) Set this.MySpaceObj = spcObj End Property Public Property Get IBoundControl_SpaceObject() As ISpaceObject Set IBoundControl_SpaceObject = this.MySpaceObj End Property </code></pre> <p><strong>SPACEOBJECTCOMET:</strong></p> <pre><code>Option Explicit Implements IBoundControl Implements ISpaceObject Private Type CometData left As Long top As Long width As Long height As Long ImgPathWay As String ImageName As String MyControl As Control MySpaceObj As SpaceObjectComet End Type Private this As CometData Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Property Get Self() As SpaceObjectComet Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Get ISpaceObject_ImageName() As String ISpaceObject_ImageName = this.ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property Public Property Set IBoundControl_Control(ByRef form As Control) Set this.MyControl = form End Property Public Property Get IBoundControl_Control() As Control Set IBoundControl_Control = this.MyControl End Property Public Property Set IBoundControl_SpaceObject(ByRef spcObj As ISpaceObject) Set this.MySpaceObj = spcObj End Property Public Property Get IBoundControl_SpaceObject() As ISpaceObject Set IBoundControl_SpaceObject = this.MySpaceObj End Property </code></pre> <p><strong>SPACEOBJECTCOUNT:</strong></p> <pre><code>Option Explicit Private pcount As Long Public Property Get Count() As Long Count = pcount End Property Public Property Let Count(ByRef value As Long) pcount = value End Property Public Sub IncrementCount() pcount = pcount + 1 End Sub </code></pre> <p><strong>SPACEOBJECTMISSILE:</strong></p> <pre><code>Option Explicit Implements IBoundControl Implements ISpaceObject Private Type MissileData left As Long top As Long width As Long height As Long ImgPathWay As String ImageName As String MyControl As Control MySpaceObj As SpaceObjectMissile End Type Private this As MissileData Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Property Get Self() As SpaceObjectMissile Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Get ISpaceObject_ImageName() As String ISpaceObject_ImageName = this.ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property Public Property Set IBoundControl_Control(ByRef form As Control) Set this.MyControl = form End Property Public Property Get IBoundControl_Control() As Control Set IBoundControl_Control = this.MyControl End Property Public Property Set IBoundControl_SpaceObject(ByRef spcObj As ISpaceObject) Set this.MySpaceObj = spcObj End Property Public Property Get IBoundControl_SpaceObject() As ISpaceObject Set IBoundControl_SpaceObject = this.MySpaceObj End Property </code></pre> <p><strong>SPACEOBJECTSHIP:</strong></p> <pre><code>Option Explicit Implements IBoundControl Implements ISpaceObject Private Type ShipData left As Long top As Long width As Long height As Long ImgPathWay As String ImageName As String MyControl As Control MySpaceObj As SpaceObjectShip ShieldOnOff As Boolean End Type Private this As ShipData Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Property Get Self() As SpaceObjectShip Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Get ISpaceObject_ImageName() As String ISpaceObject_ImageName = this.ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property Public Property Set IBoundControl_Control(ByRef form As Control) Set this.MyControl = form End Property Public Property Get IBoundControl_Control() As Control Set IBoundControl_Control = this.MyControl End Property Public Property Set IBoundControl_SpaceObject(ByRef spcObj As ISpaceObject) Set this.MySpaceObj = spcObj End Property Public Property Get IBoundControl_SpaceObject() As ISpaceObject Set IBoundControl_SpaceObject = this.MySpaceObj End Property </code></pre> <p><strong>SPACEOBJECTSTAR:</strong></p> <pre><code>Option Explicit Implements IBoundControl Implements ISpaceObject Private Type StarData left As Long top As Long width As Long height As Long ImgPathWay As String ImageName As String MyControl As Control MySpaceObj As SpaceObjectStar End Type Private this As StarData Public Sub SetInitialLeft(ByRef initialLeft As Long) this.left = initialLeft End Sub Public Sub SetInitialTop(ByRef initialTop As Long) this.top = initialTop End Sub Public Property Let width(ByRef width As Long) this.width = width End Property Public Property Get width() As Long width = this.width End Property Public Property Let height(ByRef height As Long) this.height = height End Property Public Property Get height() As Long height = this.height End Property Public Property Let ImgPathWay(ByRef pathWayToImg As String) this.ImgPathWay = pathWayToImg End Property Public Property Get ImgPathWay() As String ImgPathWay = this.ImgPathWay End Property Public Property Let ImageName(ByRef Name As String) this.ImageName = Name End Property Public Property Get ImageName() As String ImageName = this.ImageName End Property Public Property Get Self() As SpaceObjectStar Set Self = Me End Property Private Property Get IspaceObject_ImagePathway() As String IspaceObject_ImagePathway = this.ImgPathWay End Property Private Property Get ISpaceObject_ImageName() As String ISpaceObject_ImageName = this.ImageName End Property Private Property Let ISpaceObject_Left(ByRef changeLeft As Long) this.left = changeLeft End Property Private Property Get ISpaceObject_Left() As Long ISpaceObject_Left = this.left End Property Private Property Let ISpaceObject_Top(ByRef changeTop As Long) this.top = changeTop End Property Private Property Get ISpaceObject_Top() As Long ISpaceObject_Top = this.top End Property Private Property Get ISpaceObject_Height() As Long ISpaceObject_Height = this.height End Property Private Property Get ISpaceObject_Width() As Long ISpaceObject_Width = this.width End Property Public Property Set IBoundControl_Control(ByRef form As Control) Set this.MyControl = form End Property Public Property Get IBoundControl_Control() As Control Set IBoundControl_Control = this.MyControl End Property Public Property Set IBoundControl_SpaceObject(ByRef spcObj As ISpaceObject) Set this.MySpaceObj = spcObj End Property Public Property Get IBoundControl_SpaceObject() As ISpaceObject Set IBoundControl_SpaceObject = this.MySpaceObj End Property </code></pre> <p><strong>STOPWATCH:</strong></p> <pre><code>Option Explicit Private Declare PtrSafe Function QueryPerformanceCounter Lib "kernel32" ( _ lpPerformanceCount As UINT64) As Long Private Declare PtrSafe Function QueryPerformanceFrequency Lib "kernel32" ( _ lpFrequency As UINT64) As Long Private pFrequency As Double Private pStartTS As UINT64 Private pEndTS As UINT64 Private pElapsed As Double Private pRunning As Boolean Private Type UINT64 LowPart As Long HighPart As Long End Type Private Const BSHIFT_32 = 4294967296# ' 2 ^ 32 Private Function U64Dbl(U64 As UINT64) As Double Dim lDbl As Double, hDbl As Double lDbl = U64.LowPart hDbl = U64.HighPart If lDbl &lt; 0 Then lDbl = lDbl + BSHIFT_32 If hDbl &lt; 0 Then hDbl = hDbl + BSHIFT_32 U64Dbl = lDbl + BSHIFT_32 * hDbl End Function Private Sub Class_Initialize() Dim PerfFrequency As UINT64 QueryPerformanceFrequency PerfFrequency pFrequency = U64Dbl(PerfFrequency) End Sub Public Property Get Elapsed() As Double If pRunning Then Dim pNow As UINT64 QueryPerformanceCounter pNow Elapsed = pElapsed + (U64Dbl(pNow) - U64Dbl(pStartTS)) / pFrequency Else Elapsed = pElapsed End If End Property Public Sub Start() If Not pRunning Then QueryPerformanceCounter pStartTS pRunning = True End If End Sub Public Sub Pause() If pRunning Then QueryPerformanceCounter pEndTS pRunning = False pElapsed = pElapsed + (U64Dbl(pEndTS) - U64Dbl(pStartTS)) / pFrequency End If End Sub Public Sub Reset() pElapsed = 0 pRunning = False End Sub Public Sub Restart() pElapsed = 0 QueryPerformanceCounter pStartTS pRunning = True End Sub Public Property Get Running() As Boolean Running = pRunning End Property </code></pre>
[]
[ { "body": "<p>This will be a pretty simple review, ignoring some stuff like how you're handling position and whatnot.</p>\n<hr />\n<p>All right. I cloned the directory from github, extracted it, changed the jpeg file paths and managed to <code>RunGame</code> once. After that I always get a compile error</p>\n<b...
{ "AcceptedAnswerId": "203525", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T05:47:33.260", "Id": "203274", "Score": "4", "Tags": [ "beginner", "object-oriented", "game", "vba", "excel" ], "Title": "SpaceInvaders Second Iteration - Fully Functional - Next Up New Presenter Class" }
203274
<p>As per the instructions on this <a href="https://app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/" rel="nofollow noreferrer">Tape Equlibrium-Codility</a></p> <p>I've written the code</p> <pre><code>import java.util.Arrays; public class TapeEqulibrium { int main(int[] array) { int minimumDiff = 100000; for (int i = 1; i &lt; array.length; i++) { int differnce = Math.abs(Arrays.stream(array, 0, i).sum() - Arrays.stream(array, i, array.length).sum()); minimumDiff = differnce &lt; minimumDiff ? differnce : minimumDiff; } return minimumDiff; } } </code></pre> <p>On submission, I have got correct answers for all test cases. But It says that the time complexity is O(n*n)and taking more than 6.00 seconds. while writing I thought that it falls under time complexity of O(n) or something (as I don't know much about that). So I need to know how to calculate the time complexity of this code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T07:42:43.183", "Id": "391808", "Score": "0", "body": "Hey, welcome to Code Review! Here we review working code to make it better (faster, leaner, more secure/readable/maintainable). While a reviewer commenting on the time complexity...
[ { "body": "<p>You inner loop contains:</p>\n\n<pre><code>int differnce = Math.abs(Arrays.stream(array, 0, i).sum() - Arrays.stream(array, i, array.length).sum());\n</code></pre>\n\n<p>That does (i-0) operations for first sum and (array.length-i) for second, for a total of array.length-i+i-0=array.length. As the...
{ "AcceptedAnswerId": "203277", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T06:44:00.120", "Id": "203276", "Score": "0", "Tags": [ "java", "time-limit-exceeded", "complexity" ], "Title": "Time complexity of tape equilibirum" }
203276
<p>I need to validate the fields of user sent by an API. All works fine but the only one problem is that I don't like the solution is not an OOP solution. In the controller I call the service created by me:</p> <pre><code>$userValidatorService = $this-&gt;get(UserValidatorService::class); </code></pre> <p>And the service:</p> <pre><code>class UserValidatorService { /** * @var EntityManagerInterface */ private $entityManager; /** * @var LoggerInterface; */ private $logger; /** * @var TranslatorInterface */ private $translator; /** * @var UserManagerInterface */ private $userManager; /** * @var array */ private $locales; /** * @var User */ private $user; /** * @var array */ private $userFormData; /** * UserValidatorService constructor. * @param EntityManagerInterface $entityManager * @param LoggerInterface $logger * @param TranslatorInterface $translator * @param UserManagerInterface $userManager */ public function __construct( EntityManagerInterface $entityManager, LoggerInterface $logger, TranslatorInterface $translator, UserManagerInterface $userManager ) { $this-&gt;entityManager = $entityManager; $this-&gt;logger = $logger; $this-&gt;translator = $translator; $this-&gt;userManager = $userManager; } /** * @return array */ public function updateUser() { $messages = []; if( '' !== $errorMessage = $this-&gt;validateEmail()){ $messages['email'] = $errorMessage; } if( '' !== $errorMessage = $this-&gt;validateLocale()){ $messages['locale'] = $errorMessage; // and all fields are validated like that } /** * @return string */ private function validateEmail() { if(isset($this-&gt;userFormData['email'])){ if(!filter_var($this-&gt;userFormData['email'], FILTER_VALIDATE_EMAIL)){ return $this-&gt;translator-&gt;trans('error.message'); } return ''; } return $this-&gt;translator-&gt;trans('error.message'); } /** * @return string */ private function validateLocale() { if(isset($this-&gt;userFormData['locale'])){ if(!in_array($this-&gt;userFormData['locale'], $this-&gt;locales)){ return $this-&gt;translator-&gt;trans('error.message'); } return ''; } return $this-&gt;translator-&gt;trans('error.message'); } </code></pre> <p>The question exists as a pattern to use to avoid this duplication and to do more OOP (I repeat that this code works just fine). I want to do that by myself without using Symfony validators.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T07:42:09.470", "Id": "203278", "Score": "3", "Tags": [ "php", "reinventing-the-wheel", "validation", "php5", "symfony3" ], "Title": "Use a pattern for fields validation" }
203278
<p>I wanted to explore how I can associate routes with "controllers" with Sanic as a base. It works fine but "feels" a bit clunky but I can't put my finger on why/how.</p> <p><em>routes.py</em> - Returning controller methods from a given route</p> <pre><code>from .index import IndexRoutes from .clients import ClientRoutes from Controllers.IndexController import * from Controllers.ClientController import * CLASSES = [ IndexRoutes, ClientRoutes ] def add_routes(app): routes = get_routes() for route in routes: for m in route['methods']: controller = m['controller'] method = m['method'] app.add_route( eval(controller + '.' + method), route['prefix'] + m['path'], methods=m['request_methods'] ) def get_routes(): routes = [] for c in CLASSES: methods = getattr(c, 'ROUTE_METHODS') route = { 'name': getattr(c, 'ROUTE_NAME'), 'methods': [], 'prefix': getattr(c, 'ROUTE_PREFIX') } for method in methods: route['methods'].append(getattr(c, method)()) routes.append(route) return routes </code></pre> <p><em>client.py</em> - Example of route definitions</p> <pre><code>class ClientRoutes: ROUTE_NAME = 'clients' ROUTE_METHODS = ['index', 'create', 'update', 'single', 'destroy'] ROUTE_PREFIX = 'clients' def index(): return { 'controller': 'ClientController', 'method': 'index', 'path': '/', 'request_methods': ['GET'] } def create(): return { 'controller': 'ClientController', 'method': 'create', 'path': '/', 'request_methods': ['POST'] } def single(): return { 'controller': 'ClientController', 'method': 'single', 'path': '/&lt;id&gt;', 'request_methods': ['GET'] } def update(): return { 'controller': 'ClientController', 'method': 'update', 'path': '/&lt;id&gt;', 'request_methods': ['PUT'] } def destroy(): return { 'controller': 'ClientController', 'method': 'destroy', 'path': '/&lt;id&gt;', 'request_methods': ['DELETE'] } </code></pre> <p><em>ClientController.py</em> - Example of controller</p> <pre><code>from sanic import response from Database.Model import Model from Database.Client import Client from Helpers.transformers import to_dict class ClientController: async def index(request): clients = Model(Client) return response.json(to_dict(clients.get())) async def create(request): data = request.json try: if 'name' not in data: raise KeyError('Name is required') else: if len(data['name']) &lt; 1: raise ValueError('Name is required') except KeyError as e: return response.json(str(e), 400) except ValueError as e: return response.json(str(e), 400) client = Model(Client) return response.json(to_dict(client.save(data))) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T09:00:14.597", "Id": "203282", "Score": "2", "Tags": [ "python", "python-3.x", "mvc", "asynchronous", "url-routing" ], "Title": "Python (Sanic) Routing" }
203282
<p>I asked a similar question <a href="https://codereview.stackexchange.com/questions/203234">here</a> which is:</p> <blockquote> <p>The language L={a<sup><i>n</i></sup>b<sup><i>n</i></sup>} where <i>n</i> ≥ 1, is a language of all words with the following properties:</p> <ul> <li>The words consist of strings of a’s followed by b’s.</li> <li>The number of b’s is equal the number of a’s. </li> <li>Examples of words that belong to L are:</li> </ul> <p>ab, where <em>n</em>=1;</p> <p>aabb, where <em>n</em>=2;</p> <p>aaabbb, where <em>n</em>=3;</p> <p>aaaabbbb, where <em>n</em>=4.</p> <p>One way to test if a word <em>w</em> belong to this language L is to use a stack to check if the number of a’s balances the number of b’s. Use the following header and write a function <strong><em>isInLanguageL2</em></strong> that uses a stack to test if any word belongs to L. If <em>w</em> belongs to L then the <strong><em>isInLanguageL2</em></strong> should return true otherwise <strong><em>isInLanguageL2</em></strong> should return false.</p> <p><strong><em>bool isInLanguageL(string w);</em></strong></p> <p>Note the following:</p> <ul> <li>Only words belonging to L should be accepted.</li> <li>The word bbaa does not belong to L.</li> <li>Do not count the number of a’s or b’s.</li> </ul> </blockquote> <p>A follow up to that question asks to redo the question using queues (I realize a queue probably isn't the best way to do this, however that's not the point of the exercise): </p> <blockquote> <p>Repeat the previous question using the following header:</p> <p><strong><em>bool isInLanguageL(queueType&lt; char> &amp; w);</em></strong></p> </blockquote> <p>My solution for doing this without actually counting the a's and b's is below. It uses two queues. I "copy" all the a's from the original queue into a temp queue and remove them from the original queue which should have only b's remaining. I then iterate through the temp queue and pop the original queue for every a that is in the temp queue. After checking through the temp queue and if both queues are empty at the end, then the word is valid. </p> <p>My question: How can I accomplish this using a single queue as I think using a temporary queue would be a waste of memory.</p> <p>My code:</p> <pre><code>bool isInLanguageL(linkedQueueType&lt;char&gt; &amp;w){ linkedQueueType&lt;char&gt; temp; if(w.front() != 'a') //queue must start with an a return false; while(w.front() == 'a'){ //iterate through the a's and add them to temp queue temp.addQueue(w.front()); w.deleteQueue(); //remove a's from original queue } while(!temp.isEmptyQueue() &amp;&amp; !w.isEmptyQueue()){ //delete b for each a if(w.front() != 'b') //only b's should remain in original queue return false; else{ w.deleteQueue(); temp.deleteQueue(); } } //both stacks must be empty then number of b=a and word is valid if(w.isEmptyQueue() &amp;&amp; temp.isEmptyQueue()) return true; return false; } int main() { linkedQueueType&lt;char&gt; wordQueue; std::string word; std::cout &lt;&lt; "Enter a word belonging to language L. "; std::cin &gt;&gt; word; for(int i = 0; i &lt; word.length(); i++){ wordQueue.addQueue(word[i]); } if(isInLanguageL(wordQueue)) std::cout &lt;&lt; word &lt;&lt; " is a valid word."; else std::cout &lt;&lt; word &lt;&lt; " is not a valid word."; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T09:59:29.767", "Id": "391822", "Score": "1", "body": "The answer is exactly the same as the one to your other question. Since there is no difference in reading \"aaa...\" from left to right or right to left, it doesn't matter whethe...
[ { "body": "<p>As Konrad Rudolph points out in comments on the other question, this is probably about Pushdown Automata, for which the <a href=\"https://en.wikipedia.org/wiki/Pushdown_automaton#Example\" rel=\"nofollow noreferrer\">wikipedia page has some useful examples</a>, and this <a href=\"https://stackover...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T09:35:40.140", "Id": "203286", "Score": "0", "Tags": [ "c++", "parsing" ], "Title": "Match a simple balanced language using a queue" }
203286
<p>This program is supposed to find and slice any cell within a CSV file which contains more than a defined number of characters.</p> <p>The files can be pretty large, so being a beginner I would like to know if it is written correctly, and if I could make it more efficient. One of the lines is also more than 80 characters long, which bothers me.</p> <pre><code>import configparser, csv, sys if len(sys.argv) &lt; 3 : usage = """Usage: %s [inputfile][output file]\nThis program requires 2 \ arguments to function properly.\n[input file] is the file to clean\n[output fil\ e] is the name of the file that will be created as a result of this program\n""" print(usage % (sys.argv[0])) else : #reads the config file config = configparser.ConfigParser() config.read('csv_cleaner.ini') config = config['CONFIG'] encoding = config['character_encoding'] size = int(config['truncation_size']) #opens target file and creates the receiving one with open(sys.argv[1], 'r', newline='', encoding=encoding)as csv_file, \ open(sys.argv[2],'x', newline='', encoding=encoding)as output_file: #helps with parsing if config['detect_dialect'] : dialect = csv.Sniffer().sniff(csv_file.read(2048)) dialect.escapechar = '\\' #return to beginning of file csv_file.seek(0) #creates reader and writer reader = csv.reader(csv_file, dialect) dialect.delimiter = config['delimiter_in_output'] writer = csv.writer(output_file, dialect) #loops through file's lines for row in reader : #slices cells and loops through line's columns row=[col[:(size-2)]+(col[(size-2):]and'..')for col in row] #writes in new file writer.writerow(row) </code></pre> <p>This program uses a config file :</p> <pre><code>[CONFIG] character_encoding = UTF-8 delimiter_in_output = ; #set this option to False if the file is not recognized detect_dialect = True truncation_size = 255 </code></pre>
[]
[ { "body": "<p>The main improvement you can get is separating your concerns. Currently parsing the commandline, parsing the config file and actually truncating the columns is all mashed up together. Instead write short functions for each of these things:</p>\n\n<pre><code>import configparser\nimport csv\nimport ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T09:52:22.640", "Id": "203287", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "csv" ], "Title": "CSV file cell slicer" }
203287
<p>I have an ordered array of integer values: <em>10, 11, 12, 13, 15, 16, 19</em> and I need to write a dash between first and last consecutive values when there are more than two consecutive values (10-13). Between other values I need to write a comma and whitespace. Output for this input must be <em>10-13, 15, 16, 19</em>. I wrote a method that implements this:</p> <pre><code>class Program { private static string AddDashesBetweenConsecutiveNumbers(int[] orderedArray) { if (orderedArray.Length == 0 || orderedArray == null) { return string.Empty; } var groupedArray = orderedArray.Select((x, i) =&gt; new { Difference = i - x, Value = x }) .GroupBy(x =&gt; x.Difference) .Select(group =&gt; group.Select(a =&gt; a.Value)) .Select(arr =&gt; arr.Count() &gt; 2 ? $"{arr.First()}-{arr.Last()}" : string.Join(", ", arr)); return string.Join(", ", groupedArray); } static void Main(string[] args) { int[] array = { 10, 11, 12, 13, 15, 16, 19 }; Console.WriteLine(AddDashesBetweenConsecutiveNumbers(array)); // Output: "10-13, 15, 16, 19" } } </code></pre> <p>What I wrote seems to work, but this code has some disadvantages, especially in readability of the LINQ expression. So if you have any ideas how to improve this method or have better or alternative solution, that would be great to find out. </p>
[]
[ { "body": "<p>Sorry but no comments (yet) on the LINQ.</p>\n\n<p>Your first conditional has a logic error. You should be checking if <code>orderedArray</code> is null before you check if its length is 0.</p>\n\n<p>The method has a leap of faith that someone is inputting an array sorted in ascending order. The...
{ "AcceptedAnswerId": "203307", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T10:40:30.843", "Id": "203291", "Score": "5", "Tags": [ "c#", "linq", "interval" ], "Title": "Add dash between more than two consecutive numbers and comma between other numbers in array" }
203291
<p>The following is my attempt at creating a Boggle board solver in Ruby. It's not especially fast. I would love to have input on how the solution can either be sped up, or whether a different algorithm might be applied that is faster.</p> <p>The solution corresponds to my answer on a related question on the Math Stack Exchange site: <a href="https://math.stackexchange.com/a/2908479/30919">https://math.stackexchange.com/a/2908479/30919</a></p> <pre><code>require 'set' # List of words in a file, imported into sorted set for quick lookup: WORDS = SortedSet.new(open('wordlist.txt').readlines.map(&amp;:chomp)) # Possible directions from a space and their x/y deltas: DIRS = { n: [0, -1], ne: [1, -1], e: [1, 0], se: [1, 1], s: [0, 1], sw: [-1, 1], w: [-1, 0], nw: [-1, -1] }.freeze # Note on "Qu" -- "Qu" should require special handling in the # Sample board we want to solve; we could create a random board with # the known configuration of the cubes. # For 'Qu' on the Boggle board, only 'Q' is entered in @board, because the traversion routine # has special handling for 'Q' by adding a 'U' each time @board = [ %w[ N P E R ], %w[ P L R O ], %w[ I U N T ], %w[ J E G V ] ] # This method determines the next position based on the currend position # and direction. If the position is out of bounds, it returns nil def next_pos(position, direction) npos = [ position[0] + DIRS[direction][0], position[1] + DIRS[direction][1] ] return nil if (npos[0] &lt; 0) || (npos[1] &lt; 0) || (npos[0] &gt; 3) || (npos[1] &gt; 3) npos end @stack = [] # Stack containing the positions traversed # NB: **The letters have their own stack due to the special handling of "Qu"** @letters = [] # Corresponding letters from the positions in stack @found_words = SortedSet.new # Words found def traverse(cpos) # Nested method that handles popping of stack with special 'Qu' handling (because it's used more than once) def pop_stack @stack.pop @letters.pop # Special handling for "Qu": @letters.pop if @letters.last == "Q" end #The longest words in my list are 15 letters - omit this check if you have more return if @stack.length == 15 # Push current position and letters collected so far on the respective stacks @stack &lt;&lt; cpos @letters &lt;&lt; @board[cpos[0]][cpos[1]] # Special handling for Qu: @letters &lt;&lt; "U" if @letters.last == "Q" # From 2 letters onwards, check whether this path is worth pursuing if @stack.length &gt;= 2 unless WORDS.grep(/^#{@letters.join}/).any? pop_stack return end end # From 3 letters onwards, check if the word is in the dictionary if @stack.length &gt;= 3 word = @letters.join if WORDS.include?(word) @found_words &lt;&lt; word end end # Try each direction in succession from the current position DIRS.keys.each do |dir| npos = next_pos(cpos, dir) # Calculate next pos from current pos next unless npos # Check it is not out of bounds # Check whether the new position had been visited in current stack visited = false @stack.reverse_each do |pos| if pos == npos visited = true break end end next if visited # Skip the new position if it had been visited traverse(npos) # Start looking from next position end # Take the last position/letter off the stack before returning pop_stack end # Traverse from every square on the board 4.times.map do |x| 4.times.map do |y| traverse([x, y]) end end puts @found_words.sort </code></pre>
[]
[ { "body": "<p>I can't comment on Ruby style, but there are a couple of algorithmic points which don't need Ruby knowledge to identify.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if @stack.length &gt;= 2\n unless WORDS.grep(/^#{@letters.join}/).any?\n pop_stack\n return\n end\n end\n</code></pre>...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T10:41:15.227", "Id": "203292", "Score": "4", "Tags": [ "algorithm", "ruby" ], "Title": "Boggle board solver in Ruby" }
203292
<p>I created a function that generates all the combinations of 1 digit, 2 equal letters and 2 different letters. </p> <p>I reduced the numbers and letters to make it more easy to calculate: </p> <pre><code>letters = "bcdfghjklmnpqrstvwxz" digits = "2456789" </code></pre> <p>There are 1,436,400 possibilities because $${5\choose1}{7\choose1}{4\choose2}{20\choose1}·19·18 = 1,436,400$$ where</p> <p>\${5\choose1}{7\choose1}\$ — Choosing place for one number and choosing the number<br> \${4\choose2}{20\choose1}\$ — Choosing 2 places for the equal letter and choosing the letter<br> \$19·18\$ — Permutations of the rest of the letters </p> <p>Example for <strong>CORRECT</strong> combinations: </p> <pre><code>1abac 1aabd c8ldc </code></pre> <p>Example for <strong>INCORRECT</strong> combinations: </p> <pre><code>1aaaa -&gt; incorrect because there are more than 2 equal letters 1aaab -&gt; Same as the previous 1abcd -&gt; No 2 equal letters </code></pre> <p>I wrote the following code</p> <pre><code>from itertools import permutations, combinations import time # Generate 1 digit, 2 equal letters and 2 different letters def generate_1_digit_2_equal_letters_2_different_letters(): alpha = "bcdfghjklmnpqrstvwxz" digits = "2456789" places = '01234' s = ['-', '-', '-', '-', '-'] combos = [] # Choosing a place for 1 digit for dig_indx in range(0, 5): # Choosing a digit for digit in digits: s[dig_indx] = digit # Creating equal letter indxes new_places = places.replace(str(dig_indx), '') # We are using 'combinations' because 'bb' on indexes 1,2 is the same as 2,1 equal_letter_indxs = combinations(new_places, 2) equal_letter_indxs2 = [] for x in equal_letter_indxs: equal_letter_indxs2.append(''.join(x)) # Choosing the equal letter for equal_letter in alpha: # Choosing a two places for the equal letter for i in equal_letter_indxs2: if int(i[0]) != dig_indx and int(i[1]) != dig_indx: s[int(i[0])] = equal_letter s[int(i[1])] = equal_letter # Creating the rest of the letters places two_places = places.replace(str(dig_indx), '') two_places = two_places.replace(i[0], '') two_places = two_places.replace(i[1], '') all_places_combo = permutations(two_places, 2) # Choosing the places for the two other letters for two_places in all_places_combo: letter1_history = {} # Choosing the first letter the different from all the other for letter1 in alpha: if letter1 != equal_letter: letter1_history[letter1] = letter1 # Choosing the second letter that different from all the other for letter2 in alpha: if letter2 != equal_letter and letter2 != letter1: found = False for k in letter1_history.keys(): if letter2 == k: found = True if not found: s[int(two_places[0])] = letter1 s[int(two_places[1])] = letter2 #print(''.join(s)) combos.append(''.join(s)) return combos # Should be 1,436,400 start_time = time.time() print(len(generate_1_digit_2_equal_letters_2_different_letters())) print("--- %s seconds ---" % (time.time() - start_time)) </code></pre> <p>This is not efficient because when calculating it:</p> <pre><code>for dig_indx in range(0, 5) =&gt; 5 times for digit in digits =&gt; 7 times for x in equal_letter_indxs =&gt; 2 times for equal_letter in alpha =&gt; 20 times for i in equal_letter_indxs2 =&gt; 2 times for two_places in all_places_combo =&gt; 2 times for letter1 in alpha =&gt; 20 times for letter2 in alpha =&gt; 20 times for k in letter1_history.keys() =&gt; 20 times in worst case 5*7*(2+20*2*2*20*20*20 = ~640,002 iterations </code></pre> <p>It works, but I though maybe you have suggestions how to make it more efficient. Feel free to make changes in my code or create a new better code, I will be glad to see different approachs (maybe recursion ? ) </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T11:03:50.997", "Id": "391827", "Score": "0", "body": "Why are `0, 1, 3` not included as numbers? And why are some letters missing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T11:17:32.337", "I...
[ { "body": "<p>The main thing that I see when I look at your code is that it's too complicated. You have one big function, and I won't even count the amount of nested loops you have.</p>\n\n<p>The first thing I'd do is to simplify this, and split it into separate functions. The second thing I'd to is to improve ...
{ "AcceptedAnswerId": "203297", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T10:56:26.390", "Id": "203294", "Score": "2", "Tags": [ "python", "mathematics", "combinatorics" ], "Title": "Generating all permutations of 1 digit, 2 equal letters and 2 different letters efficiently" }
203294
<p>I've implemented a console ToDo application. I would like to hear some opinions about it, what should I change etc.</p> <p><strong>About project:</strong></p> <p>It is intended to manage everyday tasks. Application contains:</p> <ul> <li>adding users to database </li> <li>adding tasks to database </li> <li>getting list of user's tasks</li> </ul> <p>It's my second project in which I use <code>mockito</code>, <code>lombok</code>, <code>junit</code>, <code>slf4j</code>. I tried to use MVC pattern. I've written unit tests for my controller, too.</p> <p>Let's start from package <strong>MODEL</strong> (there is nothing interesting, but I want to add every class). <strong>User class</strong> (model)</p> <pre><code>package model; import lombok.*; @RequiredArgsConstructor @Getter @Setter @EqualsAndHashCode public class User { private final String name; private final String password; private int ID; } </code></pre> <p><strong>Task class</strong> (model)</p> <pre><code>package model; import lombok.*; @Getter @Setter @AllArgsConstructor @ToString @NoArgsConstructor @EqualsAndHashCode public class Task { private String taskName; } </code></pre> <p>Here is my <strong>VIEW</strong> package:</p> <p><strong>ToDoView</strong> class(view)</p> <pre><code>package view; import controller.ToDoEngine; import model.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.InputMismatchException; import java.util.List; import java.util.Scanner; public class ToDoView { private static final int LOGIN = 1; private static final int REGISTER = 2; private Logger logger; private ToDoEngine toDoEngine; private Scanner input; private int option; public ToDoView(ToDoEngine toDoEngine) { this.toDoEngine = toDoEngine; logger = LoggerFactory.getLogger(ToDoView.class); input = new Scanner(System.in); } public void executeMainMenu() { logger.info("--MAIN MENU--"); logger.info("1. Sign in"); logger.info("2. Sign up"); boolean isInvalid = true; while (isInvalid) { try { option = input.nextInt(); if (option == 1 || option == 2) { isInvalid = false; switch (option) { case LOGIN: executeLoginCase(); break; case REGISTER: executeRegistrationCase(); break; } } } catch (InputMismatchException e) { logger.error("Try again"); input.next(); } catch (SQLException e) { e.printStackTrace(); } } } private void executeLoginCase() throws SQLException { String username, password; boolean isInvalid = true; do { logger.info("Put your username and password"); logger.info("User: "); username = input.next(); logger.info("Password: "); password = input.next(); if (toDoEngine.signIn(username, password)) { logger.info("You've logged in"); executeUserCase(); isInvalid = false; } else logger.info("Bad login or password, try again"); } while (isInvalid); } private void executeRegistrationCase() throws SQLException { String username, password; logger.info("Put your username and password"); logger.info("User: "); username = input.next(); logger.info("Password: "); password = input.next(); if (toDoEngine.createUser(username, password)) logger.info("User created successfully, now you can sign in!"); } private void executeUserCase() throws SQLException { do { logger.info("1. Add task"); logger.info("2. Remove task"); logger.info("3. Get all tasks"); logger.info("4. Quit"); option = input.nextInt(); executeUserOptions(option); } while (option != 4); } private void executeUserOptions(int option) throws SQLException { switch (option) { case 1: logger.info("Input task"); String taskName = input.next(); toDoEngine.addTask(taskName); break; case 2: logger.info("Input task"); taskName = input.next(); toDoEngine.deleteTask(taskName); break; case 3: List&lt;Task&gt; tasks = toDoEngine.getTasks(); for (Task task : tasks) logger.info(String.valueOf(task)); break; } } } </code></pre> <p><strong>Controller package</strong></p> <p><strong>ToDoEngine class</strong> (controller)</p> <pre><code>package controller; import model.Task; import model.User; import repository.TaskActions; import repository.UserActions; import java.sql.SQLException; import java.util.List; public class ToDoEngine { private TaskActions taskActions; private UserActions userActions; private User connectedUser; public ToDoEngine(UserActions userStorage, TaskActions taskStorage) { this.taskActions = taskStorage; this.userActions = userStorage; } public boolean signIn(String username, String password) throws SQLException { connectedUser = new User(username, password); if (!userActions.signIn(connectedUser)) { return false; } connectedUser.setID(retrieveConnectedUserID(connectedUser)); return true; } private int retrieveConnectedUserID(User connectedUser) throws SQLException { return userActions.retrieveUserID(connectedUser); } public boolean createUser(String username, String password) throws SQLException { return userActions.createUser(new User(username, password)); } public void addTask(String taskName) throws SQLException { taskActions.addTask(new Task(taskName), connectedUser); } public void deleteTask(String taskName) throws SQLException { taskActions.deleteTask(new Task(taskName), connectedUser); } public List&lt;Task&gt; getTasks() throws SQLException { return taskActions.getTasks(connectedUser); } } </code></pre> <p><strong>Repository</strong> package. I created 2 interfaces - UserActions and TaskActions. That's beacuse I wanted to have everything organized. (I'm not gonna paste interfaces. Just classes that implement them)</p> <p><strong>TaskRepository class</strong> (repository)</p> <pre><code>package repository; import model.Task; import model.User; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; public class TaskRepository implements TaskActions { private Connection connection; public TaskRepository() throws SQLException { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/todoapp?autoReconnect=true&amp;serverTimezone=" + TimeZone.getDefault().getID(), "root", "password"); } public boolean addTask(Task task, User user) throws SQLException { if (task == null) return false; PreparedStatement preparedStatement = connection.prepareStatement("INSERT into tasks (task,idUser) values (?,?) "); preparedStatement.setString(1, task.getTaskName()); preparedStatement.setInt(2, user.getID()); preparedStatement.executeUpdate(); return true; } public boolean deleteTask(Task task, User user) throws SQLException { if (!doesTaskExists(task)) return false; PreparedStatement preparedStatement = connection.prepareStatement("DELETE from tasks WHERE idUser=? AND task=?"); preparedStatement.setInt(1, user.getID()); preparedStatement.setString(2, task.getTaskName()); preparedStatement.executeUpdate(); return true; } public List&lt;Task&gt; getTasks(User connectedUser) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM tasks where idUser=?"); preparedStatement.setInt(1, connectedUser.getID()); ResultSet result = preparedStatement.executeQuery(); List&lt;Task&gt; tasks = new ArrayList&lt;Task&gt;(); while (result.next()) { Task task = new Task(); task.setTaskName(result.getString("task")); tasks.add(task); } return tasks; } public boolean doesTaskExists(Task task) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("SELECT task FROM tasks WHERE task=?"); preparedStatement.setString(1, task.getTaskName()); ResultSet result = preparedStatement.executeQuery(); return result.next(); } } </code></pre> <p><strong>UserRepository</strong> (repository)</p> <pre><code>package repository; import model.User; import java.sql.*; import java.util.TimeZone; public class UserRepository implements UserActions { private Connection connection; public UserRepository() throws SQLException { connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/todoapp?autoReconnect=true&amp;serverTimezone=" + TimeZone.getDefault().getID(), "root", "password"); } public boolean createUser(User user) throws SQLException { if (doesUserWithThatUsernameExist(user)) return false; PreparedStatement preparedStatement = connection.prepareStatement("INSERT into user (username,password) values (?,?)"); preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getPassword()); preparedStatement.executeUpdate(); return true; } public boolean signIn(User user) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("SELECT COUNT(username) FROM user WHERE username=? AND password=? LIMIT 0,1"); preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getPassword()); ResultSet result = preparedStatement.executeQuery(); int count = 0; if (result.next()) count = result.getInt(1); return count &gt;= 1; } public int retrieveUserID(User user) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("SELECT id FROM user WHERE username=? AND password=?"); preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getPassword()); ResultSet result = preparedStatement.executeQuery(); if (result.next()) user.setID(result.getInt("id")); return user.getID(); } private boolean doesUserWithThatUsernameExist(User user) throws SQLException { PreparedStatement preparedStatement = connection.prepareStatement("SELECT username FROM user WHERE username=?"); preparedStatement.setString(1, user.getName().toUpperCase()); ResultSet result = preparedStatement.executeQuery(); return result.next(); } } </code></pre> <p><strong>Main class:</strong></p> <pre><code>import controller.ToDoEngine; import repository.TaskRepository; import repository.UserRepository; import view.ToDoView; import java.sql.SQLException; public class Main { public static void main(String[] args) throws SQLException { UserRepository userRepository = new UserRepository(); TaskRepository taskRepository = new TaskRepository(); ToDoEngine toDoEngine = new ToDoEngine(userRepository,taskRepository); ToDoView toDoView = new ToDoView(toDoEngine); toDoView.executeMainMenu(); } } </code></pre> <p>Here are my <strong>unit tests</strong>:</p> <pre><code>package controller; import model.Task; import model.User; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import repository.TaskActions; import repository.UserActions; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ToDoEngineTest { @Mock TaskActions taskActionsMock; @Mock UserActions userActionsMock; private ToDoEngine toDoEngine; @Before public void setup() { MockitoAnnotations.initMocks(this); toDoEngine = new ToDoEngine(userActionsMock, taskActionsMock); } @Test public void createUser() throws SQLException { User user = new User("admin", "123"); toDoEngine.createUser("admin", "123"); verify(userActionsMock).createUser(user); } @Test public void getTasks() throws SQLException { List&lt;Task&gt; tasks = new ArrayList&lt;&gt;(); User user = new User("admin", "123"); Task task = new Task("wash"); tasks.add(task); when(taskActionsMock.getTasks((User) any())).thenReturn(tasks); List&lt;Task&gt; actual = toDoEngine.getTasks(); List&lt;Task&gt; expected = taskActionsMock.getTasks(user); assertEquals(expected, actual); } @Test public void signIn() { // TODO: 2018-09-06 } @Test public void addTask() throws SQLException { toDoEngine.signIn("admin", "123"); Task taskName = new Task("wash"); User user = new User("admin", "123"); verify(userActionsMock).signIn(user); toDoEngine.addTask("wash"); verify(taskActionsMock).addTask(taskName, user); } @Test public void deleteTask() throws SQLException { toDoEngine.signIn("admin", "123"); Task taskName = new Task("wash"); User user = new User("admin", "123"); verify(userActionsMock).signIn(user); toDoEngine.deleteTask("wash"); verify(taskActionsMock).deleteTask(taskName, user); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T13:02:56.523", "Id": "391853", "Score": "0", "body": "Welcome to Code Review! Does it currently work as intended?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T13:16:43.187", "Id": "391859", ...
[ { "body": "<p>Globally, it works. I have to admit that I am a bit skeptic on your usage of \na logger. Because a logger is dedicated to log, some can be asynchronous or \nuse a buffer or are just disabled. Why don't you use the <code>System.out</code> ?</p>\n\n<p>You have some tests and is a good thing. Sadly, ...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T12:02:57.250", "Id": "203299", "Score": "3", "Tags": [ "java", "sql", "mvc", "to-do-list", "lombok" ], "Title": "ToDoApp - adding users, managing tasks, getting tasks" }
203299
<p>I am trying to solve a programming challange that involves converting reverse polish notation to infix notation. For example: 1 3 + 2 4 5 - + / would be: ((1+3)/(2+(4-5))) My solution so far does work, but it's not fast enough. So I am looking for any optimization advice.</p> <pre><code>public class betteralgo { public static void main(String[] args) throws IOException { BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); String line = bi.readLine(); String[] input = line.split(" "); StringBuilder builder = new StringBuilder(); Stack&lt;String&gt; stack = new Stack&lt;String&gt;(); for(String e:input) { switch(e){ case("+"): case("-"): case("*"): case("/"): String i = stack.pop(); String k = stack.pop(); stack.push("(" + k + e + i + ")"); break; default: stack.push(e); } } System.out.println(stack.pop()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T12:52:20.640", "Id": "391848", "Score": "5", "body": "*\"it's not fast enough\"* – for which input? How long does it take? Is there a concrete time limit that you need to achieve?" } ]
[ { "body": "<p>If you want to do it faster I know that I once solved this with a hashMap which is much faster. The problem is that, depending on what you are going to use it for, it's harder to implement. I don't have time to show exactly how I did it now, I might come back to you, but it should give you a point...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T12:12:24.167", "Id": "203301", "Score": "5", "Tags": [ "java", "performance", "algorithm", "math-expression-eval" ], "Title": "Converting Reverse Polish to Infix Notation in Java" }
203301
<p>I am solving another <a href="https://leetcode.com/problems/subsets/description/" rel="noreferrer">problem in leetcode</a>.</p> <blockquote> <p>Given a set, generate all the subsets of the set.</p> <p>Input: <code>[1,2,3]</code><br> Output: <code>[ [3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]]</code></p> </blockquote> <p>The solution is accepted but I would like to improve on my C coding style. I have created a <code>node_t</code> type to encapsulate the data related each subset. There could be less verbose ways to do this. Two popular methods of solving this problem seem to be:</p> <ol> <li>backtracking</li> <li>a subset equals to binary number ≤ n where n is element count.</li> </ol> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; typedef struct node_s { int *array; int size; struct node_s *next; } node_t; node_t* alloc_node() { return (node_t*)malloc(sizeof(node_t)); } void free_node(node_t *node) { free(node); } #define SIZE 3 void print_one(int *one) { printf("%d ", *one); } void print_1d_array(int *array, int size) { for(int i = 0; i &lt; size; i++) { print_one(&amp;array[i]); } printf("\n"); } void print_2d_array(int **array, int *col_sizes, int size) { for (int i = 0; i &lt; size; i++) { print_1d_array(array[i], col_sizes[i]); } } int** create_solution_array(node_t *head, int ans_size, int **column_sizes) { int **ans = (int**)malloc(sizeof(int*)*ans_size); node_t *iter; iter = head-&gt;next; int idx = 0; while(iter) { ans[idx] = iter-&gt;array; (*column_sizes)[idx] = iter-&gt;size; idx++; iter = iter-&gt;next; } return ans; } void gen_powerset(int *num, int num_size, int idx, int cur_size, int *cur, node_t **iter_node, int *ans_size) { if (idx == num_size) { node_t *new_node = alloc_node(); if (cur_size) { new_node-&gt;array = (int *) malloc(sizeof(int) * cur_size); new_node-&gt;size = cur_size ; memcpy(new_node-&gt;array, cur, cur_size*sizeof(int)); } (*iter_node)-&gt;next = new_node; *iter_node = new_node; (*ans_size)++; return; } gen_powerset(num, num_size, idx + 1, cur_size, cur, iter_node, ans_size); *(cur + cur_size) = num[idx]; gen_powerset(num, num_size, idx + 1, cur_size + 1, cur, iter_node, ans_size); } int** subsets(int* nums, int numsSize, int** columnSizes, int* returnSize) { node_t *head = alloc_node(); node_t *iter = head; int *cur = (int*)malloc(sizeof(int)*numsSize); gen_powerset(nums, numsSize, 0, 0, cur, &amp;iter, returnSize); return create_solution_array(head, *returnSize, columnSizes); } int main () { int *nums = (int*)malloc(sizeof(int)*SIZE); for (int i = 0; i &lt; SIZE; i++) { nums[i] = i+1; } int *col_sizes = (int*)malloc(sizeof(int)*SIZE); int ans_size; int ** ans = subsets(nums, SIZE, &amp;col_sizes, &amp;ans_size); print_2d_array(ans, col_sizes, ans_size); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T13:25:17.800", "Id": "391862", "Score": "0", "body": "@Toby Speight Added problem description." } ]
[ { "body": "<p>I'll just work through this from the top:</p>\n\n<blockquote>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n</code></pre>\n</blockquote>\n\n<p>Looks good; we need these.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>typedef struct node_s {\n int *array;\n...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T12:53:51.807", "Id": "203305", "Score": "10", "Tags": [ "c", "programming-challenge", "combinatorics", "depth-first-search" ], "Title": "Generating the powerset in C" }
203305
<p>My requirement is, I need to load the existing xml file from the given path by passing through command line arguments and need to update the xml file from C# code. First time I am working on the C# project. I have done given requirement but need few clarifications and optimization techniques in my code snippet.</p> <pre><code>namespace SchemaChange { class FragmentUpdate { private String fragmentFileRU; private String fragmentFileES; private XmlDocument docRU; private XmlDocument docES; private String fileRU; private String fileES; public FragmentUpdate(String filename) { string result = Path.GetFileName(filename); fileRU = "PCPE_FRAGMENT_RU.wxs"; fileES = "PCPE_FRAGMENT_ES.wxs"; if (result == fileRU.Trim()) { fragmentFileRU = filename; docRU = new XmlDocument(); docRU.Load(fragmentFileRU); UpdateFragmentRU(); } else if (result == fileES.Trim()) { fragmentFileES = filename; docES = new XmlDocument(); docES.Load(fragmentFileES); UpdateFragmentES(); } } private void UpdateFragmentRU() { string nameSpace = "http://wixtoolset.org/schemas/v4/wxs"; //Getting document root Element XmlElement rootElement = docRU.DocumentElement; rootElement.SetAttribute("xmlns", nameSpace); XmlElement FragmentElement = (XmlElement)rootElement.GetElementsByTagName("Fragment")[0]; XmlElement dirRefElement = (XmlElement)FragmentElement.GetElementsByTagName("DirectoryRef")[0]; XmlElement compElement = (XmlElement)dirRefElement.GetElementsByTagName("Component")[0]; XmlNodeList fileNodeList = compElement.GetElementsByTagName("File"); int count = fileNodeList.Count; //iterating through the count of nodes for (int i = 0; i &lt; count; i++) { XmlElement fileElement = (XmlElement)fileNodeList[i]; String srcString = fileElement.GetAttribute("src"); if (srcString != "") { //Storing value of src attribute in source attribute fileElement.SetAttribute("Source", srcString); fileElement.RemoveAttribute("src"); } } //Saving the document docRU.Save(fragmentFileRU); } private void UpdateFragmentES() { string nameSpace = "http://wixtoolset.org/schemas/v4/wxs"; XmlElement rootElement = docES.DocumentElement; rootElement.SetAttribute("xmlns", nameSpace); XmlElement FragmentElement = (XmlElement)rootElement.GetElementsByTagName("Fragment")[0]; XmlElement dirRefElement = (XmlElement)FragmentElement.GetElementsByTagName("DirectoryRef")[0]; XmlElement compElement = (XmlElement)dirRefElement.GetElementsByTagName("Component")[0]; XmlNodeList fileNodeList = compElement.GetElementsByTagName("File"); int count = fileNodeList.Count; for (int i = 0; i &lt; count; i++) { //Getting the File element XmlElement fileElement = (XmlElement)fileNodeList[i]; String srcString = fileElement.GetAttribute("src"); if (srcString != "") { //Storing value of src attribute in source attribute fileElement.SetAttribute("Source", srcString); //removing src attribute fileElement.RemoveAttribute("src"); } } //Saving the document docES.Save(fragmentFileES); } static void Main(string[] args) { if (!(args.Length == 0)) { foreach (string arg in args) { FragmentUpdate fragmentUpdate = new FragmentUpdate(arg); } } } } </code></pre> <p>I am passing multiple arguments from the command line. So from the Main() function for each argument I am calling the constructor. Is it the right approach to call the constructor for each command line argument?</p> <p>From the constructor I am calling the functions (<code>UpdateFragmentRU();</code> and <code>UpdateFragmentES();</code>). Is it the correct approach or can I call these functions from the Main() function.</p> <p>Any optimization required in the body of the functions <code>UpdateFragmentRU()</code> and <code>UpdateFragmentES()</code>.</p> <p>Can I combine these two functions and optimize?</p> <p>Please provide your thoughts and suggestions and help my beginning in C#.</p>
[]
[ { "body": "<p>With your example there is almost no difference between the two fragments other than the passed in file name format. However I suspect you want varying behavior between the two <code>Fragment</code> types. You could implement an adapter styled pattern like this:</p>\n\n<pre><code>public abstract...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T17:21:53.677", "Id": "203311", "Score": "3", "Tags": [ "c#", "beginner", "xml", "constructor" ], "Title": "Load and update XML inside the constructor" }
203311
<p>I have the following radix sort implementation:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;cstddef&gt; #include &lt;algorithm&gt; void radix_sort(std::vector&lt;int&gt;&amp; arr) { int radix = 1; // Largest element in unsorted array int max = *(std::max_element(arr.begin(), arr.end())); while(max / radix) { // Buckets used for sorting. Each bucket representing a digit. std::vector&lt;std::vector&lt;int&gt;&gt; buckets(10, std::vector&lt;int&gt;()); for(const auto&amp; num : arr) { int digit = num / radix % 10; buckets[digit].push_back(num); } std::size_t k = 0; // Take the elements out of buckets into the array for(std::size_t i = 0; i &lt; 10; i++) { for(std::size_t j = 0; j &lt; buckets[i].size(); j++) { arr[k] = buckets[i][j]; k++; } } // Change the place of digit used for sorting radix *= 10; } } // Function to print array void print_arr(std::vector&lt;int&gt;&amp; arr) { for(auto elem : arr) { std::cout &lt;&lt; elem &lt;&lt; "\t"; } std::cout &lt;&lt; "\n"; } int main() { std::vector&lt;int&gt; arr; std::string s; std::cout &lt;&lt; "Enter the elements: " &lt;&lt; std::endl; std::getline(std::cin, s); std::istringstream ss(s); int val; while(ss &gt;&gt; val) { arr.push_back(val); } std::cout &lt;&lt; "Before sorting: \n"; print_arr(arr); radix_sort(arr); std::cout &lt;&lt; "After sorting: \n"; print_arr(arr); return 0; } </code></pre> <p>I pass an array to the <code>radix_sort</code> function. It uses a variable called <code>radix</code> to identify the digit in a particular place (unit, ten, hundred etc.) in the number. Based on this digit, we sort elements into buckets. Once this sorting is done, the elements are taken out based on the order of bucket (The elements in zeroth bucket comes out first, followed by those in first bucket, second bucket and so on). This is repeated until all the digits in the largest element are visited.</p> <p>1) I would like to know if there is a better data structure for buckets?</p> <p>2) Is there a more efficient method to find largest element in the unsorted array?</p> <p>3) If possible, please provide an overall review of the code.</p>
[]
[ { "body": "<p>A vector is usually the best data structure to use unless you have a compelling reason to use something else. Since you know how many buckets you need, one slight improvement you can make to your buckets is to use an array of vectors, rather than a vector of vectors:</p>\n\n<pre><code>std::array&...
{ "AcceptedAnswerId": "203318", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T18:09:34.900", "Id": "203314", "Score": "1", "Tags": [ "c++", "sorting", "vectors", "radix-sort" ], "Title": "C++ - Radix sort implementation" }
203314
<p>Graph Coloring Algorithm (Greedy/ Welsh Powell)</p> <p>I am trying to learn graphs, and I couldn't find a Python implementation of the Welsh Powell algorithm online, so I tried to write my own. Here are the steps.</p> <ol> <li>Order the nodes in descending degree. (Most neighbors ... Least neighbors)</li> <li>For each node, check the colors of neighbor nodes and mark them as unavailable.</li> <li>Choose the lowest available color. (from [0, 1, 2, ..., len(graph) -1])</li> </ol> <hr> <pre><code>def color_nodes(graph): # Order nodes in descending degree nodes = sorted(list(graph.keys()), key=lambda x: len(graph[x]), reverse=True) color_map = {} for node in nodes: available_colors = [True] * len(nodes) for neighbor in graph[node]: if neighbor in color_map: color = color_map[neighbor] available_colors[color] = False for color, available in enumerate(available_colors): if available: color_map[node] = color break return color_map if __name__ == '__main__': graph = { 'a': list('bcd'), 'b': list('ac'), 'c': list('abdef'), 'd': list('ace'), 'e': list('cdf'), 'f': list('ce') } print(color_nodes(graph)) # {'c': 0, 'a': 1, 'd': 2, 'e': 1, 'b': 2, 'f': 2} </code></pre> <p><img src="https://i.imgur.com/OKDr9I5.jpg" alt="example"></p> <p>For the input graph, it produced the above result. Is the implementation correct?</p>
[]
[ { "body": "<p>PEP 8, the official Python style guide, says that <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"noreferrer\">indentation should be 4 spaces per level</a>. Since whitespace is significant in Python, that is a pretty strong convention.</p>\n\n<p>The implementation could be...
{ "AcceptedAnswerId": "203328", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T21:42:42.220", "Id": "203319", "Score": "5", "Tags": [ "python", "algorithm", "graph" ], "Title": "Greedy Graph Coloring in Python" }
203319
<p>I'm relatively new to PHP and one of the things I miss from other languages are enums. After looking around for some samples on how can I have somewhat similar to them, I came up with this implementation. I want to know how good is it, how can it be improved or any other flaws you can find in it. It's writen in PHP 7.</p> <h3>Base class</h3> <pre><code>abstract class BaseEnum { private $value; protected function __construct(string $value) { $this-&gt;value = $value; } public function getValue(): string { return $this-&gt;value; } public abstract static function parse(?string $value); public abstract static function InitializeEnums(); } </code></pre> <p>This is the base class from where all my &quot;enums&quot; inherit. In short this is an immutable class that hold a single string value and a getter for it (internally all enums will be string, opposed to other languages that are often ints). There is an abstract method that takes a raw string and returns the matching enum instance that needs to be implemented in a case-by-case basis, as well as an initialization method (see below for this).</p> <h3>Concrete enum class</h3> <pre><code>class VoucherType extends BaseEnum { private static $invoice; private static $creditNote; private static $advance; public static function InitializeEnums() { VoucherType::$invoice = new VoucherType(&quot;I&quot;); VoucherType::$creditNote = new VoucherType(&quot;C&quot;); VoucherType::$advance = new VoucherType(&quot;A&quot;); } public static function parse(?string $value): ?self { if($value === VoucherType::$invoice-&gt;getValue()) return VoucherType::$invoice; if($value === VoucherType::$creditNote-&gt;getValue()) return VoucherType::$creditNote; if($value === VoucherType::$advance-&gt;getValue()) return VoucherType::$advance; return null; } public static function invoice(): self { return VoucherType::$invoice; } public static function creditNote(): self { return VoucherType::$creditNote; } public static function advance(): self { return VoucherType::$advance; } } VoucherType::InitializeEnums(); </code></pre> <p>This is one of my real enum classes. All that it does is to provide the fixed valid values and appropriate getters for each one. Also implements the parse that looks each value in turn. It stores singletons of each possible value and those are returned as needed. The initialization of the singletons is done via the <code>InitializeEnums</code> method, which is called outside the class (a dirty trick to simulate a static constructor).</p> <p>This enables to make simple comparisons with &quot;constant&quot; values like <code>$var == VoucherType::invoice()</code>, or to convert to/from string with appropriate invalid values handling (and replaced with nulls). Variables will always be from this class type (and not simple strings) and assignment/comparision works as expected.</p> <p>How can I improve it and what's good, bad or should change about it?</p>
[]
[ { "body": "<p>I would simulate the enum using class constants.</p>\n\n<pre><code>class VoucherType {\n const INVOICE = 0;\n const CREDIT_NOTE = 1;\n const ADVANCE = 2;\n}\n\n$myType = VoucherType::INVOICE;\n</code></pre>\n\n<p>They are accesible from everywhere you can access the class, virtually everywhere ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T22:04:01.663", "Id": "203321", "Score": "4", "Tags": [ "php", "enum" ], "Title": "PHP class that behaves like enums" }
203321
<p>For programming practice, I created a chess program in PHP (my most comfortable language).</p> <p>The program reads a FEN (a string with the location of all the pieces on the board) from the URL, generates a board, then generates all the legal moves for that position. Then when you click the move, it loads the same file but with a new <code>?fen=</code> in the URL.</p> <p>The legal moves list code is 100% complete. It handles all special cases, including pawn promotion, en passant, castling, not allowing moves that place/keep your own king in check, etc.</p> <p>Moves can be made by double clicking on the move, hitting "Make A Move", or drag and dropping a piece on the board.</p> <p>I am hoping for feedback/advice to help me make the following improvements to the code:</p> <ul> <li>PHP Refactoring - Make the PHP code more readable / more organized / use classes better.</li> <li>PHP Performance - Speed up the PHP code. Complex positions with lots of moves are taking 1500ms to render. This speed is acceptable for a browser based game, but would be way too slow if I wanted to turn this code into a chess engine (chess A.I.)</li> </ul> <p>Humble beginnings: Version 1 of the program can be found <a href="https://codereview.stackexchange.com/questions/201557/php-chess-part-1-ascii-board-import-position">here</a>.</p> <h1>Website</h1> <p><a href="http://admiraladama.dreamhosters.com/PHPChess" rel="nofollow noreferrer">http://admiraladama.dreamhosters.com/PHPChess</a></p> <h1>Screenshot</h1> <p><a href="https://i.stack.imgur.com/eQIsi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eQIsi.png" alt="Screenshot"></a></p> <h1>index.php</h1> <pre><code>&lt;?php $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $start = $time; error_reporting(-1); ini_set('display_errors', 'On'); require_once('ChessGame.php'); require_once('ChessBoard.php'); require_once('ChessPiece.php'); require_once('ChessMove.php'); require_once('ChessSquare.php'); require_once('Dictionary.php'); $game = new ChessGame(); if ( isset($_GET['reset']) ) { // Skip this conditional. ChessGame's FEN is the default, new game FEN and doesn't need to be set again. } elseif ( isset($_GET['move']) ) { $game-&gt;board-&gt;set_fen($_GET['move']); } elseif ( isset($_GET['fen']) ) { $game-&gt;board-&gt;set_fen($_GET['fen']); } $fen = $game-&gt;board-&gt;get_fen(); $side_to_move = $game-&gt;board-&gt;get_side_to_move_string(); $who_is_winning = $game-&gt;board-&gt;get_who_is_winning_string(); $graphical_board_array = $game-&gt;board-&gt;get_graphical_board(); $legal_moves = $game-&gt;get_legal_moves_list($game-&gt;board-&gt;color_to_move, $game-&gt;board); require_once('view.php'); </code></pre> <h1>ChessGame.php</h1> <pre><code>&lt;?php class ChessGame { var $board; function __construct($fen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1') { $this-&gt;board = new ChessBoard($fen); } function __clone() { $this-&gt;board = clone $this-&gt;board; if ( $this-&gt;move_list ) { $array = array(); foreach ( $this-&gt;move_list as $key =&gt; $move ) { array_push($array, clone $move); } $this-&gt;move_list = $array; } } function get_legal_moves_list( $color_to_move, $board, $eliminate_king_in_check_moves = TRUE ) { $pieces_to_check = $this-&gt;get_all_pieces_by_color($color_to_move, $board); $moves = array(); // TODO: Is player to move checkmated? // Is enemy checkmated? // If so, return NULL since there are no legal moves. The game is over! // Else you will get a weird list of legal moves including moves capturing the enemy king. foreach ( $pieces_to_check as $key =&gt; $piece ) { if ( $piece-&gt;type == 'pawn' ) { if ( $piece-&gt;color == 'white' ) { $directions_list = array('north'); if ( $piece-&gt;on_rank(2) ) { $moves = $this-&gt;add_slide_moves_to_moves_list($directions_list, 2, $moves, $piece, $color_to_move, $board); } else { $moves = $this-&gt;add_slide_moves_to_moves_list($directions_list, 1, $moves, $piece, $color_to_move, $board); } $directions_list = array('northeast', 'northwest'); $moves = $this-&gt;add_capture_moves_to_moves_list($directions_list, $moves, $piece, $color_to_move, $board); // en passant $moves = $this-&gt;add_en_passant_moves_to_moves_list($piece, $board, $moves); } elseif ( $piece-&gt;color == 'black' ) { $directions_list = array('south'); if ( $piece-&gt;on_rank(7) ) { $moves = $this-&gt;add_slide_moves_to_moves_list($directions_list, 2, $moves, $piece, $color_to_move, $board); } else { $moves = $this-&gt;add_slide_moves_to_moves_list($directions_list, 1, $moves, $piece, $color_to_move, $board); } $directions_list = array('southeast', 'southwest'); $moves = $this-&gt;add_capture_moves_to_moves_list($directions_list, $moves, $piece, $color_to_move, $board); // en passant $moves = $this-&gt;add_en_passant_moves_to_moves_list($piece, $board, $moves); } } elseif ( $piece-&gt;type == 'knight' ) { $oclock_list = array(1, 2, 4, 5, 7, 8, 10, 11); $moves = $this-&gt;add_jump_and_jumpcapture_moves_to_moves_list($oclock_list, $moves, $piece, $color_to_move, $board); } elseif ( $piece-&gt;type == 'bishop' ) { $directions_list = array( 'northwest', 'northeast', 'southwest', 'southeast' ); $moves = $this-&gt;add_slide_and_slidecapture_moves_to_moves_list($directions_list, 7, $moves, $piece, $color_to_move, $board); } elseif ( $piece-&gt;type == 'rook' ) { $directions_list = array( 'north', 'south', 'east', 'west' ); $moves = $this-&gt;add_slide_and_slidecapture_moves_to_moves_list($directions_list, 7, $moves, $piece, $color_to_move, $board); } elseif ( $piece-&gt;type == 'queen' ) { $directions_list = array( 'north', 'south', 'east', 'west', 'northwest', 'northeast', 'southwest', 'southeast' ); $moves = $this-&gt;add_slide_and_slidecapture_moves_to_moves_list($directions_list, 7, $moves, $piece, $color_to_move, $board); } elseif ( $piece-&gt;type == 'king' ) { $directions_list = array( 'north', 'south', 'east', 'west', 'northwest', 'northeast', 'southwest', 'southeast' ); $moves = $this-&gt;add_slide_and_slidecapture_moves_to_moves_list($directions_list, 1, $moves, $piece, $color_to_move, $board); // Set $king here so castling function can use it later. $king = $piece; } } if ( $moves === array() ) { $moves = NULL; } if ( $eliminate_king_in_check_moves ) { $enemy_color = $this-&gt;invert_color($color_to_move); // Eliminate king in check moves $new_moves = array(); if ( ! $king ) { throw new Exception('ChessGame Class - Invalid FEN - One of the kings is missing'); } foreach ( $moves as $key =&gt; $move ) { $friendly_king_square = $move-&gt;board-&gt;get_king_square($color_to_move); $squares_attacked_by_enemy = $this-&gt;get_squares_attacked_by_this_color($enemy_color, $move-&gt;board); if ( ! in_array($friendly_king_square-&gt;alphanumeric, $squares_attacked_by_enemy) ) { array_push($new_moves, $move); } } $moves = $new_moves; // TODO: Move notation - disambiguate vague starting squares // foreach $moves as $key =&gt; $move // if $move-&gt;piece-&gt;type == queen, rook, knight, bishop // make list of destination squares // identify duplicates // foreach duplicates as $key =&gt; $move2 // if column disambiguate this piece // $move-&gt;set_disambiguation(column); // elseif row disambiguates this piece // $move-&gt;set_disambiguation(row); // else // $move-&gt;set_disambiguation(columnrow); // Castling // (castling does its own "king in check" checks so we can put this code after the "king in check" code) $squares_attacked_by_enemy = $this-&gt;get_squares_attacked_by_this_color($enemy_color, $board); $moves = $this-&gt;add_castling_moves_to_moves_list($moves, $king, $squares_attacked_by_enemy, $board); // if move puts enemy king in check, tell the $move object so it can add a + to the notation foreach ( $moves as $key =&gt; $move ) { $enemy_king_square = $move-&gt;board-&gt;get_king_square($enemy_color); $squares_attacked_by_moving_side = $this-&gt;get_squares_attacked_by_this_color($color_to_move, $move-&gt;board); if ( in_array($enemy_king_square-&gt;alphanumeric, $squares_attacked_by_moving_side) ) { $move-&gt;set_enemy_king_in_check(TRUE); } } // TODO: alphabetize } return $moves; } function add_slide_and_slidecapture_moves_to_moves_list($directions_list, $spaces, $moves, $piece, $color_to_move, $board) { foreach ( $directions_list as $key =&gt; $direction ) { // $spaces should be 1 for king, 1 or 2 for pawns, 7 for all other sliding pieces // 7 is the max # of squares you can slide on a chessboard $xy = array( 'north' =&gt; array(0,1), 'south' =&gt; array(0,-1), 'east' =&gt; array(1,0), 'west' =&gt; array(-1,0), 'northeast' =&gt; array(1,1), 'northwest' =&gt; array(-1,1), 'southeast' =&gt; array(1,-1), 'southwest' =&gt; array(-1,-1) ); // XY coordinates and rank/file are different. Need to convert. $xy = $this-&gt;convert_from_xy_to_rankfile($xy); $legal_move_list = array(); for ( $i = 1; $i &lt;= $spaces; $i++ ) { $current_xy = $xy[$direction]; $current_xy[0] *= $i; $current_xy[1] *= $i; $ending_square = $this-&gt;square_exists_and_not_occupied_by_friendly_piece( $piece-&gt;square, $current_xy[0], $current_xy[1], $color_to_move, $board ); if ( $ending_square ) { $capture = FALSE; if ( is_a($board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file], 'ChessPiece') ) { if ( $board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file]-&gt;color != $color_to_move ) { $capture = TRUE; } } array_push($legal_move_list, new ChessMove( $piece-&gt;square, $ending_square, $piece-&gt;color, $piece-&gt;type, $capture, $board )); if ( $capture ) { // stop sliding break; } else { // empty square // continue sliding continue; } } else { // square does not exist, or square occupied by friendly piece // stop sliding break; } } if ( $legal_move_list === array() ) { $legal_move_list = NULL; } if ( $legal_move_list ) { foreach ( $legal_move_list as $key2 =&gt; $value2 ) { array_push($moves, $value2); } } } return $moves; } function add_capture_moves_to_moves_list($directions_list, $moves, $piece, $color_to_move, $board) { foreach ( $directions_list as $key =&gt; $direction ) { $xy = array( 'north' =&gt; array(0,1), 'south' =&gt; array(0,-1), 'east' =&gt; array(1,0), 'west' =&gt; array(-1,0), 'northeast' =&gt; array(1,1), 'northwest' =&gt; array(-1,1), 'southeast' =&gt; array(1,-1), 'southwest' =&gt; array(-1,-1) ); // XY coordinates and rank/file are different. Need to convert. $xy = $this-&gt;convert_from_xy_to_rankfile($xy); $legal_move_list = array(); $current_xy = $xy[$direction]; $ending_square = $this-&gt;square_exists_and_not_occupied_by_friendly_piece( $piece-&gt;square, $current_xy[0], $current_xy[1], $color_to_move, $board ); if ( $ending_square ) { $capture = FALSE; if ( is_a($board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file], 'ChessPiece') ) { if ( $board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file]-&gt;color != $color_to_move ) { $capture = TRUE; } } if ( $capture ) { $move = new ChessMove( $piece-&gt;square, $ending_square, $piece-&gt;color, $piece-&gt;type, $capture, $board ); // pawn promotion $white_pawn_capturing_on_rank_8 = $piece-&gt;type == "pawn" &amp;&amp; $ending_square-&gt;rank == 8 &amp;&amp; $piece-&gt;color == "white"; $black_pawn_capturing_on_rank_1 = $piece-&gt;type == "pawn" &amp;&amp; $ending_square-&gt;rank == 1 &amp;&amp; $piece-&gt;color == "black"; if ( $white_pawn_capturing_on_rank_8 || $black_pawn_capturing_on_rank_1 ) { $promotion_pieces = array( 'queen', 'rook', 'bishop', 'knight' ); foreach ( $promotion_pieces as $key =&gt; $type ) { $move2 = clone $move; $move2-&gt;set_promotion_piece($type); array_push($legal_move_list, $move2); } } else { array_push($legal_move_list, $move); } } } if ( $legal_move_list === array() ) { $legal_move_list = NULL; } if ( $legal_move_list ) { foreach ( $legal_move_list as $key2 =&gt; $value2 ) { array_push($moves, $value2); } } } return $moves; } function add_slide_moves_to_moves_list($directions_list, $spaces, $moves, $piece, $color_to_move, $board) { foreach ( $directions_list as $key =&gt; $direction ) { // $spaces should be 1 for king, 1 or 2 for pawns, 7 for all other sliding pieces // 7 is the max # of squares you can slide on a chessboard $xy = array( 'north' =&gt; array(0,1), 'south' =&gt; array(0,-1), 'east' =&gt; array(1,0), 'west' =&gt; array(-1,0), 'northeast' =&gt; array(1,1), 'northwest' =&gt; array(-1,1), 'southeast' =&gt; array(1,-1), 'southwest' =&gt; array(-1,-1) ); // XY coordinates and rank/file are different. Need to convert. $xy = $this-&gt;convert_from_xy_to_rankfile($xy); $legal_move_list = array(); for ( $i = 1; $i &lt;= $spaces; $i++ ) { $current_xy = $xy[$direction]; $current_xy[0] *= $i; $current_xy[1] *= $i; $ending_square = $this-&gt;square_exists_and_not_occupied_by_friendly_piece( $piece-&gt;square, $current_xy[0], $current_xy[1], $color_to_move, $board ); if ( $ending_square ) { $capture = FALSE; if ( is_a($board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file], 'ChessPiece') ) { if ( $board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file]-&gt;color != $color_to_move ) { $capture = TRUE; } } if ( $capture ) { // enemy piece in square // stop sliding break; } else { $new_move = new ChessMove( $piece-&gt;square, $ending_square, $piece-&gt;color, $piece-&gt;type, $capture, $board ); // en passant target square if ( $piece-&gt;type == 'pawn' &amp;&amp; $i == 2 ) { $en_passant_xy = $xy[$direction]; $en_passant_xy[0] *= 1; $en_passant_xy[1] *= 1; $en_passant_target_square = $this-&gt;square_exists_and_not_occupied_by_friendly_piece( $piece-&gt;square, $en_passant_xy[0], $en_passant_xy[1], $color_to_move, $board ); $new_move-&gt;board-&gt;set_en_passant_target_square($en_passant_target_square); } // pawn promotion $white_pawn_moving_to_rank_8 = $piece-&gt;type == "pawn" &amp;&amp; $ending_square-&gt;rank == 8 &amp;&amp; $piece-&gt;color == "white"; $black_pawn_moving_to_rank_1 = $piece-&gt;type == "pawn" &amp;&amp; $ending_square-&gt;rank == 1 &amp;&amp; $piece-&gt;color == "black"; if ( $white_pawn_moving_to_rank_8 || $black_pawn_moving_to_rank_1 ) { $promotion_pieces = array( 'queen', 'rook', 'bishop', 'knight' ); foreach ( $promotion_pieces as $key =&gt; $type ) { $move2 = clone $new_move; $move2-&gt;set_promotion_piece($type); array_push($legal_move_list, $move2); } } else { array_push($legal_move_list, $new_move); } // empty square // continue sliding continue; } } else { // square does not exist, or square occupied by friendly piece // stop sliding break; } } if ( $legal_move_list === array() ) { $legal_move_list = NULL; } if ( $legal_move_list ) { foreach ( $legal_move_list as $key2 =&gt; $value2 ) { array_push($moves, $value2); } } } return $moves; } function add_jump_and_jumpcapture_moves_to_moves_list($oclock_list, $moves, $piece, $color_to_move, $board) { foreach ( $oclock_list as $key =&gt; $oclock ) { $xy = array( 1 =&gt; array(1,2), 2 =&gt; array(2,1), 4 =&gt; array(2,-1), 5 =&gt; array(1,-2), 7 =&gt; array(-1,-2), 8 =&gt; array(-2,-1), 10 =&gt; array(-2,1), 11 =&gt; array(-1,2) ); // XY coordinates and rank/file are different. Need to convert. $xy = $this-&gt;convert_from_xy_to_rankfile($xy); $ending_square = $this-&gt;square_exists_and_not_occupied_by_friendly_piece( $piece-&gt;square, $xy[$oclock][0], $xy[$oclock][1], $color_to_move, $board ); $legal_move_list = array(); if ( $ending_square ) { $capture = FALSE; if ( is_a($board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file], 'ChessPiece') ) { // enemy piece if ( $board-&gt;board[$ending_square-&gt;rank][$ending_square-&gt;file]-&gt;color != $color_to_move ) { $capture = TRUE; } } array_push($legal_move_list, new ChessMove( $piece-&gt;square, $ending_square, $piece-&gt;color, $piece-&gt;type, $capture, $board )); } if ( $legal_move_list === array() ) { $legal_move_list = NULL; } if ( $legal_move_list ) { foreach ( $legal_move_list as $key2 =&gt; $value2 ) { array_push($moves, $value2); } } } return $moves; } function add_castling_moves_to_moves_list($moves, $piece, $squares_attacked_by_enemy, $board) { $scenarios = array ( array( 'boolean_to_check' =&gt; 'white_can_castle_kingside', 'color_to_move' =&gt; 'white', 'rook_start_square' =&gt; new ChessSquare('h1'), 'king_end_square' =&gt; new ChessSquare('g1'), 'cannot_be_attacked' =&gt; array( new ChessSquare('e1'), new ChessSquare('f1'), new ChessSquare('g1') ), 'cannot_be_occupied' =&gt; array( new ChessSquare('f1'), new ChessSquare('g1') ) ), array( 'boolean_to_check' =&gt; 'white_can_castle_queenside', 'color_to_move' =&gt; 'white', 'rook_start_square' =&gt; new ChessSquare('a1'), 'king_end_square' =&gt; new ChessSquare('c1'), 'cannot_be_attacked' =&gt; array( new ChessSquare('e1'), new ChessSquare('d1'), new ChessSquare('c1') ), 'cannot_be_occupied' =&gt; array( new ChessSquare('d1'), new ChessSquare('c1'), new ChessSquare('b1') ) ), array( 'boolean_to_check' =&gt; 'black_can_castle_kingside', 'color_to_move' =&gt; 'black', 'rook_start_square' =&gt; new ChessSquare('h8'), 'king_end_square' =&gt; new ChessSquare('g8'), 'cannot_be_attacked' =&gt; array( new ChessSquare('e8'), new ChessSquare('f8'), new ChessSquare('g8') ), 'cannot_be_occupied' =&gt; array( new ChessSquare('f8'), new ChessSquare('g8') ) ), array( 'boolean_to_check' =&gt; 'black_can_castle_queenside', 'color_to_move' =&gt; 'black', 'rook_start_square' =&gt; new ChessSquare('a8'), 'king_end_square' =&gt; new ChessSquare('c8'), 'cannot_be_attacked' =&gt; array( new ChessSquare('e8'), new ChessSquare('d8'), new ChessSquare('c8') ), 'cannot_be_occupied' =&gt; array( new ChessSquare('d8'), new ChessSquare('c8'), new ChessSquare('b8') ) ), ); $legal_move_list = array(); foreach ( $scenarios as $key =&gt; $value ) { // only check castling for current color_to_move if ( $value['color_to_move'] != $board-&gt;color_to_move ) { continue; } // make sure the FEN has castling permissions $boolean_to_check = $value['boolean_to_check']; if ( ! $board-&gt;castling[$boolean_to_check] ) { continue; } // check all cannot_be_attacked squares foreach ( $value['cannot_be_attacked'] as $key2 =&gt; $square_to_check ) { if ( in_array($square_to_check-&gt;alphanumeric, $squares_attacked_by_enemy) ) { continue 2; } } // check all cannot_be_occupied_squares foreach ( $value['cannot_be_occupied'] as $key2 =&gt; $square_to_check ) { if ( $board-&gt;square_is_occupied($square_to_check) ) { continue 2; } } // Make sure the rook is still there. This case should only occur in damaged FENs. If the rook isn't there, throw an invalid FEN exception (to prevent a clone error later on). $rook_start_square = $value['rook_start_square']; $rank = $rook_start_square-&gt;rank; $file = $rook_start_square-&gt;file; $piece_to_check = $board-&gt;board[$rank][$file]; if ( ! $piece_to_check ) { throw new Exception('ChessGame Class - Invalid FEN - Castling permissions set to TRUE but rook is missing'); } if ( $piece_to_check-&gt;type != 'rook' || $piece_to_check-&gt;color != $board-&gt;color_to_move ) { throw new Exception('ChessGame Class - Invalid FEN - Castling permissions set to TRUE but rook is missing'); } // The ChessMove class handles displaying castling notation, taking castling privileges out of the FEN, and moving the rook into the right place on the board. No need to do anything extra here. array_push($legal_move_list, new ChessMove( $piece-&gt;square, $value['king_end_square'], $piece-&gt;color, $piece-&gt;type, FALSE, $board )); } if ( $legal_move_list === array() ) { $legal_move_list = NULL; } if ( $legal_move_list ) { foreach ( $legal_move_list as $key2 =&gt; $value2 ) { array_push($moves, $value2); } } return $moves; } function add_en_passant_moves_to_moves_list($piece, $board, $moves) { if ( $piece-&gt;color == 'white' ) { $capture_directions_from_starting_square = array('northeast', 'northwest'); $enemy_pawn_direction_from_ending_square = array('south'); $en_passant_rank = 5; } elseif ( $piece-&gt;color == 'black' ) { $capture_directions_from_starting_square = array('southeast', 'southwest'); $enemy_pawn_direction_from_ending_square = array('north'); $en_passant_rank = 4; } if ( $piece-&gt;on_rank($en_passant_rank) &amp;&amp; $board-&gt;en_passant_target_square ) { $squares_to_check = $this-&gt;get_squares_in_these_directions($piece-&gt;square, $capture_directions_from_starting_square, 1); foreach ( $squares_to_check as $key =&gt; $square ) { if ( $square-&gt;alphanumeric == $board-&gt;en_passant_target_square-&gt;alphanumeric ) { $move = new ChessMove( $piece-&gt;square, $square, $piece-&gt;color, $piece-&gt;type, TRUE, $board ); $move-&gt;set_en_passant(TRUE); $enemy_pawn_square = $this-&gt;get_squares_in_these_directions($square, $enemy_pawn_direction_from_ending_square, 1); $move-&gt;board-&gt;remove_piece_from_square($enemy_pawn_square[0]); array_push($moves, $move); } } } return $moves; } function convert_from_xy_to_rankfile($xy) { // XY coordinates and rank/file are different. Need to convert. // We basically need to flip X and Y to fix it. foreach ( $xy as $key =&gt; $value ) { $xy[$key] = array($value[1], $value[0]); } return $xy; } function get_all_pieces_by_color($color_to_move, $board) { $list_of_pieces = array(); for ( $i = 1; $i &lt;= 8; $i++ ) { for ( $j = 1; $j &lt;=8; $j++ ) { $piece = $board-&gt;board[$i][$j]; if ( $piece ) { if ( $piece-&gt;color == $color_to_move ) { array_push($list_of_pieces, $piece); } } } } if ( $list_of_pieces === array() ) { $list_of_pieces = NULL; } return $list_of_pieces; } // positive X = east, negative X = west, positive Y = north, negative Y = south function square_exists_and_not_occupied_by_friendly_piece($starting_square, $x_delta, $y_delta, $color_to_move, $board) { $rank = $starting_square-&gt;rank + $x_delta; $file = $starting_square-&gt;file + $y_delta; $ending_square = $this-&gt;try_to_make_square_using_rank_and_file_num($rank, $file); // Ending square is off the board if ( ! $ending_square ) { return FALSE; } // Ending square contains a friendly piece if ( is_a($board-&gt;board[$rank][$file], 'ChessPiece') ) { if ( $board-&gt;board[$rank][$file]-&gt;color == $color_to_move ) { return FALSE; } } return $ending_square; } function try_to_make_square_using_rank_and_file_num($rank, $file) { $file_letters = new Dictionary(array( 1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd', 5 =&gt; 'e', 6 =&gt; 'f', 7 =&gt; 'g', 8 =&gt; 'h' )); $alphanumeric = $file_letters-&gt;check_dictionary($file) . $rank; $valid_squares = array( 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8' ); if ( in_array($alphanumeric, $valid_squares) ) { return new ChessSquare($alphanumeric); } else { return FALSE; } } function invert_color($color) { if ( $color == 'white' ) { return 'black'; } else { return 'white'; } } function get_squares_attacked_by_this_color($color, $board) { $legal_moves_for_opponent = $this-&gt;get_legal_moves_list($color, $board, FALSE); $squares_attacked = array(); foreach ( $legal_moves_for_opponent as $key =&gt; $move ) { // avoid duplicates if ( ! in_array($move-&gt;ending_square-&gt;alphanumeric, $squares_attacked) ) { array_push($squares_attacked, $move-&gt;ending_square-&gt;alphanumeric); } } return $squares_attacked; } // Used to generate en passant squares. function get_squares_in_these_directions($starting_square, $directions_list, $spaces) { $list_of_squares = array(); foreach ( $directions_list as $key =&gt; $direction ) { // $spaces should be 1 for king, 1 or 2 for pawns, 7 for all other sliding pieces // 7 is the max # of squares you can slide on a chessboard $xy = array( 'north' =&gt; array(0,1), 'south' =&gt; array(0,-1), 'east' =&gt; array(1,0), 'west' =&gt; array(-1,0), 'northeast' =&gt; array(1,1), 'northwest' =&gt; array(-1,1), 'southeast' =&gt; array(1,-1), 'southwest' =&gt; array(-1,-1) ); // XY coordinates and rank/file are different. Need to convert. $xy = $this-&gt;convert_from_xy_to_rankfile($xy); $current_xy = $xy[$direction]; $current_xy[0] = $current_xy[0] * $spaces + $starting_square-&gt;rank; $current_xy[1] = $current_xy[1] * $spaces + $starting_square-&gt;file; $square = $this-&gt;try_to_make_square_using_rank_and_file_num($current_xy[0], $current_xy[1]); if ( $square ) { array_push($list_of_squares, $square); } } if ( $list_of_squares === array() ) { $list_of_squares = NULL; } return $list_of_squares; }} </code></pre> <h1>ChessMove.php</h1> <pre><code>&lt;?php class ChessMove { const PIECE_LETTERS = array( 'p' =&gt; 'pawn', 'n' =&gt; 'knight', 'b' =&gt; 'bishop', 'r' =&gt; 'rook', 'q' =&gt; 'queen', 'k' =&gt; 'king' ); var $starting_square; var $ending_square; var $color; var $piece_type; var $capture; var $check; var $checkmate; var $promotion_piece_type; var $en_passant_capture; var $disambiguation; var $notation; var $coordiante_notation; var $board; function __construct( $starting_square, $ending_square, $color, $piece_type, $capture, $old_board ) { $this-&gt;starting_square = $starting_square; $this-&gt;ending_square = $ending_square; $this-&gt;color = $color; $this-&gt;piece_type = $piece_type; $this-&gt;capture = $capture; // These cases are rare. The data is passed in via set functions instead of in the constructor. $this-&gt;disambiguation = ''; $this-&gt;promotion_piece_type = NULL; $this-&gt;en_passant = FALSE; $this-&gt;check = FALSE; $this-&gt;checkmate = FALSE; $this-&gt;notation = $this-&gt;get_notation(); $this-&gt;coordinate_notation = $this-&gt;starting_square-&gt;alphanumeric . $this-&gt;ending_square-&gt;alphanumeric; $this-&gt;board = clone $old_board; $this-&gt;board-&gt;make_move($starting_square, $ending_square); // if the king or rook moves, update the FEN to take away castling privileges if ( $this-&gt;color == 'black' ) { if ( $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'e8' ) { $this-&gt;board-&gt;set_castling('black_can_castle_kingside', FALSE); $this-&gt;board-&gt;set_castling('black_can_castle_queenside', FALSE); } elseif ( $this-&gt;piece_type == 'rook' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'a8' ) { $this-&gt;board-&gt;set_castling('black_can_castle_queenside', FALSE); } elseif ( $this-&gt;piece_type == 'rook' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'h8' ) { $this-&gt;board-&gt;set_castling('black_can_castle_kingside', FALSE); } } elseif ( $this-&gt;color == 'white' ) { if ( $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'e1' ) { $this-&gt;board-&gt;set_castling('white_can_castle_kingside', FALSE); $this-&gt;board-&gt;set_castling('white_can_castle_queenside', FALSE); } elseif ( $this-&gt;piece_type == 'rook' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'a1' ) { $this-&gt;board-&gt;set_castling('white_can_castle_queenside', FALSE); } elseif ( $this-&gt;piece_type == 'rook' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'h1' ) { $this-&gt;board-&gt;set_castling('white_can_castle_kingside', FALSE); } } // if castling, move the rook into the right place if ( $this-&gt;color == 'black' ) { if ( $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'e8' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'g8' ) { $starting_square = new ChessSquare('h8'); $ending_square = new ChessSquare('f8'); $this-&gt;board-&gt;make_additional_move_on_same_turn($starting_square, $ending_square); } elseif ( $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'e8' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'c8' ) { $starting_square = new ChessSquare('a8'); $ending_square = new ChessSquare('d8'); $this-&gt;board-&gt;make_additional_move_on_same_turn($starting_square, $ending_square); } } elseif ( $this-&gt;color == 'white' ) { if ( $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'e1' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'g1' ) { $starting_square = new ChessSquare('h1'); $ending_square = new ChessSquare('f1'); $this-&gt;board-&gt;make_additional_move_on_same_turn($starting_square, $ending_square); } elseif ( $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;starting_square-&gt;alphanumeric == 'e1' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'c1' ) { $starting_square = new ChessSquare('a1'); $ending_square = new ChessSquare('d1'); $this-&gt;board-&gt;make_additional_move_on_same_turn($starting_square, $ending_square); } } } // Do a deep clone. Needed for pawn promotion. function __clone() { $this-&gt;starting_square = clone $this-&gt;starting_square; $this-&gt;ending_square = clone $this-&gt;ending_square; $this-&gt;board = clone $this-&gt;board; } function set_promotion_piece($piece_type) { // update the piece $rank = $this-&gt;ending_square-&gt;rank; $file = $this-&gt;ending_square-&gt;file; $this-&gt;board-&gt;board[$rank][$file]-&gt;type = $piece_type; $this-&gt;board-&gt;update_fen(); // Automatically pick queen when drag and dropping. if ( $piece_type != "queen" ) { $this-&gt;coordinate_notation = ""; } // update the notation $this-&gt;promotion_piece_type = $piece_type; $this-&gt;notation = $this-&gt;get_notation(); } function set_enemy_king_in_check($boolean) { $this-&gt;check = $boolean; $this-&gt;notation = $this-&gt;get_notation(); } function set_checkmate($boolean) { $this-&gt;checkmate = $boolean; $this-&gt;notation = $this-&gt;get_notation(); } function set_en_passant($boolean) { $this-&gt;en_passant = $boolean; $this-&gt;notation = $this-&gt;get_notation(); } function set_disambiguation($string) { $this-&gt;disambiguation = $string; $this-&gt;notation = $this-&gt;get_notation(); } function get_notation() { $string = ''; if ( $this-&gt;starting_square-&gt;alphanumeric == 'e8' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'g8' &amp;&amp; $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;color = 'black' ) { $string .= 'O-O'; } elseif ( $this-&gt;starting_square-&gt;alphanumeric == 'e1' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'g1' &amp;&amp; $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;color = 'white' ) { $string .= 'O-O'; } elseif ( $this-&gt;starting_square-&gt;alphanumeric == 'e8' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'c8' &amp;&amp; $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;color = 'black' ) { $string .= 'O-O-O'; } elseif ( $this-&gt;starting_square-&gt;alphanumeric == 'e1' &amp;&amp; $this-&gt;ending_square-&gt;alphanumeric == 'c1' &amp;&amp; $this-&gt;piece_type == 'king' &amp;&amp; $this-&gt;color = 'white' ) { $string .= 'O-O-O'; } else { // type of piece if ( $this-&gt;piece_type == 'pawn' &amp;&amp; $this-&gt;capture ) { $string .= substr($this-&gt;starting_square-&gt;alphanumeric, 0, 1); } elseif ( $this-&gt;piece_type != 'pawn' ) { $string .= strtoupper(array_search( $this-&gt;piece_type, self::PIECE_LETTERS )); } // disambiguation rank/file/square $string .= $this-&gt;disambiguation; // capture? if ( $this-&gt;capture ) { $string .= 'x'; } // destination square $string .= $this-&gt;ending_square-&gt;alphanumeric; // en passant if ( $this-&gt;en_passant ) { $string .= 'e.p.'; } // pawn promotion if ( $this-&gt;promotion_piece_type == 'queen' ) { $string .= '=Q'; } elseif ( $this-&gt;promotion_piece_type == 'rook' ) { $string .= '=R'; } elseif ( $this-&gt;promotion_piece_type == 'bishop' ) { $string .= '=B'; } elseif ( $this-&gt;promotion_piece_type == 'knight' ) { $string .= '=N'; } } // check or checkmate if ( $this-&gt;checkmate ) { $string .= '#'; } elseif ( $this-&gt;check ) { $string .= '+'; } return $string; } } </code></pre> <h1>ChessBoard.php</h1> <pre><code>&lt;?php class ChessBoard { const PIECE_LETTERS = array( 'p' =&gt; 'pawn', 'n' =&gt; 'knight', 'b' =&gt; 'bishop', 'r' =&gt; 'rook', 'q' =&gt; 'queen', 'k' =&gt; 'king' ); var $board = array(); // $board[y][x], or in this case, $board[rank][file] var $color_to_move; var $castling = array(); // format is array('white_can_castle_kingside' =&gt; TRUE, etc.) var $en_passant_target_square = NULL; var $halfmove_clock; var $fullmove_number; var $fen; function __construct($fen) { $this-&gt;set_fen($fen); $this-&gt;fen = $fen; } function __clone() { if ( $this-&gt;board ) { for ( $rank = 1; $rank &lt;= 8; $rank++ ) { for ( $file = 1; $file &lt;= 8; $file++ ) { if ( $this-&gt;board[$rank][$file] ) { $this-&gt;board[$rank][$file] = clone $this-&gt;board[$rank][$file]; } } } } } function set_fen($fen) { $fen = trim($fen); // set everything back to default $legal_moves = array(); $checkmate = FALSE; $stalemate = FALSE; $move_list = array(); // TODO: add more // Basic format check. This won't catch everything, but it will catch a lot of stuff. // TODO: Make this stricter so that it catches everything. $valid_fen = preg_match('/^([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8})\/([rnbqkpRNBQKP12345678]{1,8}) ([bw]{1}) ([-KQkq]{1,4}) ([a-h1-8-]{1,2}) (\d{1,2}) (\d{1,4})$/', $fen, $matches); if ( ! $valid_fen ) { throw new Exception('ChessBoard Class - Invalid FEN'); } // ******* CREATE PIECES AND ASSIGN THEM TO SQUARES ******* // Set all board squares to NULL. That way we don't have to blank them in the loop below. We can just overwrite the NULL with a piece. for ( $i = 1; $i &lt;= 8; $i++ ) { for ( $j = 1; $j &lt;= 8; $j++ ) { $this-&gt;board[$i][$j] = NULL; } } // Create $rank variables with strings that look like this // rnbqkbnr // pppppppp // 8 // PPPPPPPP // RNBQKBNR // 2p5 // The numbers are the # of blank squares from left to right $rank = array(); for ( $i = 1; $i &lt;= 8; $i++ ) { // Match string = 1, but rank = 8. Fix it here to avoid headaches. $rank = $this-&gt;invert_rank_or_file_number($i); $rank_string[$rank] = $matches[$i]; } // Process $rank variable strings, convert to pieces and add them to $this-&gt;board[][] foreach ( $rank_string as $rank =&gt; $string ) { $file = 1; for ( $i = 1; $i &lt;= strlen($string); $i++ ) { $char = substr($string, $i - 1, 1); // Don't use is_int here. $char is a string. Use is_numeric instead. if ( is_numeric($char) ) { $file = $file + $char; } else { $square = $this-&gt;number_to_file($file) . $rank; if ( ctype_upper($char) ) { $color = 'white'; } else { $color = 'black'; } $type = self::PIECE_LETTERS[strtolower($char)]; $this-&gt;board[$rank][$file] = new ChessPiece($color, $square, $type); $file++; } } } // ******* SET COLOR TO MOVE ******* if ( $matches[9] == 'w' ) { $this-&gt;color_to_move = 'white'; } elseif ( $matches[9] == 'b' ) { $this-&gt;color_to_move = 'black'; } else { throw new Exception('ChessBoard Class - Invalid FEN - Invalid Color To Move'); } // Set all castling to false. Only set to true if letter is present in FEN. Prevents bugs. $this-&gt;castling['white_can_castle_kingside'] = FALSE; $this-&gt;castling['white_can_castle_queenside'] = FALSE; $this-&gt;castling['black_can_castle_kingside'] = FALSE; $this-&gt;castling['black_can_castle_queenside'] = FALSE; // ******* SET CASTLING POSSIBILITIES ******* // strpos is case sensitive, so that's good if ( strpos($matches[10], 'K') !== FALSE ) { $this-&gt;castling['white_can_castle_kingside'] = TRUE; } if ( strpos($matches[10], 'Q') !== FALSE ) { $this-&gt;castling['white_can_castle_queenside'] = TRUE; } if ( strpos($matches[10], 'k') !== FALSE ) { $this-&gt;castling['black_can_castle_kingside'] = TRUE; } if ( strpos($matches[10], 'q') !== FALSE ) { $this-&gt;castling['black_can_castle_queenside'] = TRUE; } // ******* SET EN PASSANT TARGET SQUARE ******* if ( $matches[11] == '-' ) { $this-&gt;en_passant_target_square = FALSE; } else { $this-&gt;en_passant_target_square = new ChessSquare($matches[11]); } // ChessPiece throws its own exceptions, so no need to throw one here. // ******* SET HALFMOVE CLOCK ******* $this-&gt;halfmove_clock = $matches[12]; // ******* SET FULLMOVE NUMBER ******* $this-&gt;fullmove_number = $matches[13]; // ******* SET HALFMOVE NUMBER ******* $this-&gt;halfmove_number = $matches[13] * 2 - 1; if ( $this-&gt;color_to_move == 'black' ) { $this-&gt;halfmove_number++; } $this-&gt;fen = $fen; } function get_fen() { $string = ''; // A chessboard looks like this // a8 b8 c8 d8 // a7 b7 c7 d7 // etc. // But we want to print them starting with row 8 first. // So we need to adjust the loops a bit. for ( $rank = 8; $rank &gt;= 1; $rank-- ) { $empty_squares = 0; for ( $file = 1; $file &lt;= 8; $file++ ) { $piece = $this-&gt;board[$rank][$file]; if ( ! $piece ) { $empty_squares++; } else { if ( $empty_squares ) { $string .= $empty_squares; $empty_squares = 0; } $string .= $piece-&gt;get_fen_symbol(); } } if ( $empty_squares ) { $string .= $empty_squares; } if ( $rank != 1 ) { $string .= "/"; } } if ( $this-&gt;color_to_move == 'white' ) { $string .= " w "; } elseif ( $this-&gt;color_to_move == 'black' ) { $string .= " b "; } if ( $this-&gt;castling['white_can_castle_kingside'] ) { $string .= "K"; } if ( $this-&gt;castling['white_can_castle_queenside'] ) { $string .= "Q"; } if ( $this-&gt;castling['black_can_castle_kingside'] ) { $string .= "k"; } if ( $this-&gt;castling['black_can_castle_queenside'] ) { $string .= "q"; } if ( ! $this-&gt;castling['white_can_castle_kingside'] &amp;&amp; ! $this-&gt;castling['white_can_castle_queenside'] &amp;&amp; ! $this-&gt;castling['black_can_castle_kingside'] &amp;&amp; ! $this-&gt;castling['black_can_castle_queenside'] ) { $string .= "-"; } if ( $this-&gt;en_passant_target_square ) { $string .= " " . $this-&gt;en_passant_target_square-&gt;alphanumeric; } else { $string .= " -"; } $string .= " " . $this-&gt;halfmove_clock . ' ' . $this-&gt;fullmove_number; return $string; } function update_fen() { $this-&gt;fen = $this-&gt;get_fen(); } // Keeping this for debug reasons. function get_ascii_board() { $string = ''; if ( $this-&gt;color_to_move == 'white' ) { $string .= "White To Move"; } elseif ( $this-&gt;color_to_move == 'black' ) { $string .= "Black To Move"; } // A chessboard looks like this // a8 b8 c8 d8 // a7 b7 c7 d7 // etc. // But we want to print them starting with row 8 first. // So we need to adjust the loops a bit. for ( $rank = 8; $rank &gt;= 1; $rank-- ) { $string .= "&lt;br /&gt;"; for ( $file = 1; $file &lt;= 8; $file++ ) { $square = $this-&gt;board[$rank][$file]; if ( ! $square ) { $string .= "*"; } else { $string .= $this-&gt;board[$rank][$file]-&gt;get_unicode_symbol(); } } } $string .= "&lt;br /&gt;&lt;br /&gt;"; return $string; } function get_graphical_board() { // We need to throw some variables into an array so our view can build the board. // The array shall be in the following format: // square_color = black / white // id = a1-h8 // piece = HTML unicode for that piece // A chessboard looks like this // a8 b8 c8 d8 // a7 b7 c7 d7 // etc. // But we want to print them starting with row 8 first. // So we need to adjust the loops a bit. $graphical_board_array = array(); for ( $rank = 8; $rank &gt;= 1; $rank-- ) { for ( $file = 1; $file &lt;= 8; $file++ ) { $piece = $this-&gt;board[$rank][$file]; // SQUARE COLOR if ( ($rank + $file) % 2 == 1 ) { $graphical_board_array[$rank][$file]['square_color'] = 'white'; } else { $graphical_board_array[$rank][$file]['square_color'] = 'black'; } // ID $file_letters = new Dictionary(array( 1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd', 5 =&gt; 'e', 6 =&gt; 'f', 7 =&gt; 'g', 8 =&gt; 'h' )); $graphical_board_array[$rank][$file]['id'] = $file_letters-&gt;check_dictionary($file) . $rank; // PIECE if ( ! $piece ) { $graphical_board_array[$rank][$file]['piece'] = ''; } else { $graphical_board_array[$rank][$file]['piece'] = $this-&gt;board[$rank][$file]-&gt;get_unicode_symbol(); } } } return $graphical_board_array; } function get_side_to_move_string() { $string = ''; if ( $this-&gt;color_to_move == 'white' ) { $string .= "White To Move"; } elseif ( $this-&gt;color_to_move == 'black' ) { $string .= "Black To Move"; } return $string; } function get_who_is_winning_string() { $points = 0; foreach ( $this-&gt;board as $key1 =&gt; $value1 ) { foreach ( $value1 as $key2 =&gt; $piece ) { if ( $piece ) { $points += $piece-&gt;value; } } } if ( $points &gt; 0 ) { return "Material: White Ahead By $points"; } elseif ( $points &lt; 0 ) { $points *= -1; return "Material: Black Ahead By $points"; } else { return "Material: Equal"; } } function invert_rank_or_file_number($number) { $dictionary = array( 1 =&gt; 8, 2 =&gt; 7, 3 =&gt; 6, 4 =&gt; 5, 5 =&gt; 4, 6 =&gt; 3, 7 =&gt; 2, 8 =&gt; 1 ); return $dictionary[$number]; } function number_to_file($number) { $dictionary = array( 1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd', 5 =&gt; 'e', 6 =&gt; 'f', 7 =&gt; 'g', 8 =&gt; 'h' ); if ( ! array_key_exists($number, $dictionary) ) { throw new Exception('ChessBoard Class - number_to_file - unknown file number - $number = ' . var_export($number, TRUE)); } return $dictionary[$number]; } // Note: This does not check for and reject illegal moves. It is up to code in the ChessGame class to generate a list of legal moves, then only make_move those moves. // In fact, sometimes make_move will be used on illegal moves (king in check moves), then the illegal moves will be deleted from the list of legal moves in a later step. function make_move($old_square, $new_square) { $moving_piece = clone $this-&gt;board[$old_square-&gt;rank][$old_square-&gt;file]; $this-&gt;set_en_passant_target_square(NULL); $is_capture = $this-&gt;board[$new_square-&gt;rank][$new_square-&gt;file]; if ( $moving_piece-&gt;type == 'pawn' || $is_capture ) { $this-&gt;halfmove_clock = 0; } else { $this-&gt;halfmove_clock++; } $this-&gt;board[$new_square-&gt;rank][$new_square-&gt;file] = $moving_piece; // Update $moving_piece-&gt;square too to avoid errors. $moving_piece-&gt;square = $new_square; $this-&gt;board[$old_square-&gt;rank][$old_square-&gt;file] = NULL; if ( $this-&gt;color_to_move == 'black' ) { $this-&gt;fullmove_number++; } $this-&gt;flip_color_to_move(); $this-&gt;update_fen(); } // Used to move the rook during castling. // Can't use make_move because it messes up color_to_move, halfmove, and fullmove. function make_additional_move_on_same_turn($old_square, $new_square) { $moving_piece = clone $this-&gt;board[$old_square-&gt;rank][$old_square-&gt;file]; $this-&gt;board[$new_square-&gt;rank][$new_square-&gt;file] = $moving_piece; // Update $moving_piece-&gt;square too to avoid errors. $moving_piece-&gt;square = $new_square; $this-&gt;board[$old_square-&gt;rank][$old_square-&gt;file] = NULL; $this-&gt;update_fen(); } function flip_color_to_move() { if ( $this-&gt;color_to_move == 'white' ) { $this-&gt;color_to_move = 'black'; } elseif ( $this-&gt;color_to_move == 'black' ) { $this-&gt;color_to_move = 'white'; } } function set_castling($string, $boolean) { $this-&gt;castling[$string] = $boolean; $this-&gt;update_fen(); } function set_en_passant_target_square($square) { $this-&gt;en_passant_target_square = $square; $this-&gt;update_fen(); } function square_is_occupied($square) { $rank = $square-&gt;rank; $file = $square-&gt;file; if ( $this-&gt;board[$rank][$file] ) { return TRUE; } else { return FALSE; } } function get_king_square($color) { foreach ( $this-&gt;board as $key =&gt; $value ) { foreach ( $value as $key2 =&gt; $piece ) { if ( $piece ) { if ( $piece-&gt;type == 'king' &amp;&amp; $piece-&gt;color == $color ) { return $piece-&gt;square; } } } } return NULL; } function remove_piece_from_square($square) { $rank = $square-&gt;rank; $file = $square-&gt;file; $this-&gt;board[$rank][$file] = NULL; $this-&gt;update_fen(); } } </code></pre> <h1>ChessPiece.php</h1> <pre><code>&lt;?php class ChessPiece { var $value; var $color; var $type; var $square; const VALID_COLORS = array('white', 'black'); const VALID_TYPES = array('pawn', 'knight', 'bishop', 'rook', 'queen', 'king'); const UNICODE_CHESS_PIECES = array( 'white_king' =&gt; '&amp;#9812;', 'white_queen' =&gt; '&amp;#9813;', 'white_rook' =&gt; '&amp;#9814;', 'white_bishop' =&gt; '&amp;#9815;', 'white_knight' =&gt; '&amp;#9816;', 'white_pawn' =&gt; '&amp;#9817;', 'black_king' =&gt; '&amp;#9818;', 'black_queen' =&gt; '&amp;#9819;', 'black_rook' =&gt; '&amp;#9820;', 'black_bishop' =&gt; '&amp;#9821;', 'black_knight' =&gt; '&amp;#9822;', 'black_pawn' =&gt; '&amp;#9823;' ); const FEN_CHESS_PIECES = array( 'white_king' =&gt; 'K', 'white_queen' =&gt; 'Q', 'white_rook' =&gt; 'R', 'white_bishop' =&gt; 'B', 'white_knight' =&gt; 'N', 'white_pawn' =&gt; 'P', 'black_king' =&gt; 'k', 'black_queen' =&gt; 'q', 'black_rook' =&gt; 'r', 'black_bishop' =&gt; 'b', 'black_knight' =&gt; 'n', 'black_pawn' =&gt; 'p' ); const PIECE_VALUES = array( 'pawn' =&gt; 1, 'knight' =&gt; 3, 'bishop' =&gt; 3, 'rook' =&gt; 5, 'queen' =&gt; 9, 'king' =&gt; 0 ); const SIDE_VALUES = array( 'white' =&gt; 1, 'black' =&gt; -1 ); function __construct($color, $square_string, $type) { if ( in_array($color, self::VALID_COLORS) ) { $this-&gt;color = $color; } else { throw new Exception('ChessPiece Class - Invalid Color'); } $this-&gt;square = new ChessSquare($square_string); if ( in_array($type, self::VALID_TYPES) ) { $this-&gt;type = $type; } else { throw new Exception('ChessPiece Class - Invalid Type'); } $this-&gt;value = self::PIECE_VALUES[$type] * self::SIDE_VALUES[$color]; } function __clone() { $this-&gt;square = clone $this-&gt;square; } function get_unicode_symbol() { $dictionary_key = $this-&gt;color . '_' . $this-&gt;type; return self::UNICODE_CHESS_PIECES[$dictionary_key]; } function get_fen_symbol() { $dictionary_key = $this-&gt;color . '_' . $this-&gt;type; return self::FEN_CHESS_PIECES[$dictionary_key]; } function on_rank($rank) { if ( $rank == $this-&gt;square-&gt;rank ) { return TRUE; } else { return FALSE; } } } </code></pre> <h1>ChessSquare.php</h1> <pre><code>&lt;?php class ChessSquare { const VALID_SQUARES = array( 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'g1', 'g2', 'g3', 'g4', 'g5', 'g6', 'g7', 'g8', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8' ); var $rank; var $file; var $alphanumeric; function __construct($alphanumeric) { $file_letters = new Dictionary(array( 1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd', 5 =&gt; 'e', 6 =&gt; 'f', 7 =&gt; 'g', 8 =&gt; 'h' )); if ( in_array($alphanumeric, self::VALID_SQUARES) ) { $this-&gt;alphanumeric = $alphanumeric; $this-&gt;file = $file_letters-&gt;check_dictionary(substr($alphanumeric, 0, 1)); $this-&gt;rank = substr($alphanumeric, 1, 1); } else { throw new Exception("ChessSquare Class - Invalid Square - \$alphanumeric = " . var_export($alphanumeric, TRUE)); } } } </code></pre> <h1>Dictionary.php</h1> <pre><code>&lt;?php // Array of pairs. The list of both columns put together cannot contain duplicates. class Dictionary { var $array_of_pairs; function __construct($array) { // make sure there are no duplicates $this-&gt;array_of_pairs = $array; } function check_dictionary($search_key) { if ( isset($this-&gt;array_of_pairs[$search_key]) ) { return $this-&gt;array_of_pairs[$search_key]; } elseif ( $search_results = array_search($search_key, $this-&gt;array_of_pairs) ) { return $search_results; } else { return NULL; } } } </code></pre> <h1>script.js</h1> <pre><code>$(document).ready(function(){ $('select').dblclick(function(){ $('#make_move').submit(); }); $('.draggable_piece').on("dragstart", function (event) { var dt = event.originalEvent.dataTransfer; dt.setData('Text', $(this).closest('td').attr('id')); }); $('table td').on("dragenter dragover drop", function (event) { event.preventDefault(); if (event.type === 'drop') { var oldsquare = event.originalEvent.dataTransfer.getData('Text',$(this).attr('id')); var newsquare = $(this).attr('id'); var coordinate_notation = oldsquare + newsquare; var option_tag_in_select_tag = $("select[name='move'] option[data-coordinate-notation='" + coordinate_notation + "']"); if ( option_tag_in_select_tag.length != 0 ) { option_tag_in_select_tag.attr('selected','selected'); $('#make_move').submit(); } }; }); }) </code></pre> <h1>style.css</h1> <pre><code>body { font-family:sans-serif; } input[name="fen"] { width: 500px; } input[type="submit"], input[type="button"] { font-size: 12pt; } textarea[name="pgn"] { width: 500px; font-family: sans-serif; } select[name="move"] { width: 8em; } .two_columns { display: flex; width: 600px; } .two_columns&gt;div:nth-child(1) { flex: 60%; } .two_columns&gt;div:nth-child(2) { flex: 40%; } #graphical_board { table-layout: fixed; border-collapse: collapse; } #graphical_board td { height: 40px; width: 40px; padding: 0; margin: 0; text-align: center; vertical-align: middle; font-size: 30px; font-weight: bold; font-family: "Arial Unicode MS", "Lucida Console", Courier, monospace; cursor: move; } .black { background-color: #769656; } .white { background-color: #EEEED2; } .status_box { background-color: #F0F0F0; border: 1px solid black; padding-top: 2px; padding-bottom: 2px; padding-left: 4px; padding-right: 4px; width: 310px; margin-bottom: 5px; } </code></pre> <h1>view.php</h1> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-us"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt; AdmiralAdama Chess &lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="scripts.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; AdmiralAdama Chess &lt;/h1&gt; &lt;div class="two_columns"&gt; &lt;div&gt; &lt;div class="status_box"&gt; &lt;?php echo $side_to_move; ?&gt; &lt;/div&gt; &lt;div class="status_box"&gt; &lt;?php echo $who_is_winning; ?&gt; &lt;/div&gt; &lt;table id="graphical_board"&gt; &lt;tbody&gt; &lt;?php foreach ( $graphical_board_array as $rank =&gt; $row ): ?&gt; &lt;tr&gt; &lt;?php foreach ( $row as $file =&gt; $column ): ?&gt; &lt;td id ="&lt;?php echo $column['id']; ?&gt;" class="&lt;?php echo $column['square_color']; ?&gt;" &gt; &lt;span class="draggable_piece" draggable="true" &gt; &lt;?php echo $column['piece']; ?&gt; &lt;/span&gt; &lt;/td&gt; &lt;?php endforeach; ?&gt; &lt;/tr&gt; &lt;?php endforeach; ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;!-- &lt;input type="submit" name="flip" value="Flip The Board" /&gt; --&gt; &lt;input type="button" onclick="window.location='.'" value="Reset The Board" /&gt; &lt;/div&gt; &lt;div&gt; &lt;form id="make_move"&gt; Legal Moves:&lt;br /&gt; &lt;select name="move" size="19"&gt; &lt;?php foreach ( $legal_moves as $key =&gt; $move ): ?&gt; &lt;option value="&lt;?php echo $move-&gt;board-&gt;fen; ?&gt;" data-coordinate-notation="&lt;?php echo $move-&gt;coordinate_notation; ?&gt;" &gt; &lt;?php echo $move-&gt;notation; ?&gt; &lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt;&lt;br /&gt; Move Count: &lt;?php echo count($legal_moves); ?&gt;&lt;br /&gt; &lt;?php $time = microtime(); $time = explode(' ', $time); $time = $time[1] + $time[0]; $finish = $time; $total_time = round(($finish - $start), 4); $total_time *= 1000; $total_time = round($total_time); ?&gt; Load Time: &lt;?php echo $total_time; ?&gt; ms&lt;br /&gt; &lt;input type="submit" value="Make Move" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;form id="import_fen"&gt; &lt;p&gt; FEN:&lt;br /&gt; &lt;input type="text" name="fen" value="&lt;?php echo $fen; ?&gt;" /&gt;&lt;br /&gt; &lt;input type="submit" value="Import FEN" /&gt; &lt;/p&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<h1>General Feedback</h1>\n\n<h2>Large Methods</h2>\n\n<p>Some of the class methods are really large - e.g. <code>ChessGame ::get_legal_moves_list()</code> which consumes ~150 lines. There is a lot of redundancy - especially in the code to assign <code>$directions_list</code>. That code should be mov...
{ "AcceptedAnswerId": "203576", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T23:27:27.553", "Id": "203324", "Score": "10", "Tags": [ "javascript", "php", "jquery", "css", "chess" ], "Title": "PHP Chess Version 2" }
203324
<p>I am learning C++ and I attempted to do one exercise I found: Dungeon Crawl. The goal of this game is to reach the treasure by moving your character along the board.</p> <p>The exercise asks not to use classes so I have tried to achieve some level of abstraction with <code>structs</code> and <code>arrays</code>. I have followed my university's style for comments.</p> <pre><code>#include &lt;climits&gt; #include &lt;ctime&gt; #include &lt;iostream&gt; #include &lt;random&gt; #include &lt;string&gt; /** * DUNGEON: a simple game for the terminal. The objective of the * game is that the player (&quot;P&quot;) reaches the treasure (&quot;X&quot;) * avoiding the traps (&quot;T&quot;) and the bandits (&quot;B&quot;). * Bandits move randomly each turn. * */ int NUMBEROFTRAPS = 3; int NUMBEROFBANDITS = 2; // Represents a place in the board. // xPosition is the x-axis index and yPosition is the y-axis index struct Location { int xPosition; int yPosition; }; // Represents the player. // It is guaranteed Player position is in the board. // Position is altered through function movePlayer. struct Player { Location position; char symbol = 'P'; std::string name = &quot;player&quot;; }; // Represents traps on the board // It is guarateed Trap position is in the board. struct Trap { Location position; char symbol = 'T'; }; // Represents Bandits moving around the map. // Position is altered through funtion moveBandit. struct Bandit { Location position; char symbol = 'B'; }; // Represents the treasure. // The game ends as soon Player.position == Treasure.position struct Treasure { Location position; char symbol = 'X'; }; // Represents the board. struct { int xDimension; int yDimension; } board = {.xDimension = 10, .yDimension = 10}; // Possible directions. WRONG_DIRECTION is used to report incorrect input enum Direction { RIGHT, LEFT, TOP, BOTTOM, WRONG_DIRECTION }; enum Result { VICTORY, DEFEAT }; void drawBoard(Player, Trap[], Bandit[], Treasure); void endGame(Result); void movePlayer(Player &amp;, Direction); void moveBandit(Bandit &amp;); Direction askDirection(); int main() { std::srand(std::time(0)); // Treasure position is decided randomly. Treasure treasure = { .position = {.xPosition = std::rand() % board.xDimension, .yPosition = std::rand() % board.yDimension}}; // Traps are placed around the map. It is not guaranteed // that traps position doesn't converge. // In that case, the second trap can be assumed to not exist. Trap trapsInMap[NUMBEROFTRAPS]; for (int i = 0; i &lt; NUMBEROFTRAPS; i++) { int xPos = std::rand() % board.xDimension; int yPos = std::rand() % board.yDimension; Trap trap = {.position = {.xPosition = xPos, .yPosition = yPos}}; trapsInMap[i] = trap; } // Bandits are placed around the map. It is not guaranteed // that bandits position doesn't converge, but they will move // anyway. Bandit banditsInMap[NUMBEROFBANDITS]; for (int i = 0; i &lt; NUMBEROFBANDITS; i++) { int xPos = std::rand() % board.xDimension; int yPos = std::rand() % board.yDimension; Bandit bandit = {.position = {.xPosition = xPos, .yPosition = yPos}}; banditsInMap[i] = bandit; } // Player position on the 1st turn is randomly decided. // It can not be the same of a bandit or a trap. bool match = false; int xPos; int yPos; do { xPos = std::rand() % board.xDimension; yPos = std::rand() % board.yDimension; for (int i = 0; i &lt; NUMBEROFTRAPS; i++) { if ((xPos == trapsInMap[i].position.xPosition &amp;&amp; yPos == trapsInMap[i].position.yPosition) || (xPos == banditsInMap[i].position.xPosition &amp;&amp; yPos == banditsInMap[i].position.yPosition)) { match = true; } } } while (match); Player player = {.position = {.xPosition = xPos, .yPosition = yPos}}; // The order of the turn is the following: // 1. Board is drawn. // 2. User is asked for movement direction. // 3. Player moves in the chosen direction. // 4. Bandits move. int maxTurnos = INT_MAX; for (int i = 0; i &lt;= maxTurnos; i++) { drawBoard(player, trapsInMap, banditsInMap, treasure); Direction direction; do { direction = askDirection(); std::cout &lt;&lt; std::endl; } while (direction == WRONG_DIRECTION); movePlayer(player, direction); for (int i = 0; i &lt; NUMBEROFBANDITS; i++) { moveBandit(banditsInMap[i]); } std::cout &lt;&lt; &quot;\x1B[2J\x1B[H&quot;; } } void drawBoard( /* in */ Player player, /* in */ Trap totalTraps[], /* in */ Bandit totalBandits[], /* in */ Treasure treasure) // Draws a (board.xDimension * board.yDimension) grid. // Elements are drawn using .location.?Dimensions. // Precondition: 0 &lt;= Player.xPosition &lt;= board.xDimension &amp;&amp; // 0 &lt;= player.position.yPosition &lt;= board.yDimension &amp;&amp; // board.xDimension &gt; 0 &amp;&amp; board.yDimension &gt; 0 &amp;&amp; // Postcondition: The grid has been drawn. // All elements have been drawn. // If the player is in the same square than the treasure, // the game ends with victory. // If the player is in the same square than a bandit or // a trap, the game ends with defeat. { bool squareDrawn = false; for (int y = 0; y &lt;= board.yDimension; y++) { for (int x = 0; x &lt;= board.xDimension; x++) { // Traps are drawn for (int z = 0; z &lt;= NUMBEROFTRAPS; z++) { Trap trapToDraw = totalTraps[z]; if (trapToDraw.position.xPosition == x &amp;&amp; trapToDraw.position.yPosition == y) { std::cout &lt;&lt; trapToDraw.symbol; squareDrawn = true; } } // Bandits are drawn. // In case of collision with a trap, // only the second is drawn. for (int z = 0; z &lt;= NUMBEROFBANDITS; z++) { Bandit banditToDraw = totalBandits[z]; if (banditToDraw.position.xPosition == x &amp;&amp; banditToDraw.position.yPosition == y &amp;&amp; !squareDrawn) { std::cout &lt;&lt; banditToDraw.symbol; squareDrawn = true; } } // Treasure is drawn. If position of treasure == position of player // game ends with victory if (x == treasure.position.xPosition &amp;&amp; y == treasure.position.yPosition) { if (treasure.position.xPosition == player.position.xPosition &amp;&amp; treasure.position.yPosition == player.position.yPosition) { endGame(VICTORY); } std::cout &lt;&lt; &quot;X&quot;; continue; } if (x == player.position.xPosition &amp;&amp; y == player.position.yPosition) { if (squareDrawn) endGame(DEFEAT); std::cout &lt;&lt; &quot;P&quot;; continue; } // Empty square &quot;.&quot; is drawn. It only gets printed if there is nothing // on the square. if (!squareDrawn) std::cout &lt;&lt; &quot;.&quot;; squareDrawn = false; } std::cout &lt;&lt; std::endl; } } Direction askDirection() { // Asks the user to input a direction and returns it. // Precondition: - // Poscondition: // Return: a Direction value containing the direction chosen or // WRONG_DIRECTION. std::cout &lt;&lt; &quot;Select [L]eft, [R]ight, [T]op or [B]ottom: &quot;; char answer; std::cin.get(answer); Direction chosenDirection; switch (std::toupper(answer)) { case 'L': chosenDirection = LEFT; break; case 'R': chosenDirection = RIGHT; break; case 'T': chosenDirection = TOP; break; case 'B': chosenDirection = BOTTOM; break; default: chosenDirection = WRONG_DIRECTION; } return chosenDirection; } void movePlayer( /* inout */ Player &amp;player, // Player of the game /* in */ Direction direction) // Direction previously chosen. // It is represented by a Direction object, // different from WRONG_DIRECTION. // Moves player in the chosen direction, by altering its coordinates. If the // player would finish out of the board, no movement is made. // Precondition: 0 &lt;= Player.xPosension &lt;= board.xDimension &amp;&amp; // 0 &lt;= player.position.yPosition &lt;= board.yDimension &amp;&amp; // board.xDimension &gt; 0 &amp;&amp; board.yDimension &gt; 0 &amp;&amp; // direction in {LEFT; RIGHT; TOP; BOTTOM} &amp;&amp; // Postcondition: player coordinates have been altered &amp;&amp; // player remains inside the board. { switch (direction) { case RIGHT: if (player.position.xPosition &lt; board.xDimension) player.position.xPosition += 1; break; case LEFT: if (player.position.xPosition &gt; 0) player.position.xPosition -= 1; break; case TOP: if (player.position.yPosition &gt; 0) player.position.yPosition -= 1; break; case BOTTOM: if (player.position.yPosition &lt; board.yDimension) player.position.yPosition += 1; break; } } void moveBandit( /* inout */ Bandit &amp;bandit) // Player of the game // It is represented by a Direction object, // different from WRONG_DIRECTION. // Moves player in the chosen direction, by altering its coordinates. If the // player would finish out of the board, no movement is made. // Precondition: 0 &lt;= Player.xPosension &lt;= board.xDimension &amp;&amp; // 0 &lt;= player.position.yPosition &lt;= board.yDimension &amp;&amp; // board.xDimension &gt; 0 &amp;&amp; board.yDimension &gt; 0 &amp;&amp; // direction in {LEFT; RIGHT; TOP; BOTTOM} &amp;&amp; // Postcondition: player coordinates have been altered &amp;&amp; // player remains inside the board. { int direction = std::rand() % 4; switch (direction) { case 0: if (bandit.position.xPosition &lt; board.xDimension) bandit.position.xPosition += 1; break; case 1: if (bandit.position.xPosition &gt; 0) bandit.position.xPosition -= 1; break; case 2: if (bandit.position.yPosition &gt; 0) bandit.position.yPosition -= 1; break; case 3: if (bandit.position.yPosition &lt; board.yDimension) bandit.position.yPosition += 1; break; } } void endGame( /* in */ Result result) // Result of the game. // It is either VICTORY or DEFEAT // Cleans screen, prints a good bye message // and ends the game. // Precondition: a condition for ending the game has been found. // Either player.position == bandit.position || // player.position == trap.position [DEFEAT] // or player.position == treasure.position [VICTORY] // Poscondition: game is ended. Greeting message is printed. { std::string announcement = (result == VICTORY) ? &quot;YOU WIN&quot; : &quot;GAME OVER&quot;; std::cout &lt;&lt; &quot;\x1B[2J\x1B[H&quot;; // Resets terminal std::cout &lt;&lt; std::endl &lt;&lt; std::endl; std::cout &lt;&lt; &quot;===========================&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;||\t\t\t||&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;||\t&quot; &lt;&lt; announcement &lt;&lt; &quot;\t\t||&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;||\t\t\t||&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;===========================&quot; &lt;&lt; std::endl; exit(1); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T20:52:29.890", "Id": "514366", "Score": "2", "body": "The moderator team has decided to let you remove the personal detail. However we (Code Review users) have no obligation to allow you to remove anything from your question. In the...
[ { "body": "<p>Overall, this is really well done. You've missed the usual traps of using magic numbers, not creating structures for related items, and other common things. So nice work! I think it could be improved with the following changes.</p>\n<p>#Types vs. Variables\nYou've created a type for <code>Location...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-07T23:39:57.977", "Id": "203325", "Score": "22", "Tags": [ "c++", "game", "console", "homework" ], "Title": "Dungeon Crawl game for the terminal" }
203325
<p><a href="https://pypi.org/project/Peertable/" rel="nofollow noreferrer">From the README:</a></p> <blockquote> <p>Welcome to Peertable! This project is an infrastructural peer-to-peer networking library for Python 3. You can also use it in standalone mode, although that is for little use other than connecting existing peers and networks (so they can find each other - but once they do, you don't need that anymore!).</p> </blockquote> <p>This project comes with two modes: standalone and library mode (although, since the standalone mode does little but connect existing nodes, we're focusing on the library mode here).</p> <p>This is an example of the standalone mode running:</p> <pre><code>$ python -i -m peertable Insert your new peer's listen port: (defaults to 2912) 2912 Insert your machine's public IP address (so others can connect to you, etc): localhost Insert this server's public port, in case you use a tunnel or port forward (or none otherwise): 2912 My port: 2912 My ID: p8vM6FqyBGzm0Sdnr6XCDoZdy Insert target IP:port address: &lt;other side IP here&gt; &gt;&gt;&gt; [c.id for c in s.clients] ['fc4h0MwGznaAqObYDWMXUiAAZ'] &gt;&gt;&gt; for c in s.clients: ... s.send_id(c.id, peertable.Message(True, "TESTMESG", "Hello! If you are reading this, then a human is behind the recipient peer of this message, i.e. YOU! Your ID: " + c.id)) </code></pre> <p>In this example, the other side would see:</p> <pre><code>&gt;+ + + + + Received message! Sender ID: p8vM6FqyBGzm0Sdnr6XCDoZdy Message type: TESTMESG Payload length: 135 Payload in Base64: SGVsbG8hIElmIHlvdSBhcmUgcmVhZGluZyB0aGlzLCB0aGVuIGEgaHVtYW4gaXMgYmVoaW5kIHRoZSByZWNpcGllbnQgcGVlciBvZiB0aGlzIG1lc3NhZ2UsIGkuZS4gWU9VISBZb3VyIElEOiBmYzRoME13R3puYUFxT2JZRFdNWFVpQUFa - - - - -&lt; </code></pre> <p>So, this is the code for the library itself:</p> <pre><code>import traceback import time import time import random import string import io import socket import warnings import struct import threading import requests class PeerApplication(object): def receive(self, server, client, message): pass def on_registered(self, server): pass def connected(self, server, client): pass def disconnected(self, server, client): pass class NCMHandler(object): MSG_TYPE = " " def __init__(self, server): self.server = server def handle(self, client, message): pass def should_handle(self, client, message): return message.message_type.upper()[:8].rstrip(' ') == type(self).MSG_TYPE.upper()[:8].rstrip(' ') class NCMDisconnectHandler(NCMHandler): MSG_TYPE = "EXITPEER" def handle(self, client, message): server.remove_id(client.id) for app in self.server.applications: app.disconnected(self.server, client) class NCMPathfindHandler(NCMHandler): MSG_TYPE = "PATHFIND" def handle(self, client, message): requester_ip, requester_port, request_id, target_id, closed = [x.decode('utf-8') for x in message.payload.split(b':')] closed = [x for x in closed.split('#') if x] closed.append(client.id) if self.server.id == target_id: self.server.connect((requester_ip, int(requester_port))) else: for c in self.server.clients: if c.id not in closed: c.send(Message(False, 'PATHFIND', '{}:{}:{}:{}:{}'.format(requester_ip, requester_port, request_id, target_id, '#'.join(closed)))) class NCMIdentifyHandler(NCMHandler): MSG_TYPE = "IDENTIFY" def handle(self, client, message): client.id = message.payload.decode('utf-8') class NCMRequestIdentifyHandler(NCMHandler): MSG_TYPE = "IDENTREQ" def handle(self, client, message): client.send(Message(False, "IDENTIFY", self.server.id)) class Message(object): def __init__(self, app_level, message_type, payload=b""): self.app_level = app_level self.message_type = message_type self.payload = payload if type(self.payload) is str: self.payload = payload.encode('utf-8') def serialize(self): message_type = self.message_type[:8] + " " * (8 - min(8, len(self.message_type))) return (b"Y" if self.app_level else b"N") + message_type.encode('utf-8') + struct.pack('Q', len(self.payload)) + self.payload class MessageDeserializer(object): def __init__(self): self.msg = io.BytesIO() def write(self, msg): pos = self.msg.tell() self.msg.write(msg) self.msg.seek(pos) def _read_one(self): appl = self.msg.read(1) if appl == b'': return app_level = appl == b"Y" if not app_level and appl != b"N": raise ValueError('Bad message received at {}: invalid ALM/NCM classification boolean byte! (expected Y (0x59) or N (0x4E), but got {} (0x{}))'.format(time.time(), appl, appl.hex().upper())) msg_type = self.msg.read(8).decode('utf-8') if len(msg_type) &lt; 8: raise ValueError("Bad message received at {}: insufficient characters for header - message too small! ({} bytes, minimum 17)".format(time.time(), 1 + len(msg_type))) payload_len = self.msg.read(8) if len(payload_len) &lt; 8: raise ValueError("Bad message received at {}: insufficient characters for header - message too small! ({} bytes, minimum 17)".format(time.time(), 9 + len(payload_len))) payload_len, = struct.unpack('Q', payload_len) payload = self.msg.read(payload_len) if len(payload) &lt; payload_len: self.msg.seek(self.msg.tell() - len(payload)) warnings.warn("Bad message received at {}: insufficient characters for payload - message too small! (expected {} payload bytes, got {})".format(time.time(), payload_len + len(payload))) return return Message(app_level, msg_type, payload) def __iter__(self): return self def __next__(self): try: r = self._read_one() if r is None: raise StopIteration return r except ValueError: traceback.print_exc() raise StopIteration class PeerClient(object): def __init__(self, server, address, _socket=None, id=None): self.server = server self.id = id self.deserializer = MessageDeserializer() if type(address) is str: self.address = tuple(address.split(':')[:2]) self.address = (self.address[0], int(self.address[1])) else: self.address = address self.socket = _socket if self.socket is None: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.connect(self.address) self.socket.setblocking(0) if self.id is None: self.send(Message(False, "IDENTREQ")) def disconnect(self): self.send(Message(False, "EXITPEER")) self.server.clients.remove(self) for app in self.server.applications: app.disconnected(self.server, self) def send(self, msg): data = msg.serialize() st = io.BytesIO(data) st.seek(0) try: while st.tell() &lt; len(data) - 1: self.socket.sendall(st.read(2048)) except ConnectionAbortedError: self.server.clients.remove(self) for app in self.server.applications: app.disconnected(self.server, self) def tick(self): try: data = self.socket.recv(2048) self._receive(data) except socket.error: pass def _receive(self, data): self.deserializer.write(data) self.server.on_receive(self) class RoutePending(object): def __init__(self, id, msg, target): self.id = id self.time = time.time() self.msg = msg self.target = target class PeerServer(object): DEFAULT_HANDLERS = (NCMDisconnectHandler, NCMIdentifyHandler, NCMPathfindHandler, NCMRequestIdentifyHandler) def __init__(self, my_addr, id=None, message_timeout=60, port=2912, remote_port=None): self.id = id if self.id is None: self.id = ''.join([random.choice(string.ascii_letters + string.digits) for _ in range(25)]) self.message_timeout = message_timeout self.clients = [] self.ncm_handlers = [d(self) for d in type(self).DEFAULT_HANDLERS] self.pending = [] self.applications = [] self.port = port self.remote_port = remote_port or port self.address = my_addr self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind(("0.0.0.0", port)) self.socket.listen(5) self.socket.setblocking(0) def register_app(self, app): self.applications.append(app) app.on_registered(self) def connect(self, address): self.clients.append(PeerClient(self, address)) def not_found(self, p): warnings.warn("Warning: route to {} not found! (pending message of PMID {})".format(p.target, p.id)) def send_id(self, id, msg): cn = tuple(self.clients) # &gt; here to prevent skipping clients that occupy # the slots of popped ones, in case any are # popped for c in cn: if c.id == id: # Client found; send and return. c.send(msg) return # Client was not found in local table. Time to pathfind. r = RoutePending(''.join([random.choice(string.ascii_letters + string.digits) for _ in range(50)]), msg, id) self.pending.append(r) m = Message(False, "PATHFIND", '{}:{}:{}:{}:'.format(self.address, self.remote_port, r.id, id)) for c in self.clients: c.send(m) def loop(self, ticks_per_second=60): _delay = 1 / ticks_per_second while True: self.tick() time.sleep(_delay) def start_loop(self): threading.Thread(target=self.loop).start() def tick(self): for p in self.pending: if p.target in [c.id for c in self.clients]: self.send_id(p.target, p.msg) self.remove_pending(p.id) elif time.time() - p.time &gt; self.message_timeout: self.not_found(p.id) self.remove_pending(p.id) for c in self.clients: c.tick() try: conn, addr = self.socket.accept() c = PeerClient(self, addr, conn) self.clients.append(c) for app in self.applications: app.connected(self, c) except socket.error: pass def disconnect(self): for c in self.clients: c.disconnect() def remove_id(self, id): self.clients = [c for c in self.clients if c.id != id] def remove_pending(self, id): self.pending = [p for p in self.pending if p.id != id] def on_receive(self, client): for msg in client.deserializer: if msg.app_level: for app in self.applications: app.receive(self, client, msg) else: for handler in self.ncm_handlers: if handler.should_handle(client, msg): handler.handle(client, msg) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T02:10:41.157", "Id": "203327", "Score": "1", "Tags": [ "python", "python-3.x", "networking", "library" ], "Title": "Peertable - an infrastructural peer-to-peer networking library" }
203327
<p>I'm trying to improve my dirty data wrangling code into something nice, readable &amp; reliable.</p> <p>I believe I've done fairly well here, although maybe I should have some docstrings on my functions. Still, I believe it's fairly readable without them.</p> <p>I'd love some feedback on ways to improve! This script parses raw data from <a href="ftp://svr-ftp.eng.cam.ac.uk/pub/comp.speech/dictionaries/moby/" rel="nofollow noreferrer">Gray Ward's fantastic public-domain thesaurus</a> into a more readable JSON file.</p> <pre><code>import sys import os import json # Parses Grady Ward's public-domain thesaurus, available at # ftp://svr-ftp.eng.cam.ac.uk/pub/comp.speech/dictionaries/moby/ def main(): database = {} if len(sys.argv) &lt; 3: print("Usage: make_database &lt;input filename&gt; &lt;ouput filename&gt;") sys.exit(1) filename = sys.argv[1] if not os.path.exists(filename): print(f"File {filename} doesn't exist.") sys.exit(1) # Read file into database with open(filename, "r") as file: try: parse_file(file, database) print("Finished reading the file.") except Exception as err: print(f"Failed to read file {filename} with error {err}") sys.exit(1) # Write database to output file as JSON output_filename = sys.argv[2] with open(output_filename, "w+") as file: try: data = json.dumps(database) file.write(data) print(f"Finished writing to file {output_filename}") except Exception as err: print(f"Failed to read write to file {output_filename} with error {err}") sys.exit(1) def parse_file(file, database): for line in file: (word, thesaurus) = parse_line(line) database[word] = thesaurus def parse_line(line): words = line.strip().split(",") return (words[0], words[1:]) if __name__ == '__main__': main() </code></pre> <p>I'm still a student -- I'm trying to improve my code readability &amp; maintainability.</p> <p>It is a commandline utility that can be called like:</p> <pre><code>make_database &lt;input filename&gt; &lt;output filename&gt; </code></pre>
[]
[ { "body": "<blockquote>\n <p>Welcome to Code Review!</p>\n</blockquote>\n\n<p>The current code looks clean enough. Since it will be a command line utility, I'd suggest taking up the <a href=\"https://devdocs.io/python~3.6/library/argparse\" rel=\"nofollow noreferrer\"><code>argparse</code></a> or <a href=\"htt...
{ "AcceptedAnswerId": "203341", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T06:20:04.083", "Id": "203333", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Converting raw thesaurus data into nice JSON file" }
203333
<p><strong>Disclaimer:</strong> The following question is not related to any malicious activity. Only performance testing we are doing. </p> <p>I am working on querying an internal server with lots of requests (~20 million).<br> I need it to be as fast as possible. </p> <p>How the algorithm works:</p> <ul> <li>30 Threads (because I found that more can slow it down) are running in the backgournd and checking a Queue.</li> <li>The <code>Queue</code> contains a list of strings that I am generating </li> <li>When a thread see that the Queue is not empty, it pull a string and using to send a <code>GET</code> request to the server.</li> <li>If some of the threads got a status code of <code>200</code> they will exit but my goal is to check the <strong>WORST CASE</strong> so in the example I am sending strings that will make a bad request (<code>404</code>) </li> </ul> <p>Notice that if I send my server 20 million requests asynchronically it might crash. This is why the use of only 30 threads and a Queue doesn't crash my server. </p> <p>Diagram: </p> <p><a href="https://i.stack.imgur.com/mE9Ui.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mE9Ui.png" alt="enter image description here"></a> The following is my code, I set <code>https://google.com</code> as the URL just for an example, <code>NUM_CONCURRENT_REQUESTS = 30</code> as the number of threads and <code>size = 100</code> is the size of requests I am sending - currently it just 100 for testing purpose.<br> My Code: </p> <pre><code>import time import urllib3 import queue import threading urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) https = urllib3.PoolManager() # Taken from https://stackoverflow.com/questions/18466079/can-i-change-the-connection-pool-size-for-pythons-requests-module def patch_https_connection_pool(**constructor_kwargs): """ This allows to override the default parameters of the HTTPConnectionPool constructor. For example, to increase the poolsize to fix problems with "HttpSConnectionPool is full, discarding connection" call this function with maxsize=16 (or whatever size you want to give to the connection pool) """ from urllib3 import connectionpool, poolmanager class MyHTTPSConnectionPool(connectionpool.HTTPSConnectionPool): def __init__(self, *args,**kwargs): kwargs.update(constructor_kwargs) super(MyHTTPSConnectionPool, self).__init__(*args,**kwargs) poolmanager.pool_classes_by_scheme['https'] = MyHTTPSConnectionPool patch_https_connection_pool(maxsize=160) def try_get_request(some_string): # I put google.com as an example but it is an internal server url = 'https://google.com/' + some_string r = https.request('GET', url, headers={ 'Content-Type': 'application/json' }) return r.status def queue_algo(): NUM_CONCURRENT_REQUESTS = 30 work = queue.Queue() global end_process end_process = False def worker(): global end_process #print('****** TID %s: STARTED ******' % threading.get_ident()) while not end_process: try: some_string = work.get(True, 3) #print("TID %s: Testing %s" % (threading.get_ident(), some_string)) status = try_get_request(some_string) #print("TID %s: DONE %s" % (threading.get_ident(), some_string)) if status == 200: print('found 200 status code') end_process = True work.task_done() else: continue except queue.Empty: continue work.task_done() threads = [] for unused_index in range(NUM_CONCURRENT_REQUESTS): thread = threading.Thread(target=worker) thread.daemon = True thread.start() threads.append(thread) queued = 0 wait = False try: # The strings I am sending size = 100 for i in range(0, size): work.put(str(i)) queued += 1 if queued &gt;= size: wait = True break if wait: while work.qsize() &gt; 0: time.sleep(5) end_process = True for thread in threads: if thread.is_alive(): thread.join() except KeyboardInterrupt: end_process = True for thread in threads: if thread.is_alive(): thread.join() start_time = time.time() queue_algo() print("--- %s seconds ---" % (time.time() - start_time)) </code></pre> <p>I wrote it in Python and I have been told that this is not the best solution for using threads.<br> I also tried with <code>Go</code> also I don't have here an example of the code.<br> The current stats on my internal server are 100,000 requests with 30 threads in 2.6 minutes.<br> This is too much, I need to do it much faster.<br> Because I can't share with you my internal server I put <code>https://google.com</code> as an example for URL that can test it to check the times. </p> <p>I wanted to know how you suggest to approach it ? Maybe the architecture of using threads with Queue is not the best and there is a better one. Maybe Python is not the language for such stuff because of the GIL mechanism that threads are not working as a "real" threads. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T08:15:19.303", "Id": "203336", "Score": "1", "Tags": [ "python", "performance", "multithreading" ], "Title": "Using multi-threading efficiently with million GET requests" }
203336
<p>I have solved the following problem using dynamic programming: <strong>Little Deepu and his Girlfriend</strong> <a href="https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/algorithm/little-deepu-and-his-girlfriend-2/" rel="nofollow noreferrer">1</a>. To paraphrase, </p> <blockquote> <p>We have two players Little Deepu and Kate and M items in the bag B, also we have a game set S with N elements, each element of game set is an integer. The game is played as follows, each player takes turn to pick an element from the game set S and removes that number of items from the bag, the player that is unable to remove the items from the bag looses the game. Little Deepu start the game ,If both Little Deepu and Kate play the game optimally, your task is to determine who wins the game.</p> </blockquote> <p><strong>Input:</strong> First line contains a integer T , number of test cases. Each test case contain two lines , first line contain two integer M and N and second line contain elements of S.</p> <p><strong>Output:</strong> For each test case print name of the winner of the game .</p> <p>Though correct, my solution is exceeding time limit for large inputs. Please tell me where I am going wrong.</p> <pre><code>def winner(n_i, n_t, t_k): output = [False]*(n_i + 1) for j in t_k: output[j ] = True print(output) for i in range(1, n_i + 1): if not output[j]: for j in t_k: if j &gt; i: continue val = output[i - j] if not val: output[i] = True break return 'Little Deepu' if output[n_i] else 'Kate' num_test = int(input()) for i in range(num_test): num_items,num_take_outs = map(int, input().split()) take_outs = list(map(int, input().split())) print(winner(num_items, num_take_outs, take_outs)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-25T13:25:07.963", "Id": "394014", "Score": "0", "body": "I'm not sure why this question is not well received. `time-limit-exceeded` is a valid concern for CodeReview which doesn't mean the code is broken." } ]
[ { "body": "<p>The key insight is that I didn't have to check if any of the choices made at current position, say x, from game set S lead to a position, say x -S<sub>i</sub> , that will guarantee a loss for the opponent.Rather for any position that leads to loss I had to mark all further positions reachable fro...
{ "AcceptedAnswerId": "203469", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T08:52:31.367", "Id": "203337", "Score": "-2", "Tags": [ "python", "programming-challenge", "time-limit-exceeded", "dynamic-programming" ], "Title": "Dynamic Programming solution for one pile nim game" }
203337
<p>I'm getting started with Android development. Take a look at this Android layout file:</p> <pre><code>&lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="@drawable/wallpaper"&gt; &lt;Button android:id="@+id/gameStartButton" android:text="Start" android:fontFamily="serif" android:textSize="30sp" android:textColor="@color/white" android:background="@color/metal" android:layout_width="match_parent" android:layout_margin="10dp" android:layout_height="@dimen/mainMenuItemWidth" android:onClick="chooseGameMode"/&gt; &lt;Button android:id="@+id/settingsButton" android:text="Settings" android:fontFamily="serif" android:textSize="30sp" android:textColor="@color/white" android:background="@color/metal" android:layout_width="match_parent" android:layout_margin="10dp" android:layout_height="@dimen/mainMenuItemWidth" android:onClick="openSettings"/&gt; &lt;Button android:id="@+id/exitButton" android:text="Quit" android:fontFamily="serif" android:textSize="30sp" android:textColor="@color/white" android:background="@color/metal" android:layout_width="match_parent" android:layout_margin="10dp" android:layout_height="@dimen/mainMenuItemWidth" android:onClick="closeApp"/&gt; &lt;/LinearLayout&gt; </code></pre> <p>All three buttons have exactly the same dimensions, margins and color. As a result, this layout file appears needlessly verbose. Is is possible to extract this common information somewhere else so that it could be reused?</p> <p>One way could be to subclass <code>Button</code> with specific features and use it instead of the stock button. Is there any other way? What I'm trying to achieve is simple attribute sharing and it shouldn't require dropping down to Java.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T22:37:40.997", "Id": "391986", "Score": "0", "body": "Have you looked into [styles](https://www.tutorialspoint.com/android/android_styles_and_themes.htm \"styles\")?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T09:57:38.783", "Id": "203338", "Score": "1", "Tags": [ "android", "xml", "layout" ], "Title": "Making a lot of similar looking views in Android layouts" }
203338
<p>In some components and services I need the <code>window</code> and <code>document</code>. So I created a small service, that provides these two objects.</p> <p><strong>windowAndDocument.service.ts</strong>:</p> <pre><code>import { Inject, Injectable } from '@angular/core'; import { DOCUMENT } from '@angular/common'; function getWindow (): any { return window; } @Injectable({ providedIn: 'root', }) export class WindowAndDocumentService { public window = null; constructor(@Inject( DOCUMENT ) public document :HTMLDocument) { this.window = getWindow(); } } </code></pre> <p>This works fine and can be imported into other services.</p> <p><strong>some.service.ts:</strong></p> <pre><code>import { Injectable } from '@angular/core'; import { WindowAndDocumentService } from './windowAndDocument.service'; @Injectable({ providedIn: 'root', }) export class SomeService { constructor(private wads: WindowAndDocumentService) {} soSomething() { console.log(this.wads.window); console.log(this.wads.document.doctype); } } </code></pre> <hr> <p>My questions are:</p> <ul> <li>Is this the optimal way to provide <code>window</code> and <code>document</code>?</li> <li>Can this be written more concisely? I find it kind of odd, that one variable is injected and the other is pulled from a function call.</li> </ul> <hr> <p>It's a given that the app runs in the browser.</p>
[]
[ { "body": "<p>Assuming you want a SOLID code and keep the single responsibility principle, you would need to inject window and document separately.\nA clean way is to provide each of them using the <code>useValue</code> property of your provider:</p>\n\n<pre><code>@NgModule({\n declarations: [...],\n imports:...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T11:51:53.257", "Id": "203340", "Score": "1", "Tags": [ "typescript", "angular-2+" ], "Title": "An Angular service to provide window and document objects" }
203340
<p>A while ago a tricky C++ interview question came across to me, and ever since I could not tell what I did wrong.</p> <blockquote> <p>Create a base class named “Shape” with a method to return the area of the shape. Create a class named “Triangle” derived from the base class “Shape”.</p> <p>Class “Triangle” must have two constructors. One receives the length of the (a) side of the triangle and the related (ma) height. The other receives the length of (a),(b),(c) sides of the triangle. In the second case, the constructor must validate the input by checking that the length of one side is smaller than the sum of the lengths of the other two sides. If the input is invalid, it should throw an exception. Implement the method (available in the base class) that calculates the area of the triangle on the basis of the available data. </p> <p>You can use two formulas. If the length of a side and height is given: <code>T=(a*ma)/2</code>. If the lengths of the three sides are given, you can use the Heron formula: <code>sqrt(s*(s-a)*(s-b)*(s-c))</code> where <code>s=(a+b+c)/2</code></p> </blockquote> <p>This should be obvious for any candidate. It clearly asks if you know what the base principles of OOP is, and if you can solve a bit complex problem with it. Before I could just jump into it, I found something odd. The assessment requires you to create some class that behaves differently as they've created. It asks you to use some trickery to solve this problem.</p> <p>Well, I, who read a bit about what SOLID is, and familiar with design patterns were trivial that using polymorphism is the way to solve this the most elegant way. My approach was something like this:</p> <ul> <li>Create the base class</li> <li>Create the derived class </li> <li>Use the derived class constructor as an <em>abstract factory</em> for a <em>composite</em> type, and make the implementation to act as a <em>proxy</em> toward the different implementations</li> <li>Create two other classes which handles the actual data and takes care of the calculation</li> <li>Take care of the exceptions using std::exception - these are tricky as well in C++</li> <li>Take care of the implementation</li> </ul> <p>In the end my solution looked like this:</p> <pre><code>#include &lt;exception&gt; #include &lt;string&gt; #include &lt;cmath&gt; class Shape { public: virtual double Area() = 0; }; class Exception : public std::exception { public: Exception(std::string const &amp;message) throw() : m_msg(message) {} ~Exception() throw() {} virtual char const *what() const _NOEXCEPT { return m_msg.c_str(); } private: std::string m_msg; }; class Triangle : public Shape { class TriangleSides; class TriangleBase; public: Triangle(double base, double height); Triangle(double a, double b, double c); ~Triangle(); double Area() override; private: Shape *m_shape; class TriangleSides : public Shape { public: TriangleSides(double a, double b, double c); double Area() override; private: double m_a, m_b, m_c; }; class TriangleBase : public Shape { public: TriangleBase(double base, double height); double Area() override; private: double m_base, m_height; }; }; Triangle::Triangle(double base, double height) : m_shape(nullptr) { m_shape = new Triangle::TriangleBase(base, height); } Triangle::Triangle(double a, double b, double c) : m_shape(nullptr) { if (a + b &lt;= c || a + c &lt;= b || b + c &lt;= a) throw Exception("Any two sides of a triangle must be longer than one"); m_shape = new Triangle::TriangleSides(a, b, c); } Triangle::~Triangle() { delete m_shape; } double Triangle::Area() { if (m_shape) return m_shape-&gt;Area(); else return 0; } Triangle::TriangleSides::TriangleSides(double a, double b, double c) : m_a(a), m_b(b), m_c(c) { } double Triangle::TriangleSides::Area() { const double s = (m_a + m_b + m_c) * .5; return sqrt(s * (s - m_a) * (s - m_b) * (s - m_c)); } Triangle::TriangleBase::TriangleBase(double base, double height) : m_base(base), m_height(height) { } double Triangle::TriangleBase::Area() { return .5 * (m_base * m_height); } </code></pre>
[]
[ { "body": "<p>I see some things that may help you improve your code.</p>\n\n<h2>Don't overcomplicate your code</h2>\n\n<p>The only thing required of the <code>Shape</code> and <code>Triangle</code> classes is the calculation of area. For that reason, the code can be considerably simplified if the constructor c...
{ "AcceptedAnswerId": "203451", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T13:50:43.377", "Id": "203345", "Score": "9", "Tags": [ "c++", "object-oriented", "interview-questions", "polymorphism" ], "Title": "Area calculator for shapes as an OOP interview test" }
203345
<p>The task is for training go-lang. The idea is to extract unique words sorted and grouped by length. Might be useful in learning new words. The program uses command line argument assuming it's a file to read; reads from stdin if no arguments were given. </p> <pre><code>package main import ( "bufio" "fmt" "os" "regexp" "sort" "strings" ) type words = map[string]struct{} type groupedWords = map[int]words // Checks for fatal errors. // If non nil error passed program will be terminated func check(e error) { if e != nil { panic(e) } } // Reads data from bufio.Reader and returns // a map of grouped unique words: key is letters count, value is map of words func getGroupedWords(reader *bufio.Reader) groupedWords { groupedWords := make(groupedWords) re, err := regexp.Compile("[^a-zA-Z]") check(err) for { str, err := reader.ReadString(' ') str = strings.ToLower(strings.TrimSpace(str)) if !re.MatchString(str) { val, exists := groupedWords[len(str)] if !exists { groupedWords[len(str)] = words{str: struct{}{}} } else { val[str] = struct{}{} } } if err != nil { break } } delete(groupedWords, 0) return groupedWords } // Extracts sorted slice of keys from words func getSortedKeysWord(w words) []string { list := make([]string, len(w)) i := 0 for word := range w { list[i] = word i++ } sort.Strings(list) return list } // Extracts sorted slice of letters count from groupedWords func getSortedKeysGroupedWord(gw groupedWords) []int { list := make([]int, len(gw)) i := 0 for lettersCnt := range gw { list[i] = lettersCnt i++ } sort.Ints(list) return list } func main() { var reader *bufio.Reader args := os.Args if len(args) == 1 { reader = bufio.NewReader(os.Stdin) } else { file, err := os.Open(args[1]) check(err) reader = bufio.NewReader(file) } groupedWords := getGroupedWords(reader) lettersCntList := getSortedKeysGroupedWord(groupedWords) for _, lettersCnt := range lettersCntList { list := getSortedKeysWord(groupedWords[lettersCnt]) fmt.Print(lettersCnt, "(", len(list), "):\t") for _, word := range list { fmt.Print(word, " ") } fmt.Println() } } </code></pre> <p>usage</p> <pre><code>echo "The unary notation can be abbreviated by introducing different symbols for certain new values. " | go run extract_words.go </code></pre> <p>should give </p> <pre><code>2(2): be by 3(3): can for new 5(1): unary 7(2): certain symbols 8(1): notation 9(1): different 11(2): abbreviated introducing </code></pre>
[]
[ { "body": "<p>This program could be improved by using more specific tools from the standard Library</p>\n\n<h2>Use a Scanner</h2>\n\n<p>The best way to extract words from a text is to use a <code>bufio.Scanner</code> with the split function <code>bufio.ScanWords</code> ( see this <a href=\"https://golang.org/pk...
{ "AcceptedAnswerId": "203377", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T16:11:24.423", "Id": "203349", "Score": "1", "Tags": [ "go", "mapreduce" ], "Title": "Extract unique words from given text and group by letter count" }
203349
<p>I wrote a program for solving the <a href="https://www.hackerrank.com/challenges/attribute-parser/problem" rel="nofollow noreferrer">Attribute Parser challenge on HackerRank</a>. The challenge is to read some specified number of lines of HTML-like markup (each line no more than 200 characters; for any attributes, the <code>=</code> sign will be preceded and followed by a space), and perform some specified number of attribute queries (each query no more than 200 characters).</p> <h3>Sample Input</h3> <pre class="lang-none prettyprint-override"><code>4 3 &lt;tag1 value = "HelloWorld"&gt; &lt;tag2 name = "Name1"&gt; &lt;/tag2&gt; &lt;/tag1&gt; tag1.tag2~name tag1~name tag1~value </code></pre> <h3>Sample Output</h3> <pre class="lang-none prettyprint-override"><code>Name1 Not Found! HelloWorld </code></pre> <p>All comments and suggestions are welcome and appreciated.</p> <hr> <pre><code>#include&lt;iostream&gt; #include&lt;string&gt; #include&lt;vector&gt; #include&lt;climits&gt; #include&lt;algorithm&gt; #include&lt;map&gt; #include&lt;sstream&gt; enum TagType { OPENING_TAG, CLOSING_TAG }; class Tag { private: std::string tag_name; std::map&lt;std::string, std::string&gt; attributes; TagType type; public: Tag(const std::string); std::string search_for_attribute(const std::string); TagType get_type(); std::string get_name(); }; std::vector&lt;std::string&gt; tokenize_string(const std::string string, const std::string delimiters) { std::stringstream stream(string); std::string line; std::vector&lt;std::string&gt; result; while (std::getline(stream, line)) { std::size_t previous = 0, pos; while ((pos = line.find_first_of(delimiters, previous)) != std::string::npos) { if (pos &gt; previous) result.push_back(line.substr(previous, pos - previous)); previous = pos + 1; } if (previous &lt; line.length()) result.push_back(line.substr(previous, std::string::npos)); } return result; } /* * Maps the tag to its level of nesting. 0 - outermost tag, above 0 - nesting level * Returns a map containing the tag name as a key, and it's nesting level as a value */ std::map&lt;std::string, int&gt; map_tag_depths(std::vector&lt;Tag&gt;&amp; tags) { int current_level = -1; std::map&lt;std::string, int&gt; tag_depths; for (auto tag : tags) { if (tag.get_type() == OPENING_TAG) { current_level++; tag_depths.insert(std::make_pair(tag.get_name(), current_level)); } else { current_level--; } } return tag_depths; } Tag::Tag(const std::string line) { std::vector&lt;std::string&gt; tokens = tokenize_string(line,"&lt; =\"/&gt;"); this-&gt;tag_name = tokens[0]; for (auto it = tokens.begin() + 1; it != tokens.end(); it += 2) { attributes.insert(std::make_pair(*it, *(it + 1))); } type = (line[1] == '/') ? CLOSING_TAG : OPENING_TAG; } std::string Tag::search_for_attribute(const std::string attribute_name) { auto iterator = this-&gt;attributes.find(attribute_name); if (iterator != attributes.end()) return iterator-&gt;second; else { return "Not Found!"; } } TagType Tag::get_type() { return this-&gt;type; } std::string Tag::get_name() { return tag_name; } void process_queries(std::vector&lt;Tag&gt;&amp; tags, std::vector&lt;std::string&gt;&amp; queries) { std::map&lt;std::string, int&gt; tag_depths = map_tag_depths(tags); for (auto query : queries) { std::vector&lt;std::string&gt; query_tokens = tokenize_string(query,".~"); bool path_found = true; //Check if the path is valid for (int i = 0; i &lt; query_tokens.size() - 1; i++) { auto it = tag_depths.find(query_tokens[i]); if (it == tag_depths.end() || it-&gt;second != i) path_found = false; } if (path_found) { //We know that the path is correct, so we can use //the tag name referenced last by the query std::string tag_name = query_tokens[query_tokens.size() - 2]; //Name of the attribute in the query std::string attribute_name = query_tokens[query_tokens.size() - 1]; //Find the tag for (auto it = tags.begin(); it != tags.end(); it++) { if (it-&gt;get_name() == tag_name) { std::cout &lt;&lt; it-&gt;search_for_attribute(attribute_name)&lt;&lt;'\n'; break; } } } else std::cout &lt;&lt; "Not Found!\n"; } } int main() { int N, Q; std::cin &gt;&gt; N &gt;&gt; Q; std::cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n'); std::vector&lt;Tag&gt; tags; while (N--) { std::string line; std::getline(std::cin, line); Tag current_tag(line); tags.push_back(current_tag); } std::vector&lt;std::string&gt; queries; while (Q--) { std::string query; std::cin &gt;&gt; query; queries.push_back(query); } process_queries(tags, queries); return 0; } </code></pre>
[]
[ { "body": "<p>Wonderful Mate. Very neatly written. \nI understood it while debugging it myself but will be great for others if you could add few comments as well around the conditions so that its more easier to understand for everyone.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T17:32:05.500", "Id": "203355", "Score": "4", "Tags": [ "c++", "programming-challenge", "parsing", "xml" ], "Title": "HackerRank Attribute Parser" }
203355
<p>I'm working on a nice approximation for the Bilateral Filter.<br> I have a working code which runs pretty fast yet still I think much can be improved.</p> <p>The code (<code>C</code> Code, compiles with <code>C99</code>) is given by (See code on <a href="https://godbolt.org/z/90d7vz" rel="nofollow noreferrer">Compiler Explorer</a>):</p> <pre><code>#define _USE_MATH_DEFINES #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;memory.h&gt; #include &lt;omp.h&gt; #define OFF 0 #define ON 1 #include &lt;immintrin.h&gt; // AVX #define SSE_STRIDE 4 #define SSE_ALIGNMENT 16 #define AVX_STRIDE 8 #define AVX_ALIGNMENT 32 #define M_PIf (float)(M_PI) void ImageConvolutionGaussianKernel(float* mO, float* mI, float* mTmp, int numRows, int numCols, float gaussianStd, int stdToRadiusFactor); void InitOmegaArrays(float* mCOmega, float* mSOmega, float* mI, int numRows, int numCols, float paramOmega); void UpdateArrays(float* mO, float* mZ, float* mC, float* mS, float* mCFiltered, float* mSFiltered, int numRows, int numCols, int iterationIdx, float paramD); void InitArraysSC(float* mC, float* mS, float* mCOmega, float* mSOmega, int numRows, int numCols); void UpdateArraysSC(float* mC, float* mS, float* mCOmega, float* mSOmega, int numRows, int numCols); void UpdateOutput(float* mO, float* mZ, float* mI, int numRows, int numCols, float rangeStd, float paramL); void BilateralFilterFastCompressive(float* mO, float* mI, int numRows, int numCols, float spatialStd, float rangeStd, int paramK) { int ii, paramN; float paramL, paramTau, *vParamD, *mZ, *mT, paramOmega, *mCOmega, *mSOmega, *mC, *mS, *mCFiltered, *mSFiltered; mZ = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); // Should be initialized to Zero mT = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); // Buffer mC = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); mS = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); mCOmega = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); mSOmega = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); mCFiltered = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); mSFiltered = (float*)_mm_malloc(numRows * numCols * sizeof(float), AVX_ALIGNMENT); memset(mZ, 0.0f, numRows * numCols * sizeof(float)); // Init Parameters paramL = paramK * rangeStd; paramTau = paramK / M_PIf; paramN = ceilf((paramK * paramK) / M_PIf); paramOmega = M_PIf / paramL; vParamD = (float*)_mm_malloc(paramN * sizeof(float), AVX_ALIGNMENT); for (ii = 1; ii &lt;= paramN; ii++) { vParamD[ii - 1] = 2 * expf(-(ii * ii) / (2 * paramTau * paramTau)); } InitOmegaArrays(mCOmega, mSOmega, mI, numRows, numCols, paramOmega); // Iteration Number 1 ii = 1; ImageConvolutionGaussianKernel(mCFiltered, mCOmega, mT, numRows, numCols, spatialStd, paramK); ImageConvolutionGaussianKernel(mSFiltered, mSOmega, mT, numRows, numCols, spatialStd, paramK); UpdateArrays(mO, mZ, mCOmega, mSOmega, mCFiltered, mSFiltered, numRows, numCols, ii, vParamD[ii - 1]); // Iteration Number 2 ii = 2; InitArraysSC(mC, mS, mCOmega, mSOmega, numRows, numCols); ImageConvolutionGaussianKernel(mCFiltered, mC, mT, numRows, numCols, spatialStd, paramK); ImageConvolutionGaussianKernel(mSFiltered, mS, mT, numRows, numCols, spatialStd, paramK); UpdateArrays(mO, mZ, mC, mS, mCFiltered, mSFiltered, numRows, numCols, ii, vParamD[ii - 1]); for (ii = 3; ii &lt;= paramN; ii++) { UpdateArraysSC(mC, mS, mCOmega, mSOmega, numRows, numCols); ImageConvolutionGaussianKernel(mCFiltered, mC, mT, numRows, numCols, spatialStd, paramK); ImageConvolutionGaussianKernel(mSFiltered, mS, mT, numRows, numCols, spatialStd, paramK); UpdateArrays(mO, mZ, mC, mS, mCFiltered, mSFiltered, numRows, numCols, ii, vParamD[ii - 1]); } UpdateOutput(mO, mZ, mI, numRows, numCols, rangeStd, paramL); _mm_free(mZ); _mm_free(mT); _mm_free(mC); _mm_free(mS); _mm_free(mCOmega); _mm_free(mSOmega); _mm_free(mCFiltered); _mm_free(mSFiltered); _mm_free(vParamD); } // Auxiliary Functions void InitOmegaArrays(float* mCOmega, float* mSOmega, float* mI, int numRows, int numCols, float paramOmega) { int ii; for (ii = 0; ii &lt; numRows * numCols; ii++) { mCOmega[ii] = cosf(paramOmega * mI[ii]); mSOmega[ii] = sinf(paramOmega * mI[ii]); } } void UpdateArrays(float* mO, float* mZ, float* mC, float* mS, float* mCFiltered, float* mSFiltered, int numRows, int numCols, int iterationIdx, float paramD) { int ii; for (ii = 0; ii &lt; numRows * numCols; ii++) { mO[ii] += (iterationIdx * paramD) * (mC[ii] * mSFiltered[ii] - mS[ii] * mCFiltered[ii]); mZ[ii] += paramD * (mC[ii] * mCFiltered[ii] + mS[ii] * mSFiltered[ii]); } } void InitArraysSC(float* mC, float* mS, float* mCOmega, float* mSOmega, int numRows, int numCols) { int ii; for (ii = 0; ii &lt; numRows * numCols; ii++) { mS[ii] = 2.0f * mCOmega[ii] * mSOmega[ii]; mC[ii] = 2.0f * mCOmega[ii] * mCOmega[ii] - 1.0f; } } void UpdateArraysSC(float* mC, float* mS, float* mCOmega, float* mSOmega, int numRows, int numCols) { int ii; float varTmp; for (ii = 0; ii &lt; numRows * numCols; ii++) { varTmp = mC[ii] * mSOmega[ii] + mS[ii] * mCOmega[ii]; mC[ii] = mC[ii] * mCOmega[ii] - mS[ii] * mSOmega[ii]; mS[ii] = varTmp; } } void UpdateOutput(float* mO, float* mZ, float* mI, int numRows, int numCols, float rangeStd, float paramL) { int ii; float outFactor; outFactor = (M_PIf * rangeStd * rangeStd) / paramL; for (ii = 0; ii &lt; numRows * numCols; ii++) { mO[ii] = mI[ii] + (outFactor * (mO[ii] / (1.0f + mZ[ii]))); } } </code></pre> <p>Basically few iterations of Gaussian Blur and Element Wise operations. </p> <p>I'm testing the code on image of size <code>8000 x 8000</code> with <code>spatialStd = 5</code>, <code>rangeStd = 10 / 255</code> and <code>paramK = 5</code>.<br> This set of parameters means the number of iterations (<code>paramN</code> in the code) is 8 (Gaussian Blur is done twice per iteration).<br> My <a href="https://codereview.stackexchange.com/questions/172157">Gaussian Blur implementation</a> takes ~0.18 [Sec] per iteration in the settings above when tested independently. </p> <p>The issues I'm having with the code:</p> <ol> <li>Per iteration, it seems the time all Element Wise operations takes more than the Gaussian Blur. It seems to me something isn't efficient with the code.</li> <li>Overhead - If I run the code skipping the Gaussian Blur it takes ~1.8 [Sec]. Thinking that 16 x 0.18 = 2.88 [Sec] (16 iterations of the Gaussian Blur) means I should expect run time of ~5 [Sec]. In practice I get ~ 7 [Sec]. It means there is huge overhead somewhere there.</li> </ol> <p>What I've tried:</p> <ol> <li>Writing all small function using <a href="https://stackoverflow.com/questions/52227549">AVX2 SIMD intrinsics</a>. Yet it seems I gain only 3-5% over the compiler (I use Intel Compiler).</li> <li>Using the <code>#pragma vector aligned</code> to force compiler to vectorize the code and assume no aliasing and no alignment issues. It yields results which are 3-5% slower than the hand tuned I did (See 1).</li> <li>Disabling OpenMP (Didn't improve).</li> <li>Various compilers (MSVC, GCC 7.3 / 8.1, Intel Compiler 2018 [Was best]). Results above are the best achieved (Intel Compiler). I tried <code>-Ofast</code> and <code>-O3</code> on GCC. Using <code>O3</code> on Intel. FP Precision is set to fast.</li> </ol> <p>I'd be happy to get some feedback on that.</p> <p><strong>Remark</strong><br> The code is part of a work at University and will be published on GitHub once it is ready.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T20:43:10.223", "Id": "391964", "Score": "0", "body": "`UpdtaeOutput` has a typo in the function name. `ImageConvolutionGaussianKernel` doesn't seem to be defined anywhere, so I couldn't look at how the whole thing compiles." }, ...
[ { "body": "<p>the posted code does not compile! Please post code that compiles. When compiling, always enable the warnings, then fix those warnings. (for <code>gcc</code>, at a minimum use: <code>-Wall -Wextra -Wconversion -pedantic -std=gnu17</code> ) Note, other compilers have a different set of options t...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-08T18:16:40.137", "Id": "203356", "Score": "3", "Tags": [ "performance", "c", "memory-optimization", "vectorization", "simd" ], "Title": "Optimizations of C Code - Bilateral Filter" }
203356