body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>This is a basic implementation of Dijkstra's Shortest Path Algorithm for Graphs. I am looking for any kind of improvement.</p>
<pre><code>/*
Author: Stevan Milic
Date: 10.05.2018.
Dijkstra's Shortest Path Algorithm
*/
#include <stdio.h>
#include <limits.h>
#include <iostream>
#define N 9 // Number of Nodes in the graph
int minDistance(int distance[], bool visitedSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < N; v++)
if (visitedSet[v] == false && distance[v] <= min)
min = distance[v], min_index = v;
return min_index;
}
void displayPath(int parent[], int s)
{
if (parent[s] == -1)
return;
displayPath(parent, parent[s]);
printf("-> %d ", s);
}
void display(int distance[], int n, int parent[])
{
int start = 0;
printf("Node\t Distance\t Path");
for (int i = 1; i < N; i++)
{
printf("\n%d -> %d\t\t%d\t\t%d ", start, i, distance[i], start);
displayPath(parent, i);
}
}
void dijkstra(int graph[N][N], int start)
{
int distance[N];
bool visitedSet[N];
int parent[N]; // For storing the shortest path tree
for (int i = 0; i < N; i++) // This will make all distances as infinite and all nodes as unvisited
{
parent[0] = -1;
distance[i] = INT_MAX;
visitedSet[i] = false;
}
distance[start] = 0;
for (int count = 0; count < N - 1; count++) // Finding the shortest path for all nodes
{
int u = minDistance(distance, visitedSet);
visitedSet[u] = true;
for (int n = 0; n < N; n++)
if (!visitedSet[n] && graph[u][n] && distance[u] + graph[u][n] < distance[n])
{
parent[n] = u;
distance[n] = distance[u] + graph[u][n];
}
}
display(distance, N, parent);
}
int main()
{
printf("***** Dijkstra's Shortest Path Algorithm ***** \n\n");
int graph[N][N] = { {0, 4, 0, 0, 0, 0, 0, 8, 0 },
{4, 0, 8, 0, 0, 0, 0, 11, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 2 },
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 0, 10, 0, 2, 0, 0},
{0, 0, 0, 14, 0, 2, 0, 1, 6},
{8, 11, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
printf("\n\n");
system("pause");
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T22:33:17.000",
"Id": "425372",
"Score": "2",
"body": "Removing unnecessary include, system call and including stdbool allows C compiler to compile this. Perhaps slightly modifying the code and retagging it as C will result in reviews that you are interested in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:04:46.197",
"Id": "425373",
"Score": "1",
"body": "`stdio.h` and `limits.h` are not C++ headers. And you don’t use anything in the C++ standard library or any language features that distinguish it from C. Why tag this C++?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:05:27.590",
"Id": "425550",
"Score": "0",
"body": "Dijkstra usually finds a path from A to B. That's not what you are doing. You are annotating the graph with min distances from A. Also Dijkstra algorithm has a couple of properties that you normally associated with it that don't seem to be included (a done list and frontier list). So I think you need to re-name your algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:06:22.810",
"Id": "425551",
"Score": "0",
"body": "Have a look at: https://stackoverflow.com/a/3448361/14065"
}
] | [
{
"body": "<p>The <code><iostream></code> header is not used.</p>\n\n<p><code>min_distance</code> can <em>theoretically</em> return an uninitialized value if all elements of <code>visited_set</code> are nonzero. This shouldn't happen here, but initializing <code>min_index = 0</code> would remove a potential problem and compiler warning.</p>\n\n<p><code>display</code> assumes that node 0 is the start node, but that value is passed in to <code>dijkstra</code>. It should be passed in as a parameter.</p>\n\n<p>In <code>dijkstra</code>, the <code>graph</code> parameter could be <code>const int graph[N][N]</code>, which would then allow the <code>graph</code> variable in <code>main</code> to also be const. The <code>parent[0] = -1</code> assignment seems to be a typo. It should be <code>parent[i] = -1;</code> to initialize all elements of <code>parent</code>. The <code>for (int n = 0; n < N; n++)</code> loop should have curly brackets around its body. While not currently necessary, having them in can avoid future problems when the code is modified and makes it clearer what is in the loop body rather than looking like a line with bad indentation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T00:55:28.623",
"Id": "220161",
"ParentId": "220156",
"Score": "4"
}
},
{
"body": "<h3>Overview</h3>\n<p>Terrible C++ but OK C.</p>\n<p>Modern C++ has a completely different style when used to what you have written here. Though perfectly legal C++ this is not what you would expect to see and this makes it harder to maintain and implement.</p>\n<h3>Improvements</h3>\n<p>You tightly bind your interface to a specific implementation (an Array of Arrays of distance). You should abstract your design so that the algorithm can be applied to any type that matches the interface.</p>\n<p>There are lots of standard types that would help you in this implementation. You should have a look to see what is useful</p>\n<h3>Efficiency</h3>\n<p>There are some definite improvements in efficiency that you can implement here. Your current algorithm is at least <code>O(N^2)</code> could be worse but I stopped looking. I would probably want it to be <code>O(n.log(n))</code>.</p>\n<h3>Code Review</h3>\n<p>These are C headers</p>\n<pre><code>#include <stdio.h> \n#include <limits.h> \n</code></pre>\n<p>C++ has its own set of headers use them (cstdio and climits). They put all the functions correctly into the standard namespace (<code>std::</code>).</p>\n<p>Don't include headers you don't need:</p>\n<pre><code>#include <iostream>\n</code></pre>\n<p>BUT you should need it.Prefer the C++ streams to the C io interface because of its type safety.</p>\n<hr />\n<p>Avoid macros:</p>\n<pre><code>#define N 9 // Number of Nodes in the graph\n</code></pre>\n<p>All (most) the use of macros have better alternatives in C++. Macros should be reserved for what they are good at (identifying platform dependencies and providing the appropriate different functionalities for these platforms). Unless you are writing low level platform independent code you should not be touching these.</p>\n<pre><code>constepxr int N = 9; // N is a terrible name (find a better one).\n</code></pre>\n<hr />\n<p>This is your main issue in complexity.</p>\n<pre><code>int minDistance(int distance[], bool visitedSet[])\n{\n for (int v = 0; v < N; v++) // Loop over all the nodes.\n ...\n return min_index;\n}\n</code></pre>\n<p>You are doing a full sweep of all the nodes each time. If you had simply used a form of sorted list (as the algorithm tells you) then you reduce the overall complexity a lot.</p>\n<hr />\n<p>Stop abusing the comma operator. It's not cool.</p>\n<pre><code> int min = INT_MAX, min_index; // Not technically the comma operator but same principle.\n\n min = distance[v], min_index = v;\n</code></pre>\n<p>The point of writing code in a high level language is so that it is easy for other humans to understand. By cramming everything on one line you are doing the exact opposite (making it hard to read and therefore understand and therefore maintain).</p>\n<p>Every coding standard I have ever read is one variable modification per line. One declaration per line. It does not hurt to use an extra line here.</p>\n<hr />\n<p>Prefer to always put sub blocks inside '{}`</p>\n<pre><code>for (int v = 0; v < N; v++)\n if (visitedSet[v] == false && distance[v] <= min)\n min = distance[v], min_index = v;\n</code></pre>\n<p>Seriously: I mean seriously you think that make</p>\n<pre><code>for (int v = 0; v < N; v++) {\n if (visitedSet[v] == false && distance[v] <= min) {\n min = distance[v];\n min_index = v;\n }\n}\n</code></pre>\n<p>Three extra lines. I mean I would add the <code>{</code> on their own lines (so 5) but you young people like to cram things together.</p>\n<p>Your killing me:</p>\n<pre><code> if (parent[s] == -1)\n return;\n</code></pre>\n<p>OK. I understand why you did (I was young once too). You saved a line and 5 character strokes. It looks safe. And in this case it is.</p>\n<p>The trouble is that this is a bad habit that can (and will) get you into trouble. And when it does you will not spot that error for fucking days. The problem is that without the braces only one statement is valid as part of the sub block. But what happens if there is an extra statement hidden there that you can see?</p>\n<pre><code> if (something)\n doStuff(data);\n</code></pre>\n<p>Looks innocent.</p>\n<pre><code> #define doStuff(data) doStuffStart(data);doStuffEnd(data)\n</code></pre>\n<p>Now you are fucked. And there are bad programmers out there so don't say people don't do that. They absolutely do and they will screw you one you least expect it. So be safe get in good habits and this will never burn you.</p>\n<pre><code> if (something) {\n doStuff(data);\n }\n</code></pre>\n<hr />\n<p>Recursion is a nice tool:</p>\n<pre><code>void displayPath(int parent[], int s)\n{\n displayPath(parent, parent[s]);\n}\n</code></pre>\n<p>But it is dangerous and you can burn yourself. Prefer to use a loop if you can. Use recursion for trees where there is no other choice. I mean the compiler will also try and turn this into a loop for you. But because you added the print at the end tail recursion optimization can't kick in.</p>\n<hr />\n<p>Sure that works:</p>\n<pre><code> printf("***** Dijkstra's Shortest Path Algorithm ***** \\n\\n");\n printf("\\n\\n");\n</code></pre>\n<p>But filed under bad habit. Use the type safe C++ variants. Use of <code>std::cout</code> consistently means you can un bind the C++ streams from the C streams and gain impressive speed gains from the stream library. If you use both C and C++ versions you can unbind them as you will have buffering issues.</p>\n<hr />\n<p>Why use platform specific code:</p>\n<pre><code> system("pause"); // Also you are actually calling another program.\n</code></pre>\n<p>Much simpler and easier to do:</p>\n<pre><code> std::cout << "Press Enter to exit\\n";\n std::cin.ignore(numeric_limits<streamsize>::max(), '\\n');\n</code></pre>\n<p>Now you have not created another separate processes just to check if you have hit enter.</p>\n<hr />\n<p>Don't need this in C++</p>\n<pre><code> return 0;\n</code></pre>\n<p>If there is no way to have an error then don't use it (the compiler will add the appropriate <code>return 0</code> for you.</p>\n<p>Normally people put this at the end as an indciation that somewhere else in <code>main()</code> there is a <code>return 1</code> so when I see this I start looking for the error exit condition.</p>\n<h3>Dijkstra</h3>\n<pre><code>// 1 You want a start and an end.\n// This way you can stop once you have found the best path from start to end\n// There could be thousands of nodes we don't even look at:\n//\n// 2 Abstract your graph representation from the implementation.\n// There are only a few methods you need to interrogate the graph.\n//\n// 3 The working list needs to be sorted by cost.\n// You can implement this in many ways but a good algorithm should \n// probably only cost you log(n) to keep it sorted.\n// probably a lot less.\n// \n// 4 The working set. You should be able to check it quickly.\n// std::set or std::hash_set would be good.\n//\nvoid dijkstra(Graph g, int Start, int End)\n{\n WorkingSet working; // List of Node with cost sorted by cost.\n NodeSet finished; // List of nodes we have processed.\n\n working.addNode(Start, 0); // No cost to get to start.\n \n for( (node, cost) = working.popHead(); node != End; (node,cost) = working.popHead())\n {\n // If we have already processed this node ignore it.\n if (finished.find(node))\n { continue;\n }\n \n // We have just removed a node from working.\n // Because it is the top of the list it is guaranteed to be the shortest route to\n // the node. If there is another route to the node it must go through one of the\n // other nodes in the working list which means the cost to reach it will be higher\n // (because working is sorted). Thus we have found the shortest route to the node.\n \n // As we have found the shortest route to the node save it in finished.\n finished.addNode(node,cost);\n \n // For each arc leading from this node we need to find where we can get to.\n foreach(arc in node.arcs())\n {\n dest = arc.dest();\n if (NOT (finished.find(dest)))\n {\n // If the node is already in finished then we don't need to worry about it\n // as that will be the shortest route other wise calculate the cost and add\n // this new node to the working list.\n destCost = arc.cost() + cost;\n working.addNode(dest,destCost); // Note. Working is sorted list\n }\n }\n } \n}\n</code></pre>\n<hr />\n<p>Starting point:</p>\n<p>I have not tried this and it will probably take some tweaking.</p>\n<pre><code> use NodeId = int;\n use Cost = int;\n use WorkingItem = std::pair<NodeId, Cost>;\n use Order = [](WorkingItem const& lhs, WorkingItem const& rhs) {return lhs.second > rhs.second;};\n use WorkingSet = std::priority_queue<WorkingItem, std::vector<WorkingItem>, Order>;\n\n use NodeSet = std::set<NodeId>; \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:50:44.123",
"Id": "220260",
"ParentId": "220156",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T22:28:49.260",
"Id": "220156",
"Score": "1",
"Tags": [
"c++",
"algorithm",
"graph"
],
"Title": "Dijkstra's Algorithm C++"
} | 220156 |
<p>I have a program that needs to run an command on all the files in a folder:</p>
<pre><code>import glob
import os
dirName = "../pack"
if not os.path.exists(dirName):
os.mkdir(dirName)
os.chdir("xml/")
files = []
for file in glob.glob("*.xml"):
files.append(file)
os.chdir("..")
filearchiver_cmdline = "archiver.exe"
for myFile in files:
filearchiver_cmdline += " xml\\" + myFile
os.system( filearchiver_cmdline )
</code></pre>
<p>The command should look like this:</p>
<pre><code>Arhiver.exe file1.xml
</code></pre>
<p>What should I change / optimize for this code? Would a class be needed? Should there be logical def-s? Are the variables name good?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:00:36.740",
"Id": "425513",
"Score": "0",
"body": "Hi nansy. This post is being discussed on meta: https://codereview.meta.stackexchange.com/questions/9165/posted-answer-asker-deletes-question-what-do"
}
] | [
{
"body": "<ol>\n<li>Looping over <code>glob.glob</code> to build files is unneeded.</li>\n<li>You shouldn't need to <code>chdir</code> if you change the glob to <code>xml/*.xml</code></li>\n<li><code>filearchiver_cmdline</code> can be changed to use <code>str.join</code> and a comprehension.</li>\n</ol>\n\n<p><sub><strong>Note</strong>: untested</sub></p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import glob\nimport os\n\ndir_name = \"../pack\"\n\nif not os.path.exists(dir_name):\n os.mkdir(dir_name)\n\nos.system(\" \".join(\n [\"archiver.exe\"]\n + [\"xml\\\\\" + f for f in glob.glob(\"xml/*.xml\")]\n))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T13:34:46.367",
"Id": "220180",
"ParentId": "220158",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T23:59:50.287",
"Id": "220158",
"Score": "5",
"Tags": [
"python",
"python-2.x"
],
"Title": "Run a command for all files in a directory"
} | 220158 |
WebExtensions are a way to write Firefox extensions that are compatible with other browsers such as Google Chrome and Opera. Microsoft plans to bring support to their Edge browser soon. Questions requiring a MCVE (i.e. debugging questions) should include your manifest.json file in addition to all other files needed to duplicate the problem. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T00:26:51.727",
"Id": "220160",
"Score": "0",
"Tags": null,
"Title": null
} | 220160 |
<p>I am using Python 3.6.1. This program simply allows a user to enter some bytes as a "string" and it writes those bytes to a file as actual bytes in the order provided.</p>
<pre><code>import sys
WELCOME_MSG = ("Welcome to Byte Writer. Enter some bytes separated by spaces "
"like 49 A7 9F 4B when prompted. 'exit' or 'quit' to leave")
FILE_WRITE_ERROR = "Error writing to file... exiting."
INVALID_INPUT_ERROR = ("Improper byte format. Remember to enter "
"2 chars at a time separated by spaces. Hex digits only")
INPUT_PROMPT = "Enter bytes: "
VALID_CHARS = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F', 'a', 'b', 'c', 'd', 'e', 'f']
def main(argv):
if not validate_args(argv):
return -1
with open(argv[1], "ab") as f:
print(WELCOME_MSG)
while run_loop(argv, f) is True:
pass
print("Have a nice day.")
def run_loop(argv, f):
output_list = []
ui = input(INPUT_PROMPT)
if ui == "exit" or ui == "quit":
return False
list_of_str_bytes = ui.split(' ')
if validate_input_list(list_of_str_bytes) is False:
print(INVALID_INPUT_ERROR)
return False
for b in list_of_str_bytes:
output_list.append( int(b, 16) )
try:
f.write(bytes(output_list))
except:
print(FILE_WRITE_ERROR)
return False
return True
def validate_args(argv):
if len(argv) != 2:
print("USAGE: {} [filename to save to]".format(argv[0]))
return False
return True
def validate_input_list(input_list):
for b in input_list:
if len(b) != 2 or not valid_chars(b):
return False
return True
def valid_chars(chars):
for c in chars:
if c not in VALID_CHARS:
return False
return True
if __name__ == '__main__':
main(sys.argv)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T09:03:33.527",
"Id": "425493",
"Score": "0",
"body": "It looks like the indentation in your function `valid_chars` is off. I guess the final `return` should be one level further out, otherwise you only ever check the first character."
}
] | [
{
"body": "<p>Consider using <a href=\"https://docs.python.org/3/library/functions.html#any\" rel=\"nofollow noreferrer\">any()</a> for implementing <code>validate_input_list</code> and <code>valid_chars</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:48:28.980",
"Id": "220164",
"ParentId": "220163",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T01:40:31.653",
"Id": "220163",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"io"
],
"Title": "Write input bytes to a file directly in Python3"
} | 220163 |
<p><strong>Task to be accomplished:</strong> </p>
<p>Write a function that takes two strings <strong>s</strong> and <strong>p</strong> as arguments and returns a boolean denoting whether s matches p.</p>
<p><strong>p</strong> is a sequence of any number of the following:</p>
<ol>
<li>a-z - which stands for itself</li>
<li>. - which matches any character</li>
<li>* - which matches 0 or more occurrences of the previous single character</li>
</ol>
<p><strong>Code:</strong></p>
<pre><code>#include <iostream>
using namespace std;
bool eval(string s, string p) {
int j = 0;
for(int i = 0; i < p.length(); i++) {
// is next character is wildcard
if((int)p[i+1] == 42)
{
// is it preceded by a dot
if((int)p[i] == 46)
{
char charToMatch = s[j];
// keep moving forward in string until the repetition of the 'any character' is over
while(s[j] == charToMatch) j++;
}
// it's preceded by a-z
else
{
// keep moving forward in string until repetition of the letter is over
while(s[j] == p[i]) j++;
}
}
// is current character a dot
else if((int)p[i] == 46)
{
// move forward in string as it'll match no matter what
j++;
}
// it's not '.' || '*'
else
{
// is it a-z
if((int)p[i] >= 97 && (int)p[i] <= 122) {
// if current character in string != character mentioned in pattern
if(s[j] != p[i])
{
// pattern doesnt match
return false;
}
else
{
// it matches, move forward
j++;
}
}
}
}
// if pattern is ended but string is still left. pattern didnt match the whole string.
if(j < s.length()) return false;
// gone through whole string, pattern also finished. pattern matches.
else return true;
}
int main() {
cout << eval("a", "b.*"); // false
}
</code></pre>
<p><strong>Constraints:</strong> Pattern is always valid and non-empty.</p>
<p>I have just started to learn about time complexity of algos and I believe its complexity should be <span class="math-container">\$\mathcal{O}(nm)\$</span> where <span class="math-container">\$n\$</span> and <span class="math-container">\$m\$</span> are the lengths of <strong>p</strong> and the <strong>s</strong> respectively.</p>
<p>If it's not please correct me. Along with that, what improvements and optimizations could be made to lower the complexity?</p>
| [] | [
{
"body": "<h2>Bug</h2>\n\n<p>There is a case that requires NFA instead of simple DFA to recognize string (of course it is possible to convert NFA to DFA):</p>\n\n<pre><code>eval(\"aaab\", \"a*ab\");\n</code></pre>\n\n<p>Gives false, even though the string matches the regex. Disallowing same character after * fixes the problem too.</p>\n\n<h2>Style</h2>\n\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">why-is-using-namespace-std-considered-bad-practice</a>.</p>\n\n<hr>\n\n<p>Pass by const reference for read-only access. In the case of <code>eval</code> and availability of C++17, one could use <code>std::string_view</code>. I would advise taking the input range as input iterator, that would allow matching files, input from console, etc.</p>\n\n<hr>\n\n<pre><code>(int)p[i+1] == 42\n</code></pre>\n\n<p>I do not see why that is preferred to</p>\n\n<pre><code>p[i + 1] == '*'\n</code></pre>\n\n<p>more readable version makes comment obsolete.</p>\n\n<hr>\n\n<pre><code>if(j < s.length()) return false;\n else return true; \n</code></pre>\n\n<p>Could be rewritten as</p>\n\n<pre><code>return j == s.length();\n</code></pre>\n\n<p>Note that for this a bug about running over the string should be fixed, the bug is described below. <code>>=</code> will work too.</p>\n\n<hr>\n\n<p>There are also no checks if string is already fully traversed in conditions with *. Although all implementations that I know of store null terminator at the end, this will not work on arbitrary ranges of characters.</p>\n\n<hr>\n\n<p>I agree with <a href=\"https://codereview.stackexchange.com/users/308/konrad-rudolph\">KonradRudolph</a> that comments do not contribute anything useful. </p>\n\n<pre><code>// is next character is wildcard\n</code></pre>\n\n<p>This comment is misleading. * is called <a href=\"https://en.wikipedia.org/wiki/Kleene_star\" rel=\"nofollow noreferrer\">Kleene star</a>. Without looking at ASCII table one would assume there is a bug.</p>\n\n<hr>\n\n<h2>Runtime complexity</h2>\n\n<p>I believe runtime is <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> in the worst case, where <span class=\"math-container\">\\$n\\$</span> is length of input string. Think about it: the code does a single pass over a string, and doesn't reroll. </p>\n\n<hr>\n\n<h2>Theory</h2>\n\n<p>I would advise learning method of transforming NFA to DFA. It's great to learn parsing techniques, but there tools for that like flex, bison, etc exist, if you just want to hammer the nail into it's place.</p>\n\n<hr>\n\n<p>I would assume <code>.*</code> means match any sequence of characters, as by logic in the question even doing <code>|</code> for all characters in the alphabet will make it impossible to describe just any combination of letters in the alphabet. Note that such a language is in the set of regular languages, as it is possible to construct DFA for it. May be I am wrong though, as my assumption stems from javascript regex.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T10:02:11.253",
"Id": "425400",
"Score": "4",
"body": "+1. Since you mention redundant comments let me emphasise that **all** comments in OP’s code are redundant, as they don’t add a single jot of clarity. By contrast, there’s no comment describing the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T14:59:02.183",
"Id": "425512",
"Score": "0",
"body": "Great answer and very helpful. Thanks alot! One thing tho, I used `(int)p[i+1] == 42` because the compiler was giving me an error due to non equal data type comparison. And, why is the complexity \\$\\mathcal{O}(n)\\$ when there's a while loop inside the outer loop which in the worse case would pass over the whole string no? Is it because this causes the complexity to become a linear combination and hence just \\$n\\$ ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:36:01.763",
"Id": "425518",
"Score": "1",
"body": "@MohammadAreebSiddiqui, what compiler are you using? [Wandbox](https://wandbox.org/permlink/7Ip5BrnC9kSgGKxV) doesn't show any errors. About being linear time: each token in the regex will match *some* portion of the string. The sum will give the whole length in case the check reached the end, and in other cases it will be less than the length. Do not let loops to deceive you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T20:06:26.210",
"Id": "425542",
"Score": "0",
"body": "Right got it! And I am using tdm-gcc 4.9.2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T09:22:27.033",
"Id": "425711",
"Score": "1",
"body": "@MohammadAreebSiddiqui, if you are on windows, you might want to download visual studio community, or at least the compiler. Using it with visual studio code and cmake is pretty easy. Clangd (aka intellisense) doesn't seem to work properly for me, but with some tinkering I'm sure you can get it to work. The compiler is more or less up to date. If you still want gcc (bundled with g++), there is mingw64 project, which offers more up to date compilers: https://mingw-w64.org/doku.php . I recommend deleting tdm-gcc 4.9.2 and forgetting it ever existed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T16:07:15.273",
"Id": "425975",
"Score": "0",
"body": "@Incomputable hahaha thank you so much for the help! Will surely try to work on vs code. I like that ide."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T05:47:54.713",
"Id": "220169",
"ParentId": "220165",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "220169",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T03:40:30.953",
"Id": "220165",
"Score": "8",
"Tags": [
"c++",
"algorithm",
"regex",
"complexity"
],
"Title": "Regular Expression Evaluator"
} | 220165 |
<p><strong>Background</strong></p>
<p>Using this simulation I investigate a system in which enzymes proliferate in cells. During the replications of enzymes, parasites can come to be due to mutation. They can drive the system into extinction. I'm interested in where in the parameter space coexistence is possible.</p>
<p>In the program the system is a list, the cells are dictionaries with 2 keys: <code>"e"</code> for the enzymes and <code>"p"</code> for the parasites. The values of the keys are the numbers of the 2 variants.</p>
<p>Our parameters are:</p>
<ul>
<li><code>pop_size</code>: the number of the cells</li>
<li><code>cell_size</code>: the maximal number of molecules (enzymes+parasites) of cells at which cell division takes place</li>
<li><code>a_p</code>: fitness of the parasites relative to the fitness of the enzymes (for example if <code>a_p = 2</code>, the parasites' fitness is twice as that of the enzymes)</li>
<li><code>mutation_rate</code>: the probability of mutation during a replication event</li>
<li><code>gen_max</code>: the maximal number of generations (a generation corresponds to one</li>
<li><code>while</code> cycle; if the system extincts, the program doesn't run until <code>gen_max</code>)</li>
</ul>
<p>We start with <code>pop_size</code> cells with <code>cell_size // 2</code> enzimes and <code>0</code> parasites. In each cell the molecules proliferate until their number reaches <code>cell_size</code>. Each cell divides, the assortment of the molecules happens according to binomial distributions (<span class="math-container">\$p=0.5\$</span>). Cells with <code>"e" < 2</code> are discarded as dead. After that if the number of viable cells is bigger than <code>pop_size</code>, we choose <code>pop_size</code> of them according to cell fitness (<code>"e"/("e"+"p")</code>), and they move on to the next generation. On the other hand, if the number of viable cells is <code>pop_size</code> or less, they all move on to the next generation.</p>
<p><strong>My request</strong></p>
<p>I've never studied programming in school. This program is the result of heavy googling. Now I've reached a point where I need advice from experienced people. At certain parameter values the program gets quite slow.</p>
<ol>
<li><p>What better solutions exist performance-wise than my solutions for the manipulations of the list's items throughout the program and for writing data to file? And algorithm design-wise?</p></li>
<li><p>In which directions should I improve my programming skills in Python to efficiently implement these kind of models? Or am I near the limit of Python's capabilities in this regard?</p></li>
<li><p>Should I change to a more appropriate programming language in order to achieve significantly better performance at these kind of tasks? If yes, which languages should I consider? (My guess is C.)</p></li>
</ol>
<p>The program consists of two functions. <code>simulation()</code> does the simulation, <code>writeoutfile()</code> writes the data to file.</p>
<pre><code># -*- coding: utf-8 -*-
from random import choices, random
import csv
import time
import numpy as np
def simulation(pop_size, cell_size, a_p, mutation_rate, gen_max):
def fitness(pop):
return [i["e"] / (i["e"] + i["p"]) for i in pop]
def output(pop, gen, pop_size, cell_size, mutation_rate, a_p, boa_split):
if pop:
gyaklist_e = [i["e"] for i in pop]
gyaklist_p = [i["p"] for i in pop]
fitnesslist = fitness(pop)
return (
gen,
sum(gyaklist_e), sum(gyaklist_p),
sum([1 for i in pop if i["e"] > 1]),
np.mean(gyaklist_e), np.var(gyaklist_e),
np.percentile(gyaklist_e, 25),
np.percentile(gyaklist_e, 50),
np.percentile(gyaklist_e, 75),
np.mean(gyaklist_p), np.var(gyaklist_p),
np.percentile(gyaklist_p, 25),
np.percentile(gyaklist_p, 50),
np.percentile(gyaklist_p, 75),
np.mean(fitnesslist), np.var(fitnesslist),
np.percentile(fitnesslist, 25),
np.percentile(fitnesslist, 50),
np.percentile(fitnesslist, 75),
pop_size, cell_size, mutation_rate, a_p, boa_split
)
return (
gen,
0, 0,
0,
0, 0,
0, 0, 0,
0, 0,
0, 0, 0,
0, 0,
0, 0, 0,
pop_size, cell_size, mutation_rate, a_p, boa_split
)
pop = [{"e": cell_size // 2, "p": 0} for _ in range(pop_size)]
gen = 0
yield output(
pop,
gen, pop_size, cell_size, mutation_rate, a_p, boa_split="aft"
)
print(
"N = {}, rMax = {}, aP = {}, U = {}".format(
pop_size, cell_size, a_p, mutation_rate
)
)
while pop and gen < gen_max:
gen += 1
for i in pop:
while not i["e"] + i["p"] == cell_size:
luckyreplicator = choices(
["e", "p"], [i["e"], a_p*i["p"]]
)
if luckyreplicator[0] == "e" and random() < mutation_rate:
luckyreplicator[0] = "p"
i[luckyreplicator[0]] += 1
if gen % 100 == 0:
yield output(
pop,
gen, pop_size, cell_size, mutation_rate, a_p, boa_split="bef"
)
newpop = [
{"e": np.random.binomial(i["e"], 0.5),
"p": np.random.binomial(i["p"], 0.5)}
for i in pop
]
for i in zip(pop, newpop):
i[0]["e"] -= i[1]["e"]
i[0]["p"] -= i[1]["p"]
pop += newpop
newpop = [i for i in pop if i["e"] > 1]
if newpop:
fitnesslist = fitness(newpop)
fitness_sum = np.sum(fitnesslist)
fitnesslist = fitnesslist / fitness_sum
pop = np.random.choice(
newpop, min(pop_size, len(newpop)),
replace=False, p=fitnesslist
).tolist()
else:
pop = newpop
for i in range(2):
yield output(
pop,
gen+i, pop_size, cell_size, mutation_rate, a_p, boa_split="aft"
)
print("{} generations are done. Cells are extinct.".format(gen))
if gen % 100 == 0 and pop:
yield output(
pop,
gen, pop_size, cell_size, mutation_rate, a_p, boa_split="aft"
)
if gen % 1000 == 0 and pop:
print("{} generations are done.".format(gen))
def writeoutfile(simulationresult, runnumber):
localtime = time.strftime(
"%m_%d_%H_%M_%S_%Y", time.localtime(time.time())
)
with open("output_data_" + localtime + ".csv", "w", newline="") as outfile:
outfile.write(
"gen"+";" +
"eSzamSum"+";"+"pSzamSum"+";" +
"alive"+";" +
"eSzamAtl"+";"+"eSzamVar"+";" +
"eSzamAKv"+";" +
"eSzamMed"+";" +
"eSzamFKv"+";" +
"pSzamAtl"+";" + "pSzamVar" + ";" +
"pSzamAKv"+";" +
"pSzamMed"+";" +
"pSzamFKv"+";" +
"fitAtl"+";"+"fitVar"+";" +
"fitAKv"+";" +
"fitMed"+";" +
"fitFKv"+";" +
"N"+";"+"rMax"+";"+"U"+";"+"aP"+";"+"boaSplit"+"\n"
)
outfile = csv.writer(outfile, delimiter=";")
counter = 0
print(counter, "/", runnumber)
for i in simulationresult:
outfile.writerows(i)
counter += 1
print(counter, "/", runnumber)
RESULT = [simulation(100, 20, 1, 0, 10000)]
RESULT.append(simulation(100, 20, 1, 1, 10000))
N_RUN = 2
writeoutfile(RESULT, N_RUN)
# Normally I call the functions from another script,
# these last 4 lines are meant to be an example.
</code></pre>
<p>On parameter values</p>
<p>So far combinations of these values were examined:</p>
<ul>
<li><code>pop_size</code>: 100; 200; 500; 1000</li>
<li><code>cell_size</code>: 20; 50; 100; 200; 500; 1000</li>
<li><code>a_p</code>: 0.75; 1; 1.25; 1.5; 1.75; 2; 3</li>
<li><code>mutation_rate</code>: 0-1</li>
<li><code>gen_max</code>: 10000</li>
</ul>
<p>Primarily I would like to increase <code>pop_size</code> and above 1000 cells the program is slower than I would prefer. Of course that's somewhat subjective, but for example a million cells would be a perfectly reasonable assumption and at that order of magnitude I think it's objectively impossibly slow.</p>
<p>The program also gets slower with the increase in <code>cell_size</code> and slightly slower with <code>a_p</code>, but for the time being I'm happy with the values of the former and the effect of the latter is tolerable.</p>
<p>The effect of the mutation rate on speed is also tolerable.</p>
<p>In addition to <code>pop_size</code>, <code>gen_max</code> should be increased and has significant effect on run time. I know I don't catch every extinction events with 10000 generations. 20000 would be better, 50000 would be quite enough and 100000 would be like cracking a nut with a sledgehammer.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T05:37:59.983",
"Id": "425383",
"Score": "2",
"body": "Welcome to Code Review! Can you be more specific about the *parameter values the program gets quite slow*? Please be explicit about what is needed to reproduce timing: there is \"no input\" (populations are generated from parameters, not provided externally/read from, e.g., a file)? What are relevant ranges for the parameter values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T11:57:25.540",
"Id": "425411",
"Score": "0",
"body": "Thank you!\nI updated the question with the information you asked for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T06:47:21.337",
"Id": "425575",
"Score": "1",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 6 → 3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T23:53:56.380",
"Id": "426019",
"Score": "0",
"body": "I've posted a [follow-up question](https://codereview.stackexchange.com/questions/220493/population-dynamic-simulation-on-biological-information-maintenance-2)!"
}
] | [
{
"body": "<p>Numpy can be extremely fast, nigh on as fast as C or other low level languages (because it uses C!). But this is on the condition that the slow stuff is actually done in Numpy. By which I mean, you can't keep looping through lists and dictionaries then do select actions in Numpy, you have to stick to Numpy arrays and element-wise operations.</p>\n\n<p>I will give some comments on style then return to that.</p>\n\n<ul>\n<li><p>First, there are zero comments throughout your entire code. I recommend both <code>\"\"\"docstrings\"\"\"</code> at the start of your functions and short <code># Comments</code> between lines where code is a little confusing.</p></li>\n<li><p>f-strings are a python 3.6+ feature which greatly improve readability. They are used in place of .format() and string concatenation. For example:</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f'{gen} generations are done. Cells are extinct.')\n</code></pre>\n\n<ul>\n<li><p>You spread a lot of code over several lines when really, longer lines would be cleaner. You don't have very-highly nested code so the lines won't even be that long.</p></li>\n<li><p>Good uses of <code>yield</code>. This is something new programmers often skip over and it's good to see it being used to effect here.</p></li>\n<li><p>Your imports are clean, minimal and well separated from the rest of the code.</p></li>\n<li><p>Some of the naming could use some work to help clarity. Just name your keys <code>enzyme</code> and <code>parasite</code>, rather than <code>e</code> and <code>p</code>. What <em>is</em> <code>a_p</code>? Try not to use built-in function names as argument names (<code>pop</code>) as it can cause issues and be confusing. Here, it is clearly short for population but be careful with it. Use <code>snake_case</code> for naming lower-cased objects <code>ratherthanthis</code>. </p></li>\n<li><p>You are frequently returning a huge number of values. If you're always printing 0s to the file you don't need them to be returned, just write them to the file every time, then write the rest of the return values. Some things like <code>gen</code> should be kept track of externally, rather than it being returned every time. If something is static, you probably don't need to feed it into a function then spit it back out unchewed.</p></li>\n<li><p>Multi-line strings can be achieved with triple quotes:</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>example = \"\"\"\n Like\n This\n \"\"\"\n</code></pre>\n\n<p><strong>Back to Numpy</strong></p>\n\n<ul>\n<li><p>As I say, to be fast, you need to use Numpy start-to finish in your slow sections. If you generate a list with pure python, then cast it to an array, then put it back to pure python, you often save no time. It can even be slower than just pure python.</p></li>\n<li><p>You fitness function for example should instead use <a href=\"https://scipy-lectures.org/intro/numpy/operations.html\" rel=\"noreferrer\">element-wise operations</a>.</p></li>\n<li><p>If you replace the slowest sections of pure python with pure Numpy, you should see some good improvements. You could try a Code Profiler to find exactly where the hang-ups are.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T19:35:50.123",
"Id": "425455",
"Score": "0",
"body": "I see. Thank you!\nSpreading of code was suggested by pycodestyle. I was not sure that it's cleaner that way, but I just blindly followed the suggestion. So I'm glad you wrote that it would be cleaner with longer lines.\n`a_p` is the fitness of the parasites, which is actually the copying rate, which is usually \\$a\\$ in equations. You are right, `a_p` is not appropriate naming.\nDo you recommend editing the code in the question with the stylistic changes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T08:51:23.367",
"Id": "425490",
"Score": "1",
"body": "Usually people add code underneath or make a new post if changes are significant. This means that the answers aren't made incorrect by changes and are still useful to other people."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T23:54:04.713",
"Id": "426020",
"Score": "0",
"body": "I've posted a [follow-up question](https://codereview.stackexchange.com/questions/220493/population-dynamic-simulation-on-biological-information-maintenance-2)!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T11:42:33.677",
"Id": "220177",
"ParentId": "220167",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "220177",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T04:47:21.160",
"Id": "220167",
"Score": "9",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy",
"simulation"
],
"Title": "Population dynamic simulation on biological information maintenance"
} | 220167 |
<p>I had to design a very simple e-shop in C++ but I don't know if my design is the correct one. I mean in sense of re-usability. How can I find out if I have done a good design and how can I further optimize the design? The task as a simple e-shop where someone could see the products, order a product and define its characteristics. And in the end to print out the result of the order. I am posting the whole code.</p>
<p>Products.h</p>
<pre><code>#pragma once
#include <iostream>
#include <string>
#include <vector>
// Create an Interface for Product Objects
class IProducts
{
public:
// Virtual Function to get the name of the product implementing the interface
virtual std::string getProductName() = 0;
// Virtual Function to Display the names of all components of a class implementing the interface
virtual void DisplayComponents() = 0;
// Virtual Function to display the values of the components of a class implementing the interface
virtual void Display() = 0;
// Virtual Function to set the components to desired values
virtual void setAttributes() = 0;
};
// Concretion of Product Interface
class PC_Towers : public IProducts
{
public:
// Function to set the member variables of the class
void setAttributes ()
{
std::cout << "Please enter Memory size for PC_Tower in GB : ";
// MAke sure that the input in numeric
while(!(std::cin >> this->Memory))
{
std::cout << "All input's must be numeric " << std::endl;
break;
}
std::cout << "Please enter CPU size for PC_Tower in GHz : ";
while (!(std::cin >> this->CPU))
{
std::cout << "All input's must be numeric " << std::endl;
break;
};
}
// Function to get the Name of the product
std::string getProductName() { return this->productName; }
// Function to display the names of the components of the class
void DisplayComponents() { std::cout<<"The Tower is composed from : 1) Memory 2) CPU " << std::endl; }
// Function to display the values of the member variables
void Display()
{
std::cout << "Your Tower has a Memory of " << this->Memory << " GB and a CPU of " << this->CPU << " GHZ" << std::endl;
}
private:
double Memory;
double CPU;
const std::string productName = "PC_Tower";
};
// Another concrition on the IProduct interface the same as the one before
class PC_Screen : public IProducts
{
public:
void setAttributes ()
{
std::cout << "Please enter size of your Screen in inches: " ;
while (!(std::cin >> this->Size_inch))
{
std::cout << "All input's must be numeric " << std::endl;
break;
}
}
std::string getProductName() { return this->productName; }
void DisplayComponents() { std::cout << "The screen is composed from a screen measured in inches " << std::endl; }
void Display()
{
std::cout << "Your screen is " << this->Size_inch << " inches " << std::endl;
}
private:
double Size_inch;
const std::string productName = "PC_Screen";
};
// Concrition of IProducts
class Personal_Computer : public IProducts
{
public:
// Function to set the attributes of the member variable. In this case the function works as a decorator
// arround the setAttributes of the IProduct adding functionalities to it
void setAttributes()
{
Tower.setAttributes();
Screen.setAttributes();
std::cout << " Please enter size of your HardDics in GB : " ;
while (!(std::cin >> this->HardDisc))
{
std::cout << "All input's must be numeric " << std::endl;
break;
}
}
std::string getProductName() { return this->productName; }
// Decorate the DisplayComponents() and add functionalities
void DisplayComponents()
{
std::cout << "Personal Computer is composed from: 1) Tower 2) PC Screen 3) Hard Disc" << std::endl;
Tower.DisplayComponents();
Screen.DisplayComponents();
}
// Decorate the Display() and add functionalities
void Display()
{
Tower.Display();
Screen.Display();
std::cout << "Your Hard Disc has size : " << this->HardDisc << " GB " << std::endl;
}
private:
PC_Towers Tower;
PC_Screen Screen;
double HardDisc;
const std::string productName = "Personal_Computer";
};
// Concretion of Iproduct
class Work_Station : public IProducts
{
public:
void setAttributes()
{
Computer.setAttributes();
std::cout << "Please Enter your Operating System " ;
while (!(std::cin >> this->OperatingSystem))
{
std::cout << "Operating system must be string " << std::endl;
break;
}
}
std::string getProductName() { return this->productName; }
void DisplayComponents()
{
std::cout << "Work station is composed from : 1) Personal computer 2) Operating System (Linux or Windows) " << std::endl;
Computer.DisplayComponents();
}
void Display()
{
Computer.Display();
std::cout << "Your Operating System is :" << this->OperatingSystem << std::endl;
}
private:
Personal_Computer Computer;
std::string OperatingSystem;
std::string productName = "WorkStation";
};
// Interface of Factory to create IProducts
class IProductFactory
{
public:
virtual IProducts* createProduct(std::string myProduct) = 0;
};
// Concretion of Interface for IProduct creation. This Factory produces IProducts based on the an string input
// to the function ( like a user input)
class UserInputFactoryProduct : public IProductFactory
{
public:
IProducts* createProduct(std::string myProduct)
{
IProducts* product;
if (myProduct == "PC_Tower")
product = new PC_Towers;
else if (myProduct == "PC_Screen")
product = new PC_Screen;
else if (myProduct == "Personal_Computer")
product = new Personal_Computer;
else if (myProduct == "WorkStation")
product = new Work_Station;
else
product = nullptr;
return product;
}
// Function to get the product member variable
};
// Class e-shop to add and display all the products of the shop
class e_shop
{
public:
// Function to add products to the shop
void addProduct(IProducts* newProduct) { this->allProducts.push_back(newProduct); }
// Function to display all the products of the shop
void desplayAllProducts()
{
for (int i = 0 ; i < allProducts.size() ; i++)
std::cout << allProducts.at(i)->getProductName() << std::endl;
}
private:
// vector to keep all the products of the shop
std::vector< IProducts* > allProducts;
};
</code></pre>
<p>And this is main</p>
<pre><code>#include "Products.h"
int main()
{
// create some products
IProducts* Product1 = new PC_Towers;
IProducts* Product2 = new PC_Screen;
IProducts* Product3 = new Personal_Computer;
IProducts* Product4 = new Work_Station;
// create an e-shop and add the products created
e_shop myEshop;
myEshop.addProduct(Product1);
myEshop.addProduct(Product2);
myEshop.addProduct(Product3);
myEshop.addProduct(Product4);
myEshop.desplayAllProducts();
std::string choosedProduct;
std::cout << std::endl;
IProducts* myProduct = nullptr;
UserInputFactoryProduct ProductFactory;
// choose a product and use factory to create the object based on the user input
while (myProduct == nullptr)
{
std::cout << "Chose one of the above products : ";
std::cin >> choosedProduct;
myProduct = ProductFactory.createProduct(choosedProduct);
} ;
// display all the attributes of the product
myProduct->DisplayComponents();
// let the user to add values to components
myProduct->setAttributes();
// display the product ith the values of the user
myProduct->Display();
system("pause");
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T12:50:45.120",
"Id": "425413",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T13:07:50.810",
"Id": "425415",
"Score": "0",
"body": "It looks like you have two files here, one is products.h ans one is main.cpp but it is all one code block. Is it possible for you to split the code block into 2 code blocks with names before each code block?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T13:11:11.850",
"Id": "425416",
"Score": "1",
"body": "@pacmaninbw Yes i edit it so now it is 2 code blocks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T18:27:40.853",
"Id": "425450",
"Score": "0",
"body": "Which C++ standard are you targeting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:00:11.160",
"Id": "425549",
"Score": "0",
"body": "Don't write C++ like you only know Java. Learn the proper way to do C++ (never use new)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:46:26.607",
"Id": "425588",
"Score": "0",
"body": "@Martin York Thank you for the advise. I actually never use new but in this case my aim was only the design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:09:13.207",
"Id": "425627",
"Score": "1",
"body": "@ArisKoutsoukis: `IProducts* Product1 = new PC_Towers;` The trouble is this means you have a RAW pointer. RAW pointers harc back to C++03 before modern memory management techniques were introduced into the language. This has affected your design `void addProduct(IProducts* newProduct)` were you are accepting a RAW pointer (this is bad because it is unclear if the interface is accepting ownership). Use `std::make_unique()` or `std::make_shared()` for dynamic objects as these return smart pointers."
}
] | [
{
"body": "<p>If I look at your code, it looks like you are programming in 98. C++ has evolved a lot, C++11 is the least to accept, C++17 should be the standard for this time.</p>\n\n<p><code>getProductName</code> could/should be a const method. Most likely, others can as well.</p>\n\n<p>Looking at the <code>PC_Towers</code> class, I would expect it to be a <code>final</code> class.</p>\n\n<p>I'm not in favor of the <code>setAttributes</code>, it doesn't belong in this class. Do you intend to add as well the logic to read it from file, database, json, XML ... to it? Best to separate it and use a kind of factory pattern.\nLooking closer: <code>while (cond) { ... break; }</code> looks a lot like an if-statement. How about using it to have less confusion?</p>\n\n<p>From a class design, why would you create the same string for every instance. You could make it a static or simply inline it in your function call.</p>\n\n<p>Looks like you are using a factory, let's use some abstractions here. Though, ignoring those, you duplicated the strings. One small typo, big consequences.</p>\n\n<p>Looking at the factory, it still does naked new. Use <code>std::make_unique</code> as it prevents memory leaks you have in your program.</p>\n\n<p><code>desplayAllProducts</code> (typo?) looks like it can benefit from a range based for-loop. Oh, and don't use <code>.at</code> on a vector if you always know you index within bounds.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T20:15:59.090",
"Id": "425458",
"Score": "0",
"body": "My main concern was the design and not the implementation. Of course if I was aiming for good implementation it would look much different with of course smart pointers and many other modern c++ features."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T18:56:16.543",
"Id": "220199",
"ParentId": "220179",
"Score": "6"
}
},
{
"body": "<p><strong>Don't Ignore Warning Messages</strong><br>\nThis line in e_shop.desplayAllProducts() generates a warning message:</p>\n\n<pre><code> for (int i = 0; i < allProducts.size(); i++)\n</code></pre>\n\n<p>The warning is that there is a type miss-match between the variable <code>i</code> and allProducts.size(). To remove this warning message <code>i</code> should be declared as type <code>size_t</code>. All STL container classes return <code>size_t</code> from the size function. The type <code>size_t</code> is unsigned rather than signed, integers are signed.</p>\n\n<p>It might be better to use a ranged for loop using iterators rather than an index for loop:</p>\n\n<pre><code> for (auto i : allProducts) {\n std::cout << i->getProductName() << std::endl;\n }\n</code></pre>\n\n<p>This may improve performance as well.</p>\n\n<p><strong>Reusability and Maintainability</strong><br>\nIt might be better to put each class in it's own file. While several of the classes depend on the interface (abstract class) <code>IProducts</code>, none of the classes depend on the other classes in the header file. The header file Products.h can include each of the product class files.</p>\n\n<p>The <code>productName</code> string should be declared as a protected variable in the abstract class <code>IProducts</code> and rather than defining std::string getProductName() as an abstract function in <code>IProducts</code> create the full declaration of the function.</p>\n\n<pre><code>class IProducts\n{\npublic:\n std::string getProductName() { return productName; } // Note: no `this` keyword.\n // Virtual Function to Display the names of all components of a class implementing the interface\n virtual void DisplayComponents() = 0;\n // Virtual Function to display the values of the components of a class implementing the interface \n virtual void Display() = 0;\n // Virtual Function to set the components to desired values \n virtual void setAttributes() = 0;\nprotected:\n std::string productName;\n};\n</code></pre>\n\n<p>Have a constructor in each of the classes that inherits from <code>IProducts</code> that initializes productName to the proper value. The constructor should also initialize each of the private variables to a default value. Some of the classes might require destructors as well, they can always be set to the default constructor if they don't have special functions such as closing files.</p>\n\n<p>Unlike some other languages such as PHP, the <code>this</code> keyword is not generally required in C++ and is generally not used. There may be certain special cases where it is required.</p>\n\n<p>It might be better if each class had a .cpp file that contained the functions and only the class declaration was in the header file. This will improve compile times and not require all file to rebuild when changes are made in the executable code.</p>\n\n<p><strong>Portability</strong><br>\nWhile </p>\n\n<pre><code>#pragma once\n</code></pre>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Pragma_once\" rel=\"noreferrer\">is widely supported, it is not part of the C or C++ standard</a> and some C++ compilers may report a compilation error or warning message. This <a href=\"https://stackoverflow.com/questions/1263521/what-is-pragma-used-for\">stackoverflow question</a> also discusses the user of <code>#pragma once</code>. It might be better to use an explicit <a href=\"https://en.wikipedia.org/wiki/Include_guard\" rel=\"noreferrer\">include guard</a>.</p>\n\n<pre><code>#ifndef GRANDPARENT_H\n#define GRANDPARENT_H\n\nstruct foo {\n int member;\n};\n\n#endif /* GRANDPARENT_H */\n</code></pre>\n\n<p><strong>Performance</strong><br>\nGenerally the code will perform better if <code>\\n</code> is used over <code>std::endl</code>. std::endl performs a file flush to the output stream and this adds time in each execution, if you use std::endl do it outside a loop after the loop has completed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:14:24.067",
"Id": "220236",
"ParentId": "220179",
"Score": "5"
}
},
{
"body": "<p>Because I see that i get a lot of comments about the Row pointers , i changed it using smart pointers and more c++ 11. I am posting the hole code if anyone would like to use it. I made some of the changes proposed but not all of the proposed for example I was not able to make a factory for the setAttributes. And if anyone could give me a hint how to get rid of the if statements in the factory for the production of the IProducts i would appreciate it. And of course any other advice's would be welcome</p>\n\n<p>User.h</p>\n\n<pre><code>#pragma once\n#include\"Products.h\"\n\nclass IUser \n{\npublic:\n IUser(const std::string myName, const double myPassword) { name = myName, password = myPassword; }\n const std::string getName() const\n {\n return name;\n }\n\n const double getPassword() const\n {\n return password;\n }\nprotected:\n std::string name;\n double password;\n};\n\nclass Client : public IUser\n{\npublic:\n Client(const std::string myName, double passWord) :IUser(myName, passWord) {};\n void buyProduct(std::shared_ptr<IProducts> currentProduct) { boughtProducts.push_back(currentProduct); }\n void checkOut() {\n for (size_t i = 0; i < boughtProducts.size(); ++i)\n { \n std::cout << \"Your \" << i + 1 << \" bought product is \" << boughtProducts[i]->getProductName() << \" with the above charecteristics \" << std::endl;\n boughtProducts[i]->Display();\n }\n }\nprivate:\n std::vector<std::shared_ptr<IProducts>> boughtProducts;\n\n};\n</code></pre>\n\n<p>Products.h</p>\n\n<pre><code>#pragma once\n\n#include <iostream>\n#include <string>\n#include <vector>\n\n// Create an Interface for Product Objects\nclass IProducts\n{\npublic:\n // Virtual Function to get the name of the product implementing the interface\n virtual const std::string getProductName() const = 0;\n // Virtual Function to Display the names of all components of a class implementing the interface\n virtual void DisplayComponents() = 0;\n // Virtual Function to display the values of the components of a class implementing the interface \n virtual void Display() = 0;\n // Virtual Function to set the components to desired values \n virtual void setAttributes() = 0;\n};\n\n// Concretion of Product Interface\nclass PC_Towers final : public IProducts\n{\npublic:\n // Function to set the member variables of the class\n void setAttributes ()\n {\n\n std::cout << \"Please enter Memory size for PC_Tower in GB : \";\n // MAke sure that the input in numeric\n while(!(std::cin >> this->Memory))\n { \n std::cout << \"All input's must be numeric \" << std::endl;\n\n break;\n }\n\n std::cout << \"Please enter CPU size for PC_Tower in GHz : \";\n while (!(std::cin >> this->CPU))\n {\n\n std::cout << \"All input's must be numeric \" << std::endl;\n break;\n };\n\n\n\n\n }\n // Function to get the Name of the product\n const std::string getProductName() const { return this->productName; }\n // Function to display the names of the components of the class\n void DisplayComponents() { std::cout<<\"The Tower is composed from : 1) Memory 2) CPU \" << std::endl; }\n // Function to display the values of the member variables\n void Display()\n {\n std::cout << \"Your Tower has a Memory of \" << this->Memory << \" GB and a CPU of \" << this->CPU << \" GHZ\" << std::endl;\n\n\n }\n\n\nprivate:\n double Memory;\n double CPU;\n const std::string productName = \"PC_Tower\";\n};\n\n// Another concrition on the IProduct interface the same as the one before\nclass PC_Screen : public IProducts\n{\npublic:\n void setAttributes () \n {\n\n\n std::cout << \"Please enter size of your Screen in inches: \" ;\n while (!(std::cin >> this->Size_inch))\n {\n std::cout << \"All input's must be numeric \" << std::endl;\n break;\n\n\n }\n\n\n\n }\n const std::string getProductName() const { return this->productName; }\n void DisplayComponents() { std::cout << \"The screen is composed from a screen measured in inches \" << std::endl; }\n void Display()\n {\n std::cout << \"Your screen is \" << this->Size_inch << \" inches \" << std::endl;\n\n\n }\n\nprivate:\n double Size_inch;\n const std::string productName = \"PC_Screen\";\n};\n// Concrition of IProducts\nclass Personal_Computer : public IProducts\n{\npublic:\n // Function to set the attributes of the member variable. In this case the function works as a decorator\n // arround the setAttributes of the IProduct adding functionalities to it\n void setAttributes() \n {\n Tower.setAttributes();\n Screen.setAttributes();\n\n std::cout << \" Please enter size of your HardDics in GB : \" ;\n while (!(std::cin >> this->HardDisc))\n {\n std::cout << \"All input's must be numeric \" << std::endl;\n break;\n }\n\n\n\n }\n const std::string getProductName() const { return this->productName; }\n // Decorate the DisplayComponents() and add functionalities\n void DisplayComponents() \n { \n std::cout << \"Personal Computer is composed from: 1) Tower 2) PC Screen 3) Hard Disc\" << std::endl;\n Tower.DisplayComponents();\n Screen.DisplayComponents();\n\n }\n // Decorate the Display() and add functionalities\n void Display()\n {\n Tower.Display();\n Screen.Display();\n std::cout << \"Your Hard Disc has size : \" << this->HardDisc << \" GB \" << std::endl;\n\n\n }\n\n\nprivate:\n PC_Towers Tower;\n PC_Screen Screen;\n double HardDisc;\n const std::string productName = \"Personal_Computer\";\n};\n\n// Concretion of Iproduct\nclass Work_Station : public IProducts\n{\npublic:\n void setAttributes()\n {\n Computer.setAttributes();\n\n std::cout << \"Please Enter your Operating System \" ;\n while (!(std::cin >> this->OperatingSystem))\n {\n std::cout << \"Operating system must be string \" << std::endl;\n break;\n }\n\n\n }\n const std::string getProductName() const { return this->productName; }\n void DisplayComponents()\n {\n std::cout << \"Work station is composed from : 1) Personal computer 2) Operating System (Linux or Windows) \" << std::endl;\n Computer.DisplayComponents();\n }\n void Display()\n {\n Computer.Display();\n std::cout << \"Your Operating System is :\" << this->OperatingSystem << std::endl;\n\n }\n\nprivate:\n Personal_Computer Computer;\n std::string OperatingSystem;\n std::string productName = \"WorkStation\";\n};\n\n\n\n</code></pre>\n\n<p>ProductsFactory.h</p>\n\n<pre><code>#pragma once\n#include\"Products.h\"\n\nclass IProductFactory\n{\npublic:\n virtual std::shared_ptr<IProducts> createProduct(std::string) = 0;\n\n};\n// Concretion of Interface for IProduct creation. This Factory produces IProducts based on the an string input \n// to the function ( like a user input)\nclass UserInputFactoryProduct : public IProductFactory\n{\npublic:\n\n std::shared_ptr<IProducts> createProduct(std::string myProduct)\n {\n std::shared_ptr<IProducts> product;\n if (myProduct == \"PC_Tower\")\n product = std::make_shared<PC_Towers>();\n else if (myProduct == \"PC_Screen\")\n product = std::make_shared<PC_Screen>();\n else if (myProduct == \"Personal_Computer\")\n product = std::make_shared<Personal_Computer>();\n else if (myProduct == \"WorkStation\")\n product = std::make_shared<Work_Station>();\n else\n product = nullptr;\n\n return product;\n\n }\n\n\n};\n\n\n</code></pre>\n\n<p>e_shop.h</p>\n\n<pre><code>#pragma once\n#include\"Products.h\"\n\n// Class e-shop to add and display all the products of the shop\nclass e_shop\n{\npublic:\n // Function to add products to the shop\n void addProduct(std::shared_ptr<IProducts>newProduct) { this->allProducts.push_back(newProduct); }\n // Function to display all the products of the shop\n void desplayAllProducts()\n {\n\n for (auto e:allProducts)\n std::cout << e->getProductName() << std::endl;\n }\nprivate:\n // vector to keep all the products of the shop\n std::vector< std::shared_ptr<IProducts> > allProducts;\n};\n\n</code></pre>\n\n<p>main.cpp</p>\n\n<pre><code>#include \"Products.h\"\n#include \"e_shop.h\"\n#include\"ProductsFactory.h\"\n#include \"User.h\"\nint main()\n{\n Client first(\"Aris\", 12345);\n // create some products\n std::shared_ptr< IProducts > Product1 = std::make_shared<PC_Towers>();\n std::shared_ptr< IProducts > Product2 = std::make_shared<PC_Screen>();\n std::shared_ptr< IProducts > Product3 = std::make_shared<Personal_Computer>();\n std::shared_ptr< IProducts > Product4 = std::make_shared<Work_Station>();\n // create an e-shop and add the products created\n e_shop myEshop;\n myEshop.addProduct(Product1);\n myEshop.addProduct(Product2);\n myEshop.addProduct(Product3);\n myEshop.addProduct(Product4);\n myEshop.desplayAllProducts();\n std::string finish;\n\n while(finish != \"N\")\n { \n std::string choosedProduct;\n std::cout << std::endl;\n std::shared_ptr<IProducts> myProduct = nullptr;\n UserInputFactoryProduct ProductFactory;\n\n // choose a product and use factory to create the object based on the user input\n while (myProduct == nullptr)\n {\n std::cout << \"Chose one of the above products : \";\n std::cin >> choosedProduct;\n\n myProduct = ProductFactory.createProduct(choosedProduct);\n\n } ;\n\n\n // display all the attributes of the product\n myProduct->DisplayComponents();\n // let the user to add values to components\n myProduct->setAttributes();\n // display the product ith the values of the user\n first.buyProduct(myProduct);\n std::cout << \"Do you want to continue: Y or N :\" ;\n std::cin >> finish;\n }\n std::cout << first.getName() << \" bought :\" << std::endl;\n first.checkOut();\n system(\"pause\");\n}\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T17:18:05.323",
"Id": "425641",
"Score": "0",
"body": "Rather than post this answer, you might want to post a new question with a link to this question, especially if you have made significant changes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:47:09.387",
"Id": "220294",
"ParentId": "220179",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "220236",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T12:49:01.103",
"Id": "220179",
"Score": "4",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Design for a very simple e-shop"
} | 220179 |
<p>Link to github
Link to github: <a href="https://github.com/zombi3123/Game-Of-Life/" rel="nofollow noreferrer">https://github.com/zombi3123/Game-Of-Life/</a></p>
<p>Source code:</p>
<p><strong>Window.Java</strong> </p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
//JFrame Class
public class Window extends JFrame {
public Window(int x, int y) {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(x, y);
this.setResizable(true);
this.setLayout(null);
getContentPane().setBackground(Color.BLACK);
}
}
</code></pre>
<p><strong>Main.Java</strong> </p>
<pre><code>public class Main {
//Main class
public static void main(String[] args){
Window w=new Window(1800,1000);
Frame f=new Frame(w.getWidth(),w.getHeight());
w.add(f);
w.setVisible(true);
}
}
</code></pre>
<p><strong>Frame.Java</strong> </p>
<pre><code>import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
//JFrame class
public class Frame extends JPanel implements MouseListener, ActionListener, MouseMotionListener {
private ArrayList<Cell> columns;
private ArrayList<ArrayList<Cell>> rows;
private int cellLength,JFrameWidth,JFrameHeight;
private Color dead,killDefaultColor;
private Timer tm;
private int border;
private JButton Start,stop,randomize,kill,step,reset,drawLine;
private Random randNum;
private boolean killCells,drawLineMode;
public Frame(int JFrameWidth,int JFrameHeight){
tm=new Timer(1,this);
rows=new ArrayList<>();
columns= new ArrayList<>();
this.cellLength=3;
this.dead=Color.BLACK;
this.border=1;
this.JFrameWidth=JFrameWidth;
this.JFrameHeight=JFrameHeight;
this.killCells=false;
this.drawLineMode=false;
this.setSize(new Dimension(this.JFrameWidth, this.JFrameHeight));
randNum=new Random();
Start=new JButton("Start");
stop=new JButton("Stop");
randomize=new JButton("Randomize");
kill=new JButton("Kill Cells");
step=new JButton("Step");
reset=new JButton("Reset");
drawLine =new JButton("Line");
ArrayList<JButton> JB = new ArrayList<>();
JB.add(Start);
JB.add(stop);
JB.add(randomize);
JB.add(kill);
JB.add(step);
JB.add(reset);
JB.add(drawLine);
int i=50;
for (JButton j:JB){
j.setBounds(i*2,0,50,20);
this.add(j);
i+=10;
}
killDefaultColor=kill.getBackground();
Color killActiveColour=Color.green;
Start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tm.start();
Start.setVisible(false);
// Start.setEnabled(false);
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
tm.stop();
Start.setEnabled(true);
Start.setVisible(true);
}
});
randomize.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 1; i < rows.size()-1; i++) {
for (int j = 1; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
float a=randNum.nextFloat();
if (a>0.90) {
c.setAlive();
}
}
}
repaint();
}
});
kill.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
killCells=!killCells;
if (!killCells) {
kill.setBackground(killDefaultColor);
}
else kill.setBackground(killActiveColour);
}
});
step.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ArrayList<Cell> deadCells=new ArrayList<Cell>();
ArrayList<Cell> bornCells=new ArrayList<Cell>();
for (int i = 1; i < rows.size()-1; i++) {
for (int j = 1; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
Cell cE=rows.get(i).get(j+1);
Cell cW=rows.get(i).get(j-1);
Cell cN=rows.get(i-1).get(j);
Cell cS=rows.get(i+1).get(j);
Cell cNE=rows.get(i-1).get(j+1);
Cell cNW=rows.get(i-1).get(j-1);
Cell cSE=rows.get(i+1).get(j+1);
Cell cSW=rows.get(i+1).get(j-1);
if(c.isAlive()){
if(c.totalNeighbours(cE,cW,cN,cS,cNE,cNW,cSE,cSW)>=4){deadCells.add(c);}
if(c.totalNeighbours(cE,cW,cN,cS,cNE,cNW,cSE,cSW)<2){deadCells.add(c);}
}
else{
if(c.totalNeighbours(cE,cW,cN,cS,cNE,cNW,cSE,cSW)==3){bornCells.add(c);}
}
repaint();
}
}
for(Cell c:deadCells){c.setDead();}
for(Cell c:bornCells){c.setAlive();}
}
});
reset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < rows.size()-1; i++) {
for (int j = 0; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
c.setDead();
}
}
repaint();
}
});
drawLine.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
drawLineMode = !drawLineMode;
if (drawLineMode) {
killCells=false;
drawLine.setBackground(killActiveColour);
}
else{
drawLine.setBackground(killDefaultColor);
}
}
});
repaint();
createMap();
addMouseListener(this);
addMouseMotionListener(this);
setFocusable(true);
}
private void initComponents() {
}
public void createMap(){
//Draw grid. Initialize all cells to dead
for(int columsi=0;columsi<getHeight()/cellLength;columsi++){
ArrayList<Cell> columns = new ArrayList<>();
for(int rowsi=0;rowsi<getWidth()/cellLength;rowsi++){
Cell c=new Cell(rowsi*(cellLength+border),columsi*(cellLength+border),cellLength,false);
columns.add(c);
repaint();
}
rows.add(columns);
}
System.out.println(rows.size()*rows.get(0).size());
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < rows.size(); i++) {
for (int j = 0; j < rows.get(0).size(); j++){
Cell c=rows.get(i).get(j);
if (c.isAlive()) {
g.setColor(Color.black);
} else {
g.setColor(Color.white);
}
c.draw(g);
}
}
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {
if (killCells){
for (int i = 1; i < rows.size()-1; i++) {
for (int j = 1; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
if(e.getX()>=c.getTlx()&&e.getX()<c.getTlx()+c.getCellLength()&&e.getY()>= c.getTly()&&e.getY()<c.getTly()+c.getCellLength()) {
c.setDead();
repaint();
}
}
}
}
else if(!killCells && !drawLineMode){
outerLoop:
for (int i = 1; i < rows.size()-1; i++) {
for (int j = 1; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
if(e.getX()>=c.getTlx()&&e.getX()<c.getTlx()+c.getCellLength()&&e.getY()>= c.getTly()&&e.getY()<c.getTly()+c.getCellLength()) {
c.setAlive();
repaint();
break outerLoop;
}
}
}
}
else if(drawLineMode=true){
outerLoop:
for (int i = 0; i < rows.size()-1; i++) {
for (int j = 0; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
if(e.getX()>=c.getTlx()&&e.getX()<c.getTlx()+c.getCellLength()&&e.getY()>= c.getTly()&&e.getY()<c.getTly()+c.getCellLength()) {
for (int k = rows.indexOf(c); k < rows.get(0).size()-1; k++){
if(k+j>rows.get(0).size()-1){break outerLoop;}
else{rows.get(i).get(j+k).setAlive();}
repaint();
}
//break outerLoop;
}
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
//When the timer ticks, action is performed
public void actionPerformed(ActionEvent e) {
ArrayList<Cell> deadCells=new ArrayList<Cell>();
ArrayList<Cell> bornCells=new ArrayList<Cell>();
for (int i = 1; i < rows.size()-1; i++) {
for (int j = 1; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
Cell cE=rows.get(i).get(j+1);
Cell cW=rows.get(i).get(j-1);
Cell cN=rows.get(i-1).get(j);
Cell cS=rows.get(i+1).get(j);
Cell cNE=rows.get(i-1).get(j+1);
Cell cNW=rows.get(i-1).get(j-1);
Cell cSE=rows.get(i+1).get(j+1);
Cell cSW=rows.get(i+1).get(j-1);
if(c.isAlive()){
if(c.totalNeighbours(cE,cW,cN,cS,cNE,cNW,cSE,cSW)>=4){deadCells.add(c);}
if(c.totalNeighbours(cE,cW,cN,cS,cNE,cNW,cSE,cSW)<2){deadCells.add(c);}
}
else{
if(c.totalNeighbours(cE,cW,cN,cS,cNE,cNW,cSE,cSW)==3){bornCells.add(c);}
}
repaint();
}
}
for(Cell c:deadCells){c.setDead();}
for(Cell c:bornCells){c.setAlive();}
}
@Override
//When mouse dragged across screen, draw cells according to mouses position
public void mouseDragged(MouseEvent e) {
if(killCells){
outerloop:
for (int i = 1; i < rows.size()-1; i++) {
for (int j = 1; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
if(c.isAlive()){
if(e.getX()>=c.getTlx()&&e.getX()<c.getTlx()+c.getCellLength()&&e.getY()>= c.getTly()&&e.getY()<c.getTly()+c.getCellLength()) {
c.setDead();
repaint();
break outerloop;
}
}
}
}
}
else{
for (int i = 1; i < rows.size()-1; i++) {
for (int j = 1; j < rows.get(0).size()-1; j++){
Cell c=rows.get(i).get(j);
if(e.getX()>=c.getTlx()&&e.getX()<c.getTlx()+c.getCellLength()&&e.getY()>= c.getTly()&&e.getY()<c.getTly()+c.getCellLength()) {
c.setAlive();
repaint();
}
}
}
}
}
@Override
public void mouseMoved(MouseEvent e) {}
}
</code></pre>
<p><strong>Cell.Java</strong> </p>
<pre><code>import java.awt.*;
import java.util.ArrayList;
//Cell class
public class Cell {
private int cellLength,tlx,tly;
private Color color;
private boolean alive;
public Cell(int tlx,int tly,int cellLength,boolean alive){
this.cellLength=cellLength;
this.alive=alive;
this.color=color;
this.tlx=tlx;
this.tly=tly;
}
public int getTlx(){return this.tlx;}
public int getTly(){return this.tly;}
public void setAlive() {
this.alive = true;
}
public void setDead() {
this.alive = false;
}
public boolean isAlive() {
return alive;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public int getCellLength() {
return cellLength;
}
public int totalNeighbours(Cell c1,Cell c2,Cell c3,Cell c4,Cell c5,Cell c6,Cell c7,Cell c8){
int liveNeighbours=0;
ArrayList<Cell> neighborslist=new ArrayList();
neighborslist.add(c1);
neighborslist.add(c2);
neighborslist.add(c3);
neighborslist.add(c4);
neighborslist.add(c5);
neighborslist.add(c6);
neighborslist.add(c7);
neighborslist.add(c8);
for(Cell c:neighborslist){
if(c.isAlive()){
liveNeighbours+=1;
}
}
return liveNeighbours;
}
public void draw(Graphics g){
g.setColor(color);
g.fillRect(tlx,tly,cellLength,cellLength);
}
}
</code></pre>
<p>I'd like advice on how I can crunch this program down to fewer lines.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T14:25:37.097",
"Id": "425421",
"Score": "0",
"body": "If this code is in multiple files (repo seems to show that) then it might be better if you broke the code block into multiple blocks, one for each file with the file name above the code block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T14:46:15.873",
"Id": "425422",
"Score": "0",
"body": "Keeps giving me format errors. People are just going to have to use GitHub if they find the pasted source code a pain"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T14:55:42.653",
"Id": "425423",
"Score": "0",
"body": "Take a look at how I did it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T14:57:54.470",
"Id": "425424",
"Score": "0",
"body": "@pacmaninbw thank you!"
}
] | [
{
"body": "<p>The number of lines is seldom a measure of quality. It is always better to use more lines if it makes the code more readable or more efficient. Why do you want fewer lines?</p>\n\n<p>Anyway, since this is a bit of \"a big code dump,\" I'm just going to skim over it and point the most obvious things. It's not an exhaustive list. You can start improving the code from these.</p>\n\n<p><strong>Window.Java</strong></p>\n\n<p>Pararameters names <code>x</code> and <code>y</code> are reserved for indexing a two dimensional map, e.g. pinpointing a pixel in an image. The code uses them for dimension, where <code>width</code> and <code>height</code> would be better.</p>\n\n<p><strong>Main.Java</strong></p>\n\n<p>I don't remember much of Swing anymore, but shouldn't the window resize itself to fit the frame? So passing the frame size to window would be redundant as it's the Frame you want to be exactly 1800x1000 pixels.</p>\n\n<p><strong>Frame.java</strong></p>\n\n<p>You can see from the implemented interfaces that this class loads on responsibilities. Refactor the listeners into standalone classes so the frame doesn't need to be responsible for interpreting mouse movement (<a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>) and such. The frame should only be reponsible for displaying the graphics.</p>\n\n<p>This class is a bit of a mess. Cells are stored in a redundant array of rows and columns. A two dimensional array, or a one dimensional array with index calculated from x and y location would be easier to understand as they are common constructs in this kind of application.</p>\n\n<p><strong>General</strong></p>\n\n<p>There is a separate class for Cell but in Game of Life the relation of the Cells is just as important. There should be a separate class for the Grid that contains the cells. Not just a bunch of ArrayLists. The rules that control the life and death of cells should be in yet another class. That class would be the game engine.</p>\n\n<p>The Frame should not be controlling the game. The timer should be a separate class which tells the game engine to update the game model and send events to the Frame to let it know that the visual representation needs to be updated. Look at the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">Model-View-Controller</a> design pattern.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:35:49.940",
"Id": "425527",
"Score": "0",
"body": "Thank you for your in-depth comment. It means a lot to me I'll take all of your points into consideration for further improvements/programs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:45:10.180",
"Id": "425530",
"Score": "0",
"body": "I will say that I did indeed create a two-dimensional arraylist for the cells"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T06:10:21.870",
"Id": "220216",
"ParentId": "220182",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220216",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T14:06:42.507",
"Id": "220182",
"Score": "2",
"Tags": [
"java",
"simulation",
"game-of-life"
],
"Title": "Code which creates the Game Of life In Java"
} | 220182 |
<p>I have written a Java program to solve a N-puzzle with A* search and manhattan distance. My program can solve every 8-puzzle I have tested under 1 second, but it can't solve a 15-puzzle after 30 minutes. How can I improve performance?
Here a short example output:</p>
<pre><code>6 2 1
0 4 3
5 8 7
6 2 1
4 0 3
5 8 7
....
Solution length: 23
Time: 0.165308527
</code></pre>
<p>SlidingPuzzle.java:</p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.PriorityQueue;
import java.util.Comparator;
public class SlidingPuzzle {
private int size;
private int puzzle[][];
private final int[][] moves = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private final int l_moves = moves.length;
public SlidingPuzzle(int puzzle[][]) {
this.puzzle = puzzle;
this.size = puzzle.length;
aStar();
}
class Node {
int puzzle[][];
int blankX, blankY;
Node previous;
int f, h, g;
public Node(Node previous, int puzzle[][]) {
this.previous = previous;
this.puzzle = puzzle;
// init start node with blankX, blankY and manhattan distance
if(previous == null) {
for (int x = 0; x < size; x++) {
for (int y = 0; y < size; y++) {
int n = puzzle[x][y];
if (n == 0) {
blankX = x;
blankY = y;
}else {
int x1 = (n - 1) / size;
int y1 = (n - 1) % size;
this.h += Math.abs(x - x1) + Math.abs(y - y1);
}
}
}
}
}
private boolean inBoard(int x, int y) {
return (x >= 0 && y >= 0 && x < size && y < size);
}
private void swapNumbers(int x1, int y1, int x2, int y2) {
int tmp = puzzle[x1][y1];
puzzle[x1][y1] = puzzle[x2][y2];
puzzle[x2][y2] = tmp;
}
/*
from a boardstate to a childstate, manhattan distance can only change by
+1 or -1, so I don't need to calculate the manhattan distance for the whole board.
*/
public ArrayList<Node> getChildren() {
ArrayList<Node> children = new ArrayList<>();
for (int i = 0; i < l_moves; i++) {
if (inBoard(blankX + moves[i][0], blankY + moves[i][1])) {
int n1 = puzzle[blankX + moves[i][0]][blankY + moves[i][1]];
int m1 = calcManhattan(blankX + moves[i][0], (n1 - 1) / size, blankY + moves[i][1], (n1 - 1) % size);
swapNumbers(blankX, blankY, blankX + moves[i][0], blankY + moves[i][1]);
int copy[][] = new int[size][size];
for (int j = 0; j < size; j++) {
copy[j] = puzzle[j].clone();
}
int n2 = copy[blankX][blankY];
int x2 = (n2 - 1) / size;
int y2 = (n2 - 1) % size;
Node child = new Node(this, copy);
child.blankX = this.blankX + moves[i][0];
child.blankY = this.blankY + moves[i][1];
int m2 = calcManhattan(blankX, x2, blankY, y2);
int nm;
if(m1 < m2) {
nm = 1;
}else {
nm = -1;
}
child.h = this.h + nm;
children.add(child);
swapNumbers(blankX, blankY, blankX + moves[i][0], blankY + moves[i][1]);
}
}
return children;
}
public int calcManhattan(int x1, int x2, int y1, int y2) {
return Math.abs(x1 - x2) + Math.abs(y1 -y2);
}
@Override
public boolean equals(Object o) {
Node node = (Node) o;
return Arrays.deepEquals(puzzle, node.puzzle);
}
}
class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node n1, Node n2) {
return Integer.compare(n1.f, n2.f);
}
}
private void printBoard(int[][] board) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
String l = "";
if (board[i][j] < 10) {
l = " ";
}
System.out.print(l + board[i][j] + " ");
}
System.out.println("");
}
System.out.println("");
}
private void reconstructPath(Node current) {
Stack<Node> path = new Stack<>();
path.push(current);
int l = 0;
while (current.previous != null) {
current = current.previous;
path.push(current);
l++;
}
while (!path.isEmpty()) {
Node n = path.pop();
printBoard(n.puzzle);
}
System.out.println("Solution length: " + l);
}
private void aStar() {
Node start = new Node(null, puzzle);
Comparator<Node> nodeComparator = new NodeComparator();
ArrayList<Node> closedList = new ArrayList<>();
PriorityQueue<Node> openList = new PriorityQueue<>(nodeComparator);
openList.add(start);
while (!openList.isEmpty()) {
Node current = openList.poll();
closedList.add(current);
if (current.h == 0) {
reconstructPath(current);
break;
}
ArrayList<Node> children = current.getChildren();
for (Node child : children) {
if (closedList.contains(child) || openList.contains(child) && child.g >= current.g) {
continue;
}
child.g = current.g + 1;
child.f = child.g + child.h;
if(openList.contains(child)){
openList.remove(child);
openList.add(child);
}else {
openList.add(child);
}
}
}
}
public static void main(String[] args) {
int puzzle[][] = {{6, 2, 1},
{0, 4, 3},
{5, 8, 7}};
long start = System.nanoTime();
new SlidingPuzzle(puzzle);
long stop = System.nanoTime();
double time = (stop - start) / 1000000000.0;
System.out.println("Time: " +time);
}
}
</code></pre>
<p>Any help is really appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:06:10.287",
"Id": "425431",
"Score": "0",
"body": "You might be interested in [this](https://github.com/coderodde/LibID/tree/master/src/net/coderodde/libid)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T17:04:39.243",
"Id": "425439",
"Score": "0",
"body": "thx for the link."
}
] | [
{
"body": "<p><strong>Advice 1: <code>l_moves</code></strong></p>\n\n<ol>\n<li>The name <code>l_moves</code> is ain't good at all. Consider <code>numberOfMoves</code>.</li>\n<li>Since it is only read, make it a constant. Even better, it is customary in Java to name the constants with <strong><em>capital</em></strong> case. For this particular case, I suggest you rename <code>l_moves</code></li>\n</ol>\n\n<p><code>private static final int NUMBER_OF_MOVES = 4;</code></p>\n\n<p><strong>Advice 2: class SlidingPuzzle</strong></p>\n\n<p>I suggest you rename it to, say, <code>SlidingPuzzleSolver</code>.</p>\n\n<p><strong>Advice 3: class Node</strong></p>\n\n<p>I suggest you take it out of <code>SlidingPuzzle</code> and make a dedicated .java file for it.</p>\n\n<p><strong>Advice 4: Do not store search state in the actual puzzle nodes</strong></p>\n\n<pre><code>Node previous;\nint f, h, g;\n</code></pre>\n\n<p><strong>Advice 5: implement <code>hashCode</code></strong></p>\n\n<p>Implementing <code>hashCode</code> of <code>SlidingPuzzle.Node</code> makes it possible for storing the puzzle nodes in a, say, <code>HashSet</code> or <code>HashMap</code> as a key.</p>\n\n<p><strong>Advice 6: on <code>printBoard</code></strong></p>\n\n<p>Why not override <code>toString</code> for <code>Node</code>?</p>\n\n<p><strong>Advice 7: on <code>reconstructPath</code></strong></p>\n\n<p>I suggest you construct the shortest path and <strong><em>return</em></strong> it to the caller instead of printing to console output. I had this in mind:</p>\n\n<pre><code>private List<Node> reconstructPath(Node current) {\n Deque<Node> deque = new ArrayDeque<>();\n int l = 0;\n\n while (current.previous != null) {\n current = current.previous;\n deque.addFirst(current); // Amortized O(1) for the ArrayDeque\n l++;\n }\n\n for (Node node : deque) {\n printBoard(node.puzzle);\n }\n\n //System.out.println(\"Solution length: \" + l);\n return new ArrayList<>(deque);\n}\n</code></pre>\n\n<p><strong>Advice 8: <code>ArrayList</code> as the closed list</strong></p>\n\n<p>No, no, no and no. <code>contains</code> for a any JDK <code>List</code> runs in linear time. <code>HashSet</code> could do the same in <span class=\"math-container\">\\$\\Theta(1)\\$</span>. For that to happen, go back to <strong>Advice 5</strong>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:27:35.947",
"Id": "425435",
"Score": "0",
"body": "Ok, thanks. I don't really understand Advice 4. Why I shouldn't store the puzzle state in my Node class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:56:00.850",
"Id": "425436",
"Score": "2",
"body": "@Marten You could, but it is not usual way of writing industrial level code. I suggest you use `HashMap` for storing these pathfinding-related data items. For example, you could have `HashMap<Node, Integer>` for that purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T17:03:13.963",
"Id": "425438",
"Score": "0",
"body": "Ok thx. In my getChildren() method I copy ervery time the board. Is it possible to get rid of it?(otherwise after swaping, list elements would change)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T18:48:58.910",
"Id": "425451",
"Score": "0",
"body": "@Marten I might be missing something but it doesn't look like you use the previous boards. So only maintain the current board (the one set on the primary class) and just don't copy it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T15:59:57.583",
"Id": "220186",
"ParentId": "220183",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220186",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T14:09:59.317",
"Id": "220183",
"Score": "3",
"Tags": [
"java",
"performance",
"algorithm",
"a-star",
"sliding-tile-puzzle"
],
"Title": "N-puzzle solver using A* search"
} | 220183 |
<p>I asked this question on Stack Overflow and was directed here. I'm working on a function that will help me quickly find all the upper structure triads (3-note chord) that I can add to a 4-note 7th chord to create a larger compound chord, as well of the roots and names of each triad. The example I'm testing right now is a 13#11 chord, which has the following degrees in a 12-note octave (when the root is 0): <code>[0, 2, 4, 6, 7, 9, 10]</code>*</p>
<p>*side note: <code>[0, 4, 6, 7, 9, 10]</code> would also match as a 13#11.</p>
<p>The base 7th chord is a dominant 7th: <code>[0, 4, 7, 10]</code>.I already know which triads complete the chord: a major triad on the 9th, <code>[2, 6, 9]</code>, and a diminished triad on the #11, <code>0, 6, 9</code> (only the <code>6</code> (#11th) and <code>9</code> (13th) are actually necessary to build a 13#11 chord; the <code>2</code> (9th) is optional).</p>
<p>I actually already have a function that will give me these results, I'm just wondering if there's a faster/more efficient way to do it? It just feels a little bulky/clunky right now.</p>
<p>On Stack Overflow @RobNapier suggested that I look at using Enums instead of String, [String], Int, and [Int]. I definitely get how Enums would help for my <code>triadQualities</code> array. I'm not sure what they would improve with the number combinations. Or what other improvements (enum-related or other) I can make. Can anyone help enlighten me? Any help would be appreciated.</p>
<h1>the code</h1>
<pre><code>extension Int {
func degreeInOctave() -> Int {
switch self {
case 0...11:
return self
case 12...:
return self - 12
default:
return self + 12
}
}
}
var ust: [Int] = [0, 2, 4, 6, 7, 9, 10]
let maj = [0, 4, 7]
let min = [0, 3, 7]
let aug = [0, 4, 8]
let dim = [0, 3, 6]
let sus4 = [0, 5, 7]
let sus2 = [0, 2, 7]
let triadDegs = [maj, min, aug, dim, sus4, sus2]
var triadRoots: [Int] = []
var triadQualities: [String] = []
func findUpperStructureTriads(degs: [Int]) {
let degCount = degs.count
var firstIndex = 0
while firstIndex < (degCount - 2) {
var secondIndex = firstIndex + 1
while secondIndex < (degCount - 1) {
var thirdIndex = secondIndex + 1
while thirdIndex < (degCount) {
var threeNoteGroup = [degs[firstIndex], degs[secondIndex], degs[thirdIndex]]
func checkForTriad(triad: [Int]) -> Bool {
if triadDegs.contains(triad) {
switch triad {
case maj:
triadQualities.append("major")
case min:
triadQualities.append("minor")
case aug:
triadQualities.append("augmented")
case dim:
triadQualities.append("diminished")
case sus4:
triadQualities.append("sus4")
case sus2:
triadQualities.append("sus2")
default:
()
}
return true
} else {
return false
}
}
if threeNoteGroup.contains(6), threeNoteGroup.contains(9){
var inversionCount = 0
var newGroup = threeNoteGroup.map {$0 - threeNoteGroup[0]}
while inversionCount < 3 {
func invert() {
newGroup = newGroup.map {($0 - newGroup[1]).degreeInOctave()}
let newlast = newGroup.remove(at: 0)
newGroup.append(newlast)
}
if checkForTriad(triad: newGroup) {
print(threeNoteGroup, threeNoteGroup[inversionCount])
triadRoots.append(threeNoteGroup[inversionCount])
break
}
invert()
inversionCount += 1
}
}
thirdIndex += 1
}
secondIndex += 1
}
firstIndex += 1
}
for i in 0...(triadRoots.count - 1) {
print(triadRoots[i], triadQualities[i])
}
}
findUpperStructureTriads(degs: ust)
</code></pre>
<h1>outputs</h1>
<pre><code>[0, 6, 9] 6
[2, 6, 9] 2
6 diminished
2 major
</code></pre>
<h1>clarifications</h1>
<p>The combined <code>ust</code> chord is always sorted from lowest to highest. Its elements can range between 0 and 11, and they never duplicate. The lower 4-note chord and upper 3-note chord get merged into one larger chord, lower chord first. If any number in the upper chord is already in the combined chord it doesn't get added twice. So if the lower chord is <code>[0, 4, 7, 10]</code> and the upper chord is <code>[2, 7, 10]</code>, <code>ust</code> would be <code>[0, 2, 4, 7, 10]</code>. And for that chord the outputs of the combinations function (ideally) would be something like:</p>
<pre><code>[0, 2, 7] 0
[2, 7, 10] 2
0 sus2
7 minor
</code></pre>
<p>Note: One thing I realized is that this function may not actually help my larger program—it would replace a function I'm already using that takes hard-coded Int arrays for every combined chord degree array and translates them into string formulas (i.e. [1, 2] = "min triad on the Maj 2nd"). So I've already done the work. And for the new function to work I'd need to figure out an if statement for which degrees are required for completion that changed for every possible chord quality. So this may all be moot </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T02:15:34.403",
"Id": "425473",
"Score": "0",
"body": "@MartinR the program works as intended currently—the issue with `ust = [0, 2, 4, 7, 10]` not working is fixable by changing this if statement `if threeNoteGroup.contains(6), threeNoteGroup.contains(9)`. But I'm not asking about that part (because I know how to fix it). I'm more asking whether the way I'm iterating through the combinations can be improved to be faster and/or take up fewer lines of code."
}
] | [
{
"body": "<p><em>Disclaimer:</em> I am not an expert in music theory, and english is not my first language. Therefore I may use the wrong terms in the following review.</p>\n\n<h3>Review of your current code</h3>\n\n<p>I/O should be separated from the computation. In your case, the <code>findUpperStructureTriads()</code> function should <em>return</em> something instead of printing it. That makes the function better usable and testable, and increases the clarity of the program.</p>\n\n<p>Also global variables (<code>triadRoots</code> and <code>triadQualities</code>) should be avoided: Calling <code>findUpperStructureTriads()</code> twice will show unexpected results.</p>\n\n<p>The nested loops are better and simpler written as for-loops over (half-open) ranges:</p>\n\n<pre><code>for firstIndex in 0 ..< degs.count {\n for secondIndex in firstIndex+1 ..< degs.count {\n for thirdIndex in secondIndex+1 ..< degs.count {\n // ...\n }\n }\n}\n</code></pre>\n\n<p>and similarly </p>\n\n<pre><code>for inversionCount in 0 ..< 2 { ... }\n</code></pre>\n\n<p>and</p>\n\n<pre><code>for i in 0..<triadRoots.count { ... }\n</code></pre>\n\n<p>Note that your version</p>\n\n<blockquote>\n<pre><code>for i in 0...(triadRoots.count - 1) { ... }\n</code></pre>\n</blockquote>\n\n<p>would crash with a “Fatal error: Can't form Range with upperBound < lowerBound” if <code>triadRoots.count</code> is zero.</p>\n\n<p>Use <code>let</code> for variables which are never mutated, e.g.</p>\n\n<pre><code>let threeNoteGroup = [degs[firstIndex], degs[secondIndex], degs[thirdIndex]]\n</code></pre>\n\n<p>The default case in <code>checkForTriad()</code> is a case which “should not occur” – unless you made a programming error. To detect such an error early, you can use</p>\n\n<pre><code>default:\n fatalError(\"Should never come here\")\n</code></pre>\n\n<p>But actually function can be replaced by a more efficient dictionary lookup:</p>\n\n<pre><code>let qualities: [[Int]: String] = [\n maj : \"major\",\n min : \"minor\",\n dim : \"diminished\",\n]\n\n// ...\n\nif let quality = qualities[newGroup] {\n print(threeNoteGroup, threeNoteGroup[inversionCount])\n triadRoots.append(threeNoteGroup[inversionCount])\n triadQualities.append(quality)\n break\n}\n</code></pre>\n\n<p>Reducing an integer note to an octave can be done with modulo arithmetic:</p>\n\n<pre><code>extension Int {\n var degreeInOctave: Int {\n let mod12 = self % 12\n return mod12 >= 0 ? mod12 : mod12 + 12\n }\n}\n</code></pre>\n\n<h3>An alternative approach</h3>\n\n<p>Your program tests each subset of three notes of the given degrees, and its three inversions if it is one of the known triads. It may be more efficient to traverse the given list only once and consider each note as the possible root note of each triad. Then you have only to test if the other notes of the triad are in the list or not.</p>\n\n<h3>More structure</h3>\n\n<p>Using <em>types</em> gives the objects we operate on a <em>name,</em> allows to group the functionality with the objects, provide initialization methods, etc.</p>\n\n<p>For example, instead of a plain array of notes (or is it degrees?) we can define a <code>Chord</code> structure:</p>\n\n<pre><code>struct Chord {\n let notes: [Int] // Increasing array of degrees in the range 0...11\n\n init(notes: [Int]) {\n // Reduce module 12 and sort:\n self.notes = notes.map { $0.degreeInOctave }.sorted()\n }\n\n func translated(by offset: Int) -> Chord {\n return Chord(notes: notes.map { $0 + offset })\n }\n}\n</code></pre>\n\n<p>The init method ensures that the numbers are sorted in increasing order and in the proper range. The <code>translated(by:)</code> method computes a new chord by shifting all degrees. More methods can be added later if needed, e.g.</p>\n\n<pre><code>struct Chord {\n mutating func invert() { ... }\n}\n</code></pre>\n\n<p>for chord inversion.</p>\n\n<p>Triads could be defined as an <em>enumeration:</em> </p>\n\n<pre><code>enum Triad: String, CaseIterable {\n case major\n case minor\n case augmented\n case diminished\n case sus4\n case sus2\n\n var chord: Chord {\n switch self {\n case .major: return Chord(notes: [ 0, 4, 7 ])\n case .minor: return Chord(notes: [ 0, 3, 7 ])\n case .augmented: return Chord(notes: [ 0, 4, 8 ])\n case .diminished: return Chord(notes: [ 0, 3, 6 ])\n case .sus4: return Chord(notes: [ 0, 5, 7 ])\n case .sus2: return Chord(notes: [ 0, 2, 7 ])\n }\n }\n}\n</code></pre>\n\n<p>Instead of global variables (<code>maj</code>, <code>min</code>, ...) we can now refer to a triad as values of the enumeration, e.g.</p>\n\n<pre><code>let triad = Triad.major\nprint(triad) // major\nprint(triad.chord) // Chord(notes: [0, 4, 7])\n</code></pre>\n\n<p>and with the conformance to <code>CaseIterable</code> we get the list of all triads for free:</p>\n\n<pre><code>for triad in Triad.allCases { ... }\n</code></pre>\n\n<p>Finally we need a type for the results, which are triads at a certain position, for example:</p>\n\n<pre><code>struct UpperStructure: CustomStringConvertible {\n let triad: Triad\n let root: Int\n\n var description: String {\n return \"\\(root) \\(triad.rawValue)\"\n }\n}\n</code></pre>\n\n<p>The <code>description</code> method provides the textual representation of the values, and can be adjusted to your needs.</p>\n\n<p>With these preparations, we can define a function to find all upper structure triads in a given chord. This can be a <em>method</em> of the <code>Chord</code> type instead of a global function, so that we now have</p>\n\n<pre><code>struct Chord {\n let notes: [Int]\n\n init(notes: [Int]) {\n self.notes = notes.map { $0.degreeInOctave }.sorted()\n }\n\n func translated(by offset: Int) -> Chord {\n return Chord(notes: notes.map { $0 + offset })\n }\n\n func upperStructureTriads() -> [UpperStructure] {\n let notesSet = Set(notes)\n var result: [UpperStructure] = []\n\n for rootNote in notes {\n for triad in Triad.allCases {\n let chordNotes = triad.chord.translated(by: rootNote).notes\n if chordNotes.contains(6) && chordNotes.contains(9)\n && notesSet.isSuperset(of: chordNotes) {\n result.append(UpperStructure(triad: triad, root: rootNote))\n }\n }\n }\n\n return result\n }\n}\n</code></pre>\n\n<p>All possible combinations of root notes and triads are tested, and a <code>Set</code> is used to make the containment test efficient.</p>\n\n<p>Usage example:</p>\n\n<pre><code>let chord = Chord(notes: [0, 2, 4, 6, 7, 9, 10])\nlet upperStructures = chord.upperStructureTriads()\nfor us in upperStructures {\n print(us)\n}\n\n// 2 major\n// 6 diminished\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:09:56.230",
"Id": "425522",
"Score": "1",
"body": "No upper structures are found in these notes `[0, 2, 4, 7, 10]`, or am I mistaken?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:11:45.263",
"Id": "425524",
"Score": "1",
"body": "@ielyamani:Yes (as in OP's code), because it does not contain 6 or 9. See OP's comment at the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:12:57.433",
"Id": "425525",
"Score": "1",
"body": "In this case, shouldn't the upper structures contain 2 and 7 instead? Just like in the expected result?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:16:43.483",
"Id": "425526",
"Score": "1",
"body": "@ielyamani: I have implemented the same logic as in the original code, which tests `if threeNoteGroup.contains(6), threeNoteGroup.contains(9)` and therefore does not find upper structures in `[0, 2, 4, 7, 10]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T20:33:34.357",
"Id": "425543",
"Score": "0",
"body": "@MartinR Thank you for this! This is extremely helpful! I haven't had a chance to fully digest all of it yet (or try it out) but it looks like there is ton for me to work with here. As for the `[0, 2, 4, 7, 10]` case, `2` would be the upper structure note as it's the 9th and not already in the base chord (`[0, 4, 7, 10]`. So if any triad contained 2 it would complete the chord."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T19:55:33.187",
"Id": "425659",
"Score": "0",
"body": "@MartinR It's perfect! I used the alternative approach from your answer; also figured out how to easily account for different `Chords`. I changed `func upperStructureTriads()` to take a parameter `upStrNotes: [Int]`, which I used to test if a triad would complete the chord: `if Set(chordNotes).isSuperset(of: upStrNotes) && notesSet.isSuperset(of: chordNotes) { ... }`. I also added an enclosing if statement to test for if the `Chord` doesn't have any upper structure notes, and if not, simply used `if notesSet.isSuperset(of: chordNotes) { ... }` instead. Thanks again, I really appreciate it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:26:04.703",
"Id": "425661",
"Score": "1",
"body": "@JacobSmolowe: You are welcome! If I ever happen to be in SF you can give me a free piano lesson :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:59:07.360",
"Id": "425665",
"Score": "0",
"body": "@MartinR happily!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:11:31.230",
"Id": "425819",
"Score": "0",
"body": "@MartinR curious, why is `degreeInOctave` a var rather than a function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T05:45:41.003",
"Id": "425846",
"Score": "0",
"body": "@JacobSmolowe: Both is possible, and I admit that I did not think much about it. You'll find discussions about “computed property or function” e.g. [here](https://stackoverflow.com/q/24035276/1187415) and [here](https://softwareengineering.stackexchange.com/q/304077/83021). It is a simple O(1) algorithm which returns the same result on each invocation (like `.magnitude`), which justifies a computed property. On the other hand, `signum()` is a function and not a computed property ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T17:27:55.163",
"Id": "425984",
"Score": "0",
"body": "@MartinR ah thanks. Sounds like this is an opportunity for me to look into best practices for computed properties."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T08:25:28.803",
"Id": "220221",
"ParentId": "220187",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220221",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:07:12.963",
"Id": "220187",
"Score": "3",
"Tags": [
"array",
"swift",
"combinatorics",
"enum",
"music"
],
"Title": "Swift function to find a specific set of combinations of 3 digits within a larger integer array"
} | 220187 |
<p>New to Rust and would like some clarification on idiomatic and readable use of Result and Error types. Here I'm simply connecting to a database using Diesel. In my opinion, the use of match and Boxing error makes be feel like there's a more concise but still readable way to do this.</p>
<pre class="lang-rust prettyprint-override"><code>fn establish_database_connection() -> Result<PgConnection, Box<std::error::Error>> {
dotenv().ok();
let database_url = match env::var("DATABASE_URL") {
Ok(url) => url,
Err(err) => return Err(Box::new(err)),
};
match PgConnection::establish(&database_url) {
Ok(connection) => Ok(connection),
Err(err) => Err(Box::new(err)),
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:16:34.957",
"Id": "220188",
"Score": "3",
"Tags": [
"error-handling",
"database",
"rust"
],
"Title": "Connect to a database with Diesel"
} | 220188 |
<p>I made a snake game in sfml and i'm kind of proud of the code's structure, but proud doesn't mean it's good, so i'm putting it here so that if there is something that could be bettered, you would know.</p>
<p><strong>main.cpp</strong></p>
<pre><code>#ifndef UNICODE
#define UNICODE
#endif
#include "app.h"
int main() {
app game(800, 600, L"Test");
game.start();
game.end();
}
</code></pre>
<p><strong>app.h</strong></p>
<pre><code>#pragma once
#include <SFML/Graphics.hpp>
#include "Snake.h"
#include "Board.h"
class app {
public:
app(int windowWidth, int windowHeight, const wchar_t* name);
~app() = default;
// Runs the app
void start();
void end();
private:
// MEMBER VARIABLES
const int winWidth, winHeight;
int score;
bool play;
sf::RenderWindow window;
Snake snake;
Board board;
// MEMBER FUNCTIONS
// Draws the objects
void drawWindow();
// Handles events
void handleEvents();
// Updates the window
void updateWindow();
};
</code></pre>
<p><strong>app.cpp</strong></p>
<pre><code>#include "app.h"
#include <iostream>
#include <thread>
#include <chrono>
app::app(int windowWidth, int windowHeight, const wchar_t* name)
: winWidth{ windowWidth }, winHeight{ windowHeight }, score{ 0 },
play{ false } {
while (true) {
int choice;
std::wcout << L"Choose: " << std::endl;
std::wcout << L"1: Play " << std::endl;
std::wcout << L"2: Quit " << std::endl;
std::cin >> choice;
if (choice == 1) {
play = true;
break;
}
else break;
}
// Clears screen
for (size_t i = 0; i < 10; ++i)
std::wcout << L"\n\n\n\n\n\n\n\n\n\n\n\n" << std::endl;
if (play) {
window.create(sf::VideoMode(winWidth, winHeight), name);
window.setFramerateLimit(5);
}
}
// Handles any game event
void app::handleEvents() {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::TextEntered:
snake.changeDirection(static_cast<char>(event.text.unicode));
}
}
}
// Draws all game objects
void app::drawWindow() {
for (size_t i = 0, h = board.height(); i < h; ++i) {
for (size_t j = 0, w = board.width(); j < w; ++j) {
// Draws walls
if (board[i * w + j] == 2) {
sf::RectangleShape rect;
rect.setSize({ static_cast<float>(board.divisor()), static_cast<float>(board.divisor()) });
rect.setPosition({ static_cast<float>(board.divisor() * j), static_cast<float>(board.divisor() * i)});
window.draw(rect);
}
// Draws snake
else if (board[i * w + j] == 3) {
sf::RectangleShape rect;
rect.setFillColor(sf::Color::Green);
rect.setSize({ static_cast<float>(board.divisor()), static_cast<float>(board.divisor()) });
rect.setPosition({ static_cast<float>(board.divisor() * j), static_cast<float>(board.divisor() * i) });
window.draw(rect);
}
// Draws food
else if (board[i * w + j] == 4) {
sf::RectangleShape rect;
rect.setFillColor(sf::Color::Red);
rect.setSize({ static_cast<float>(board.divisor()), static_cast<float>(board.divisor()) });
rect.setPosition({ static_cast<float>(board.divisor() * j), static_cast<float>(board.divisor() * i) });
window.draw(rect);
}
}
}
}
// Updates the render window
void app::updateWindow() {
window.clear(sf::Color::Black);
drawWindow();
window.display();
}
// Starts the app
void app::start() {
while (window.isOpen()) {
handleEvents();
snake.move();
board.update(window, snake, &score);
updateWindow();
}
}
void app::end() {
if (play) {
std::wcout << L"You lose!" << std::endl;
std::wcout << L"Score: " << score << std::endl;
std::this_thread::sleep_for((std::chrono::milliseconds)3000);
}
}
</code></pre>
<p><strong>Snake.h</strong></p>
<pre><code>#pragma once
#include <SFML/Graphics.hpp>
#include <vector>
class Snake {
public:
Snake();
~Snake() = default;
// Changes the dir value based on the input
void changeDirection(char input);
// Adds a piece to the snake
void add();
// Returns the size of snakeContainer
size_t getSnakeSize();
// Moves the snake
void move();
private:
// MEMBER VARIABLES
struct Snake_segment
{
int xPos, yPos, prevxPos, prevyPos;
};
const enum direction {
UP = 0,
RIGHT,
DOWN,
LEFT
};
std::vector<Snake_segment> snakeContainer;
direction dir;
// MEMBER FUNCTIONS
// Makes the segments follow the head
void follow();
// Moves the snake's head
void moveHead();
public:
// Operator overloading (i wasn't able to declare it in .cpp file)
Snake_segment operator[](int i) { return snakeContainer[i]; }
};
</code></pre>
<p><strong>Snake.cpp</strong></p>
<pre><code>#include "Snake.h"
// Initializes a two-piece snake
Snake::Snake()
: dir { RIGHT } {
Snake_segment head { 10, 7, 9, 7 };
snakeContainer.push_back(head);
--head.xPos;
snakeContainer.push_back(head);
}
void Snake::add() {
Snake_segment newSegment;
newSegment.xPos = snakeContainer[snakeContainer.size() - 1].prevxPos;
newSegment.yPos = snakeContainer[snakeContainer.size() - 1].prevyPos;
snakeContainer.push_back(newSegment);
}
size_t Snake::getSnakeSize() {
return snakeContainer.size();
}
// Changes the direction based on input
void Snake::changeDirection(char input) {
switch (input) {
case 'w':
if (dir != DOWN) dir = UP;
break;
case 'd':
if (dir != LEFT) dir = RIGHT;
break;
case 's':
if (dir != UP) dir = DOWN;
break;
case 'a':
if (dir != RIGHT) dir = LEFT;
}
}
// All the pieces follow the head
void Snake::follow() {
for (size_t i = 1, n = snakeContainer.size(); i < n; ++i) {
snakeContainer[i].prevxPos = snakeContainer[i].xPos;
snakeContainer[i].prevyPos = snakeContainer[i].yPos;
snakeContainer[i].xPos = snakeContainer[i - 1].prevxPos;
snakeContainer[i].yPos = snakeContainer[i - 1].prevyPos;
}
}
// Moves the snake's head
void Snake::moveHead() {
snakeContainer[0].prevxPos = snakeContainer[0].xPos;
snakeContainer[0].prevyPos = snakeContainer[0].yPos;
switch (dir) {
case UP:
--snakeContainer[0].yPos;
break;
case RIGHT:
++snakeContainer[0].xPos;
break;
case DOWN:
++snakeContainer[0].yPos;
break;
case LEFT:
--snakeContainer[0].xPos;
}
}
// Moves the snake
void Snake::move() {
moveHead();
follow();
}
</code></pre>
<p><strong>Board.h</strong></p>
<pre><code>#pragma once
#include <SFML/Graphics.hpp>
#include "Snake.h"
class Board {
public:
Board();
~Board() = default;
void update(sf::RenderWindow& win, Snake& snek, int* scor);
int width() const;
int height() const;
int divisor() const;
char operator[](int i) const;
private:
// MEMBER VARIABLES
std::string map;
const size_t mapWidth = 20;
const size_t mapHeight = 15;
// Is used to divide the screen in a grid
const int common_divisor = 40;
// MEMBER FUNCTIONS
// Checks if snek has collided with something
void genFood();
void checkCollisions(sf::RenderWindow& win, Snake& snek, int* scor);
};
</code></pre>
<p><strong>Board.cpp</strong></p>
<pre><code>#include "Board.h"
#include <random>
Board::Board() {
// Creates a 20x15 grid
map = {
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
};
/*
REMINDER:
1 = FREE SPACE
2 = WALL
3 = SNAKE
4 = FOOD
*/
genFood();
}
void Board::genFood() {
int fx, fy;
do {
std::random_device gen;
std::uniform_int_distribution<int> disX(1, mapWidth - 1);
std::uniform_int_distribution<int> disY(1, mapHeight - 1);
fx = disX(gen);
fy = disY(gen);
} while (map[fy * mapWidth + fx] != 1);
map[fy * mapWidth + fx] = 4;
}
void Board::update(sf::RenderWindow& win, Snake& snek, int* scor) {
checkCollisions(win, snek, scor);
// Iterates through the whole map
for (size_t i = 0; i < mapHeight; ++i) {
for (size_t j = 0; j < mapWidth; ++j) {
// Makes walls
if (i == 0 || i == mapHeight - 1) map[i * mapWidth + j] = 2;
else if (j == 0 || j == mapWidth - 1) map[i * mapWidth + j] = 2;
// Sets free space
else if (map[i * mapWidth + j] != 4) map[i * mapWidth + j] = 1;
// Sets snek
for (size_t k = 0, n = snek.getSnakeSize(); k < n; ++k) {
if (snek[k].yPos == i && snek[k].xPos == j)
map[i * mapWidth + j] = 3;
}
}
}
}
void Board::checkCollisions(sf::RenderWindow& win, Snake& snek, int* scor) {
for (size_t i = 0; i < mapHeight; ++i) {
for (size_t j = 0; j < mapWidth; ++j) {
// Checks snek and wall collisions
if (map[snek[0].yPos * mapWidth + snek[0].xPos] == 2 ||
map[snek[0].yPos * mapWidth + snek[0].xPos] == 3 ) win.close();
// Checks snek and food collisions
else if (map[snek[0].yPos * mapWidth + snek[0].xPos] == 4) {
map[snek[0].yPos * mapWidth + snek[0].xPos] = 1;
snek.add();
*scor += 100;
genFood();
}
}
}
}
int Board::width() const { return mapWidth; }
int Board::height() const { return mapHeight; }
int Board::divisor() const { return common_divisor; }
char Board::operator[](int i) const { return map[i]; }
</code></pre>
| [] | [
{
"body": "<p>Some observations:</p>\n\n<ul>\n<li><p><strong>Comments</strong>:</p>\n\n<pre><code>// Draws the objects\nvoid drawWindow();\n\n// Handles events\nvoid handleEvents();\n\n// Updates the window\nvoid updateWindow();\n</code></pre>\n\n<p>These comments don't tell you anything that the code doesn't already\ntell you, so they should be removed. Ideally the code is well named,\nlike in that example, so you don't feel the need to even write a comment.</p>\n\n<p>Annother advice with that is. If you feel the need, in a long function,\nto comment several parts because they do something different it's probably a\ngood idea to extract the parts into its own functions. Erase the\nComments and makes the code self documentary.</p></li>\n<li><p><strong>Namespaces</strong>:</p>\n\n<p>You should always put your functions and classes into namespaces to avoid name clashes.</p></li>\n<li><p><strong>unicode</strong></p>\n\n<pre><code>#ifndef UNICODE\n#define UNICODE\n#endif\n</code></pre>\n\n<p>is this still needed?</p></li>\n<li><p><strong>std::endl</strong>:</p>\n\n<p>if you only want a newline you should replace <code>std::endl</code>\nwith <code>'\\n'</code>. </p>\n\n<p><code>std::endl</code> also does a expensive flush operation which is\nrarely desired.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T18:57:07.440",
"Id": "425535",
"Score": "0",
"body": "Really i defined unicode since i've seen on multiple occasions that unicode is now the standard and writing unicode literals is good practice, on Windows docs too. That's why i always define unicode"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-25T12:15:23.473",
"Id": "427080",
"Score": "1",
"body": "Pretty sure all compilers today define it for you, you don't need to define it yourself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T16:07:49.247",
"Id": "220240",
"ParentId": "220189",
"Score": "3"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Don't declare <code>enum</code> <code>const</code></h2>\n\n<p>In <code>snake.h</code>, the <code>direction</code> <code>enum</code> is declared as <code>const</code> but this is an error, since only functions and objects can be declared <code>const</code>.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>Snake::getSnakeSize()</code> doesn't alter the underlying <code>Snake</code> and so it should be declared <code>const</code>. Additionally, I'd name it <code>size()</code> to be consistent with standard library functions.</p>\n\n<h2>Simplify your code</h2>\n\n<p>The current <code>Snake::add()</code> code is this:</p>\n\n<pre><code>void Snake::add() {\n\n Snake_segment newSegment;\n newSegment.xPos = snakeContainer[snakeContainer.size() - 1].prevxPos;\n newSegment.yPos = snakeContainer[snakeContainer.size() - 1].prevyPos;\n\n snakeContainer.push_back(newSegment);\n}\n</code></pre>\n\n<p>However, it could be simplified into a single line:</p>\n\n<pre><code>void Snake::add() {\n snakeContainer.push_back({\n snakeContainer.back().prevxPos, \n snakeContainer.back().prevyPos, \n snakeContainer.back().prevxPos, \n snakeContainer.back().prevyPos, \n });\n}\n</code></pre>\n\n<p>Similarly, the <code>follow</code> code could be simplified by using iterators.</p>\n\n<pre><code>void Snake::follow() {\n auto it = snakeContainer.begin();\n for (auto prev = it++; it != snakeContainer.end(); ++it, ++prev) {\n it->prevxPos = it->xPos;\n it->prevyPos = it->yPos;\n it->xPos = prev->prevxPos;\n it->yPos = prev->prevyPos;\n }\n}\n</code></pre>\n\n<p>In both of these case, futher simplification could be obtained by introducing a <code>struct Coord { unsigned x, y; };</code></p>\n\n<pre><code>void Snake::follow() {\n auto it = snakeContainer.begin();\n for (auto prev = it++; it != snakeContainer.end(); ++it, ++prev) {\n it->prev = it->curr;\n it->curr = prev->prev;\n }\n}\n</code></pre>\n\n<h2>Use <code>static constexpr</code> for class constants</h2>\n\n<p>The current code has internal <code>const</code> variables for the width and height and then wrapper accessors, but this is much simplified by simply using public <code>static constexpr</code> variables and no wrapper. That's assuming you have a C++11 compiler. If not, the next best thing would be plain <code>const</code> and no wrapper.</p>\n\n<h2>Reconsider the class interfaces</h2>\n\n<p>Mostly the classes make sense to me, but it seems that the <code>score</code> should actually be maintained by the <code>Board</code> class and then returned to a caller on request via a <code>const</code> method. Also, it seems that <code>divisor</code> should be calculated and stored by the <code>app</code> class as a <code>float</code>. This would remove a lot of ugly <code>static_cast</code>s as well. Also, it may make sense for the <code>Board</code> to own the <code>Snake</code>.</p>\n\n<h2>Add helper functions for clarity</h2>\n\n<p>I would advise converting from a comment to an <code>enum</code> or an <code>enum class</code> and then using that. </p>\n\n<pre><code>enum Tile { Open = 1, Wall, Body, Food };\n</code></pre>\n\n<p>Next, I'd suggest using helper functions to make the code easier to read and understand. For example:</p>\n\n<pre><code>bool Board::isEmpty(Coord coord) const {\n return at(coord) == Open;\n}\n\nbool Board::place(Coord coord, int item) {\n if (item != Open && !isEmpty(coord)) {\n return false;\n }\n map[coord.y * width + coord.x] = item;\n return true;\n}\n\nint Board::at(Coord coord) const {\n return map[coord.y * width + coord.x];\n}\n</code></pre>\n\n<p>Here's the corresponding <code>update</code> function.</p>\n\n<pre><code>void Board::update(sf::RenderWindow& win) {\n auto newHead{snake.moveHead()};\n place(snake.follow(), Open);\n switch (at(snake.headLocation())) {\n case Wall: \n case Body: \n win.close();\n break;\n case Food: \n place(snake.headLocation(), Open);\n place(snake.add(), Body);\n m_score += 100;\n genFood();\n }\n place(newHead, Body);\n}\n</code></pre>\n\n<p>With this, note that there is no longer any need to loop through all coordinates and no need for a separate collision detection routine. Also, <code>move</code> is eliminated in favor of the two distinct calls that were in it. In this rewrite, <code>moveHead()</code> returns the location of the new head, and <code>follow()</code> returns the old location of the last segment. Since those are the only two nodes of the snake that change from one iteration to the next, those are the only two cells that need updating.</p>\n\n<h2>Don't use <code>std::endl</code> if <code>'\\n'</code> will do</h2>\n\n<p>Using <code>std::endl</code> emits a <code>\\n</code> and flushes the stream. Unless you really need the stream flushed, you can improve the performance of the code by simply emitting <code>'\\n'</code> instead of using the potentially more computationally costly <code>std::endl</code>. Also, you can make things a little neater. Instead of this:</p>\n\n<pre><code> std::wcout << L\"You lose!\" << std::endl;\n std::wcout << L\"Score: \" << score << std::endl;\n\nI would recommend writing it like this: \n\n std::wcout << L\"You lose!\\nScore: \" << score << '\\n';\n</code></pre>\n\n<h2>Don't overuse <code>std::random_device</code></h2>\n\n<p>For some implementations, <code>std::random_device</code> is actually driven by a hardware-based generator and the quality of the generated random numbers may actually drop precipitously if too many random numbers are drawn too quickly. For that reason, it's better not to overuse <code>std::random_device</code>. Instead, seed a pseudorandom generator (PRG) once from <code>std::random_device</code> and then use the PRG. Here's a rewrite of the <code>genFood()</code> routine that does just that:</p>\n\n<pre><code>void Board::genFood() {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_int_distribution<unsigned> disX(1, width - 2);\n static std::uniform_int_distribution<unsigned> disY(1, height - 2);\n\n while (!place({disX(gen), disY(gen)}, Food))\n { /* keep attempting until it works */ }\n}\n</code></pre>\n\n<h2>Think of the user</h2>\n\n<p>How often does it happen that the user starts a game, only to immediately ask to quit? It seems unlikely to me, so I would eliminate the Play/Quit prompt entirely. Future enhancements that might be nice would be to display the score and length of snake as the game is being played.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:08:41.483",
"Id": "425727",
"Score": "0",
"body": "Thanks. I never used constexpr, since i really don't understand how it works. anyways i prompt the user play/quit at the start in case the run of the program was a mistake/ something the user didn't want to do, but now that i think about it yeah, you're right, it's pretty useless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:30:37.990",
"Id": "425744",
"Score": "0",
"body": "Anyways, i'd like to know why i should make the variables public, without getters and setters. I've always known public variables are a bad practice. Just curious"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:47:59.130",
"Id": "425758",
"Score": "1",
"body": "Public variables are only bad practice when external access to them is not required or when unrestricted external write access could allow an [invariant](https://softwareengineering.stackexchange.com/a/32755/252267) violation. Because external read-only access is required and because `const` enforces read-only access, making these `public` is the best way to write it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T23:35:02.027",
"Id": "220321",
"ParentId": "220189",
"Score": "8"
}
},
{
"body": "<blockquote>\n <p><code>while (true) {</code></p>\n</blockquote>\n\n<p>Some advise using <code>for (;;)</code> instead, but this loop really isn't necessary. But you don't even have a loop here; you'll exit the loop immediately no matter what is entered. Also this throws an exception if you enter a non-int.</p>\n\n<p>Clearing the terminal should be done in a separate routine in case you want to switch to a terminal library like curses. (Also terminal is not guaranteed to be 24x80)</p>\n\n<p>Try not to loop over the whole grid. See if you can avoid clearing and redrawing everything. Just make the necessary changes. When drawing the walls, think of a different encoding so you don't have to loop over the whole grid.</p>\n\n<p>\"divisor\" is a bad name for the size of a grid cell.</p>\n\n<p>snake color should be a parameter rather than a literal. Also the snake should draw itself, and <code>drawWindow</code> should call it.</p>\n\n<p>In <code>SnakeContainer</code> types, use a bit more encapsulation, include <code>xpos</code> and <code>ypos</code> together in a <code>struct pos</code> to cut down on duplicated code..</p>\n\n<p>Shouldn't the snake be a member of the board, not a parameter?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-25T12:16:43.670",
"Id": "220983",
"ParentId": "220189",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:16:49.897",
"Id": "220189",
"Score": "8",
"Tags": [
"c++",
"beginner",
"snake-game",
"sfml"
],
"Title": "SFML snake game in C++"
} | 220189 |
<p>I've been working in statically typed languages for awhile, and I've had to write some Python utilities recently. As part of those tools, I needed a semi-sane way to implement type checking to make it easier to understand the target type I'm working with.</p>
<pre class="lang-py prettyprint-override"><code> def type_of(val: Any, target_type: Any) -> bool:
"""
Safely check to see if a value is typeOf(type).
:param val: Value or variable to check.
:param target_type: Type you want to check. It's important to know booleans are a subclass of integers, so t(False, (int,bool)) -> True
:return:
"""
try:
if isinstance(val, bool) and cast_to(val, bool):
return True
if isinstance(val, target_type):
return True
else:
return False
except ValueError:
return False
def cast_to(val: Any, target_type: [int, bool, str, list]) -> (bool, [int, bool, str, list]):
"""
If a value can be cast as that type, it will be.
:param val: Value to be cast.
:param target_type: Destination type.
:return bool, [int, bool, str, list]: Returns True if it can be base with the proper type; False if not, with the value type.
"""
try:
# if it's an int and greater than 1 or less than zero, it can't be a bool
if (isinstance(val, int) and ((val > 1) or (val < 0))) and target_type is bool:
return False, val
nval = target_type(val)
if isinstance(nval, target_type):
return True, nval
else:
return False, val
except ValueError:
return False, val
</code></pre>
<p>It generally works as intended until I get to booleans, which I recently learned are a subclass of integers, and I've had problems consistently determining if something is a boolean. How can I improve my type check to properly handle booleans?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T17:19:43.963",
"Id": "425440",
"Score": "1",
"body": "Just an FYI there's another way to check type, but it doesn't care about inheritance. `isinstance(True, int), type(True) is int` -> `(True, False)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:33:28.833",
"Id": "425517",
"Score": "0",
"body": "For my edification: WHY would you do that?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:17:41.430",
"Id": "220190",
"Score": "1",
"Tags": [
"python",
"type-safety"
],
"Title": "typeOf in Python"
} | 220190 |
<p>I have some imminent interviews and want to sharpen my game before going into them. I'm running through some practice problems. This <a href="https://leetcode.com/problems/add-two-numbers/" rel="nofollow noreferrer">LeetCode challenge</a> is to add two numbers represented as linked lists.</p>
<p>If you can critique this solution quite harshly, as though you would in a full-fledged SWE interview, I'd greatly appreciate it. I'm particularly concerned about memory usage and variable names.</p>
<pre class="lang-py prettyprint-override"><code># Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
final_l = None
curr_l = None
remainder = 0
while l1 or l2:
digit = 0
if l1:
digit += l1.val
l1 = l1.next
if l2:
digit += l2.val
l2 = l2.next
if remainder != 0:
digit += remainder
remainder = digit // 10
digit = digit % 10
if final_l is None:
final_l = ListNode(digit)
curr_l = final_l
else:
curr_l.next = ListNode(digit)
curr_l = curr_l.next
if remainder > 0:
curr_l.next = ListNode(remainder)
return final_l
</code></pre>
| [] | [
{
"body": "<p><strong>A bit of scaffolding</strong></p>\n\n<p>In order to test/review your code, I had to write a bit of additional code. In case it can be relevant to you or other reviewers, here it is:</p>\n\n<pre><code># Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n def __eq__(self, other):\n ret = other is not None and self.val == other.val and self.next == other.next\n # print(self, other, ret)\n return ret\n\n @classmethod\n def from_list(cls, l):\n ret = ln = cls(l.pop(0))\n while l:\n e = l.pop(0)\n ln.next = cls(e)\n ln = ln.next\n return ret\n\n def to_list(self):\n l = [self.val]\n return l if self.next is None else l + self.next.to_list()\n\nclass Solution:\n ...\n\n @staticmethod\n def ListNodeFromInt(n):\n return ListNode.from_list([int(d) for d in reversed(str(n))])\n\n @staticmethod\n def testAddTwoNumbersUsingNumbers(n1, n2):\n l1 = Solution.ListNodeFromInt(n1)\n l2 = Solution.ListNodeFromInt(n2)\n expected_add = Solution.ListNodeFromInt(n1 + n2)\n add = Solution().addTwoNumbers(l1, l2)\n print(n1, n2, n1 + n2, expected_add.to_list(), add.to_list())\n assert expected_add == add\n\n\n @staticmethod\n def unitTests():\n # Edge cases\n Solution.testAddTwoNumbersUsingNumbers(0, 0)\n Solution.testAddTwoNumbersUsingNumbers(342, 0)\n Solution.testAddTwoNumbersUsingNumbers(0, 342)\n # Same length\n Solution.testAddTwoNumbersUsingNumbers(342, 465)\n # Different length\n Solution.testAddTwoNumbersUsingNumbers(342, 46)\n # Return longer than input\n Solution.testAddTwoNumbersUsingNumbers(999, 999)\n\nSolution.unitTests()\n</code></pre>\n\n<p>This is pretty poorly organised but it is quick and dirty.\nNow starts the actual review</p>\n\n<p><strong>Overall review</strong></p>\n\n<p>Your code looks good. The API is a bit awkward but it is a limitation from the programming challenge platform.</p>\n\n<p>A few details can be improved anyway.</p>\n\n<p><strong>Remove non-required checks</strong></p>\n\n<p>Instead of:</p>\n\n<pre><code> if remainder != 0: \n digit += remainder\n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code> digit += remainder\n</code></pre>\n\n<p><strong>Use builtins</strong></p>\n\n<p>The builtin <a href=\"https://docs.python.org/3.8/library/functions.html#divmod\" rel=\"nofollow noreferrer\"><code>divmod</code></a> is not the most famous but it is convenient for a pretty usual task: compute both the quotient and the remainder.</p>\n\n<p>Instead of:</p>\n\n<pre><code> remainder = digit // 10\n digit = digit % 10 \n</code></pre>\n\n<p>You can write:</p>\n\n<pre><code> remainder, digit = divmod(digit, 10)\n</code></pre>\n\n<p><strong>Different strategy</strong></p>\n\n<p>Instead of having a function to perform all the steps in one go, you could split the problem: define a function computing the sum of the 2 list as an integer and a function to convert that number into a list. Adding values bigger than 9 may be what we are trying to avoid though... </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T17:50:56.997",
"Id": "220196",
"ParentId": "220192",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:23:15.433",
"Id": "220192",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"linked-list",
"interview-questions"
],
"Title": "Adding two numbers represented as linked lists"
} | 220192 |
<p>I have solved a seemingly easy problem:</p>
<blockquote>
<p>Given a square matrix, calculate the absolute difference between the sums of its diagonals.</p>
</blockquote>
<p>For example, the square matrix is shown below:
<span class="math-container">$$\begin{bmatrix} 1\, 1\, 1 \\ 2 \, 3\, 3 \\ 0\,1\,0\end{bmatrix}$$</span></p>
<p>The left-to-right diagonal = <span class="math-container">\$0+3+1=4\$</span>. The right to left diagonal <span class="math-container">\$1+3+0=4\$</span>. Their absolute difference is <span class="math-container">\$0\$</span>.</p>
<p>However, I am a beginner in C and had some troubles. It took me way too long :D. Also, I tried to abstract the problem on a higher level - which does not mean it is high. However, I am not sure how far I should abstract the problem in such challenges.</p>
<ol>
<li><p>How well/bad is this code written?</p></li>
<li><p>Is the code abstract enough?</p></li>
<li><p>How can you solve such challenges more quickly?</p></li>
</ol>
<pre><code>int addDiagonal(int from_X,int to_X,int from_Y, int to_Y, int** arr){
int sum = 0;
int dirX = to_X - from_X;
if(dirX < 0) dirX = -1;
else if(dirX > 0) dirX = 1;
int dirY= to_Y - from_Y;
if(dirY < 0) dirY = -1;
else if(dirY > 0) dirY = 1;
while(from_X != to_X){
sum+=arr[from_X][from_Y];
from_X += dirX;
from_Y += dirY;
}
sum+=arr[from_X][from_Y];
return sum;
}
int diagonalDifference(int arr_rows, int arr_columns, int** arr) {
int left_to_right = addDiagonal(0,arr_columns-1,0,arr_rows-1,arr);
int right_to_left = addDiagonal(0, arr_columns-1,arr_rows-1,0,arr);
if(left_to_right - right_to_left > 0) return left_to_right - right_to_left;
return right_to_left - left_to_right;
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>How well/bad is this code written?</p>\n</blockquote>\n\n<p>A good first timer implementation.</p>\n\n<blockquote>\n <p>Is the code abstract enough?</p>\n</blockquote>\n\n<p>Mostly. It does make unnecessary assumptions about range. It assumes <code>int</code> math does not overflow.</p>\n\n<p>To make more abstract, code could use <code>typedef int TVS_int;</code> to ease future type changes.</p>\n\n<blockquote>\n <p>How can you solve such challenges more quickly?</p>\n</blockquote>\n\n<p>Take advantage that the matrix is <em>square</em>.</p>\n\n<p>With computing along the diagonal of a <em>square</em> matrix, only the matrix and its one size parameter are needed.</p>\n\n<p>Use <code>const</code> to hint the the compiler about certain potential optimizations and convey code's intent better.</p>\n\n<p><code>size_t</code> is the best size of array indexing, not too wide nor too narrow.</p>\n\n<p>I like the idea of using a wider intermediate type to mitigate overflow problems.</p>\n\n<pre><code>typedef int TVS_int;\ntypedef long long TVS_int2; // a type with wider range.\n\nTVS_int diagonalDifference_alt(const TVS_int** arr, size_t n) {\n TVS_int2 sum_up = 0;\n TVS_int2 sum_dn = 0;\n\n for (size_t i = 0; i<n; i++) {\n // Notice both `arr` use the same `arr[i]` --> potentially easier to optimize\n sum_up += arr[i][n-i-1];\n sum_dn += arr[i][i];\n }\n TVS_int2 diff = sum_up - sum_dn;\n return (TVS_int) ((diff < 0) ? -diff : diff); // OF possible here in range reduction \n}\n</code></pre>\n\n<hr>\n\n<p><code>if(left_to_right - right_to_left > 0)</code> unnecessarily incurs the potential for <code>int</code> overflow. Simply compare instead. <code>if (left_to_right > right_to_left)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T02:11:35.923",
"Id": "220392",
"ParentId": "220193",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220392",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T16:57:01.433",
"Id": "220193",
"Score": "2",
"Tags": [
"algorithm",
"c",
"matrix"
],
"Title": "Computing the difference of the cross-totals of the diagonals of a matrix"
} | 220193 |
<p>As a result of <a href="https://codereview.stackexchange.com/questions/216803/c-asynchronous-notification-vector">my previous post</a>, I have implemented / refactored my code and have started making successful use of my class. However I have come across a couple of new questions:</p>
<ol>
<li>The observer must call PopObjects() to consume the data in the vector. PopObjects() returns a bool so I don not have to check the vector count. However, this allows me put the call in a while loop which could never break if the data producer(s) are producing faster than I can consume. I think this concern out of the scope of this class or can it be solved easily within?</li>
<li>I like to assign values to my class members (simulating c++ initializer lists). Is this overkill?</li>
<li>I noticed I cannot instantiate my class unless I provide a null value or method to the constructor. Is making a private default constructor redundant in this case?</li>
</ol>
<hr>
<pre><code>using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace fAloha.Core
{
public class NotifyVector<T>
{
public delegate void NotifyCBR();
private Action notifyCbr_ = () => { }; // Noop;
private System.Collections.Generic.List<T> vector_;
private readonly Object dataSyncObject_ = new object();
private readonly object notifySyncObject_ = new object();
private volatile bool asyncNotfyInProgress_ = false;
// Class Instantiation requires a Callback routine
public NotifyVector(Action cbr)
{
if (cbr != null)
notifyCbr_ = cbr;
vector_ = new System.Collections.Generic.List<T>();
}
// Notify the Observer by asynchronous invocation of cbr
// Lock is used to reduce notifications. A producer could
// looping and adding many items adding one at a time.
public void Notify()
{
if (asyncNotfyInProgress_ == false)
{
lock (notifySyncObject_)
{
asyncNotfyInProgress_ = true;
Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromTicks(1));
notifyCbr_();
}).ContinueWith(AsyncResult =>
{
asyncNotfyInProgress_ = false;
});
}
}
}
// Threadsafe add for vector
public void AddObject(T obj)
{
lock (dataSyncObject_)
{
vector_.Add(obj);
}
}
// Threadsafe pop Objects from vector (swap all objects to Observer)
public bool PopObjects(ref System.Collections.Generic.List<T> inlist)
{
bool retval = false;
lock (dataSyncObject_)
{
if (vector_.Count > 0)
{
inlist = vector_;
vector_ = new System.Collections.Generic.List<T>();
retval = true;
}
}
return retval;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T22:18:13.947",
"Id": "425466",
"Score": "1",
"body": "Why the `await Task.Delay(TimeSpan.FromTicks(1));` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T13:06:53.910",
"Id": "425509",
"Score": "0",
"body": "Probably to make the task run asynchronous on a different thread. Normally you would use `Task.Yield()` for that."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T18:00:55.657",
"Id": "220197",
"Score": "1",
"Tags": [
"c#",
"asynchronous",
"thread-safety",
"callback"
],
"Title": "C# asynchronous notification vector v2"
} | 220197 |
<p><strong>The task</strong>
is taken from <a href="https://leetcode.com/problems/add-two-numbers/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>You are given two non-empty linked lists representing two non-negative
integers. The digits are stored in reverse order and each of their
nodes contain a single digit. Add the two numbers and return it as a
linked list.</p>
<p>You may assume the two numbers do not contain any leading zero, except
the number 0 itself.</p>
<p><strong>Example:</strong></p>
<p>Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)</p>
<p>Output: 7 -> 0 -> 8</p>
<p>Explanation: 342 + 465 = 807.</p>
</blockquote>
<p><strong>My solution:</strong></p>
<pre><code>function ListNode(val) {
this.val = val;
this.next = null;
}
const numberA3 = new ListNode(3);
const numberA2 = new ListNode(4);
numberA2.next = numberA3;
const numberA1 = new ListNode(2);
numberA1.next = numberA2;
const numberB3 = new ListNode(4);
const numberB2 = new ListNode(6);
numberB2.next = numberB3;
const numberB1 = new ListNode(5);
numberB1.next = numberB2;
var addTwoNumbers = function(l1, l2) {
let i = l1;
let j = l2;
let sum = new ListNode(null, null);
let rollover = 0;
let isFirst = true;
let first, previous;
const sanitize = x => (x && !isNaN(x.val)) ? x.val : 0;
while(i || j) {
let k = sanitize(i) + sanitize(j) + rollover;
rollover = 0;
if (k > 9) {
const tmp = k + '';
k = Number(tmp[1]);
rollover = Number(tmp[0]);
}
if (!isFirst) { previous = sum; }
sum = new ListNode(k, new ListNode(k));
if (!isFirst) { previous.next = sum; }
if (isFirst) { first = sum; }
isFirst = false;
i = i ? i.next : i;
j = j ? j.next : j;
}
if (rollover > 0) {
previous = sum;
sum = new ListNode(rollover, new ListNode(rollover));
previous.next = sum;
}
return first;
};
let result = addTwoNumbers(numberA1, numberB1);
while(result) {
console.log(result.val);
result = result.next;
}
</code></pre>
| [] | [
{
"body": "<p>I think you're over-complicating the problem -- you need to think of a different approach. </p>\n\n<p>Here's an algorithm: consider the first digit in the linked list. Add it to the \"running total.\" If there's another number in the list, multiply it by 10*(number count) and add it to the running total. Keep going until you run out of new numbers.</p>\n\n<p>Think of it this way for an input of 8->3->4:</p>\n\n<p>1) Set runningTotal to 8 initially.<br>\n2) There's another item in the list; multiply 3 by 10*1 to get 30. Add to running total. New running total: 38.<br>\n3) There's another item in the list; multiply 4 by 10*2 to get 400. Add to running total. New running total: 483.</p>\n\n<p>And so on. This works for lists of any size.</p>\n\n<p>Make a function that will convert a linked list to an integer as described as above, and then you just need to add up the results for both lists. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T03:48:22.143",
"Id": "425476",
"Score": "1",
"body": "There's no need to ever multiply by 10 since the task description says the output should be a _list of digits_, too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T21:22:01.883",
"Id": "220205",
"ParentId": "220201",
"Score": "2"
}
},
{
"body": "<p>There are few ways to simplify the code. First, to deal with <code>rollover</code> you don't need to convert a number to string and back.</p>\n\n<pre><code> if (k > 9) {\n rollover = 1;\n k -= 10;\n }\n</code></pre>\n\n<p>looks more natural.</p>\n\n<p>Second, the <code>isFirst</code> logic is rather convoluted. A standard technique is to initialize the resulting list with the dummy head, and not worry about the special case anymore. In pseudocode:</p>\n\n<pre><code> dummy = ListNode()\n tail = dummy\n while (....) {\n compute sum\n tail.next = ListNode(sum)\n tail = tail.next\n advance lists\n }\n handle the remaining rollover\n return dummy.next\n</code></pre>\n\n<p>Finally, testing for <code>i</code> and <code>j</code> at the end of the loop effectively repeats the test you've already done at the beginning. I recommend to change <code>while (i || j)</code> to <code>while (i && j)</code>, and deal with the remaining tail separately (notice that one of the tails is guaranteed to be empty, and one of the last loops is a no-op):</p>\n\n<pre><code> while (i && j) {\n ....\n }\n\n while (i) {\n propagate rollover\n }\n\n while (j) {\n propagate rollover\n }\n</code></pre>\n\n<p>The last two loops are good candidates to become a function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T21:42:00.290",
"Id": "220206",
"ParentId": "220201",
"Score": "3"
}
},
{
"body": "<p>Wow that is a lot of code to add two numbers.</p>\n\n<h2>Potential bug</h2>\n\n<p>The function ListNode has one argument yet in the function <code>addTwoNumbers</code> you call it with two arguments. However it does not manifest as a bug as you add the link in the lines following the node creation.</p>\n\n<p>This also results in you creating twice as many nodes as needed. </p>\n\n<p>E.G the second node is dropped and never used.</p>\n\n<pre><code>sum = new ListNode(k, new ListNode(k));\n</code></pre>\n\n<h2>Sanitize</h2>\n\n<p>The question states that the inputs are digits so there is no need to sanitize the lists. The only time you vet (arr sanitize) input is when that input comes from the insane, only networks and humans can be insane hence you only sanitize data from them. (Why I hate libraries and frameworks.. Their interfaces face humans (via code) so they are full of vetting code that negatively effect their performance)</p>\n\n<h2><code>i</code>, <code>j</code> and sometime <code>k</code></h2>\n\n<p>Generally the named variables <code>i</code>, <code>j</code>, <code>k</code> are used as indexes. This is so ubiquitous in C syntax like languages that using them for other purposes is a definite no no.</p>\n\n<h2>Use numbers</h2>\n\n<p>You should never bring a string to a numbers party.</p>\n\n<p>The variable you call <code>rollover</code> is called <code>carry</code>. The carry can be extracted from the sum as <code>carry = sum / 10 | 0</code> which is a lot faster than converting to a string.</p>\n\n<p>The core of the adder requires 3 numbers <code>a</code>, <code>b</code>, and <code>carry</code> that will give a <code>val</code> and <code>carry</code> and use one intermediate to avoid repeating an operation.</p>\n\n<pre><code>sum = a + b + carry, \nval = sum % 10;\ncarry = (sum - val) / 10;\n\n// or \nsum = a + b + carry, \nval = sum % 10;\ncarry = sum / 10 | 0;\n</code></pre>\n\n<h2>Testing</h2>\n\n<p>I did not fully test your code as it did not fit well with my linked list lib and <strike>my brain not work good this morn</strike> I'm a little lazy today. If there are other problems I do not see them in the code.</p>\n\n<h2>Rewrite</h2>\n\n<p>It is assumed that the linked list functions are not part of the problem to solve. The answer contains some list helpers that can be implemented in a variety of ways.</p>\n\n<ul>\n<li>Node creates a linked list node the new token.</li>\n<li>Helper function for testing <code>toList</code> converts an array to a list returning the head node as the most significant digit. (Note <code>| 0</code> to force type <code>Number</code></li>\n</ul>\n\n<p>Changes</p>\n\n<ul>\n<li>No sanity check</li>\n<li>Uses numbers rather than string to find carry</li>\n<li>Uses a <code>do while</code> to avoid the extra code needed to handle the final carry (some argue <code>do whiles</code> are too complex for humans to use and should be avoided, all I can say to the down voters, \"Du..Really???\")</li>\n</ul>\n\n<h3>Edge case</h3>\n\n<p>The example show an edge case of zero add zero as long lists of zero</p>\n\n<p>The second version check if the result is zero and returns a single node containing <code>0</code> which to me seams to more correct answer. </p>\n\n<p>BUT what about <code>001 + 1</code> the result is <code>002</code> I have not bothered with this edge case (or <em>\"leave it for you to solve if interested\"</em>) </p>\n\n<p><sub><sup>(hint: hold last node with value)</sup></sub></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Node(val, next){ return {val, next, \n toString() {return \"\" + (this.next ? this.next : \"\") + this.val}\n}};\nconst toList = (vals, p) => (vals.forEach(v => p = Node(v | 0, p)), p);\nconst reverseList = (l, p) => {do{p = Node(l.val ,p) }while(l = l.next); return p};\n\nconst A = toList([...\"33140613\"]), B = toList([...\"9283629\"]);\nconst A1 = toList([...\"00000\"]), B1 = toList([...\"00000\"]);\nconst A2 = toList([...\"00100\"]), B2 = toList([...\"900\"]);\n\nconsole.log(A + \" + \" + B + \" = \" + add(A, B));\nconsole.log(\"Wrong: \" + A1 + \" + \" + B1 + \" = \" + add(A1, B1));\nconsole.log(\"Wrong ?: \" + A2 + \" + \" + B2 + \" = \" + add(A2, B2));\n\n\nfunction add(nA, nB) {\n var carry = 0, a, b, result;\n do {\n nA ? (a = nA.val, nA = nA.next) : a = 0;\n nB ? (b = nB.val, nB = nB.next) : b = 0;\n const sum = a + b + carry, val = sum % 10;\n carry = (sum - val) / 10;\n result = Node(val, result);\n } while(nA || nB || carry !== 0);\n return reverseList(result);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Edge case</h3>\n\n<p>Return single node for zero.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Node(val, next){ return {val, next, \n toString() {return \"\" + (this.next ? this.next : \"\") + this.val}\n}};\nconst toList = (vals, p) => (vals.forEach(v => p = Node(v | 0, p)), p);\nconst reverseList = (l, p) => {do{p = Node(l.val ,p) }while(l = l.next); return p};\n\n\nconst A = toList([...\"33140613\"]), B = toList([...\"9283629\"]);\nconst A1 = toList([...\"00000\"]), B1 = toList([...\"00000\"]);\nconst A2 = toList([...\"00100\"]), B2 = toList([...\"900\"]);\n\nconsole.log(A + \" + \" + B + \" = \" + add(A, B));\nconsole.log(A1 + \" + \" + B1 + \" = \" + add(A1, B1));\nconsole.log(\"Wrong: \" + A2 + \" + \" + B2 + \" = \" + add(A2, B2));\n\n\nfunction add(nA, nB) {\n var carry = 0, a, b, result, hasVal = 0;\n do {\n nA ? (a = nA.val, nA = nA.next) : a = 0;\n nB ? (b = nB.val, nB = nB.next) : b = 0;\n const sum = a + b + carry, val = sum % 10;\n carry = (sum - val) / 10;\n result = Node(val, result);\n hasVal += sum;\n } while(nA || nB || carry !== 0);\n return hasVal ? reverseList(result) : Node(0);\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><sub><sup><em>This answer contains subjective opinions that do not reflect the view of the CR community</em><sup> <strong>B.M.</strong></sup></sup></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T01:24:24.927",
"Id": "220212",
"ParentId": "220201",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220212",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T19:38:43.500",
"Id": "220201",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"ecmascript-6"
],
"Title": "Add Two Numbers"
} | 220201 |
<p>I wrote a simple <strong>C++ lexer in python</strong>. Although it already works but I kinda feel I didn't follow the <strong><em>pythonic</em></strong> way. Any suggestion for improvements?</p>
<p><a href="https://gist.github.com/blackdead263/ab6a88e271ea5795df032a1c9697bf7a" rel="nofollow noreferrer">Sample C++ Code</a></p>
<p><a href="https://gist.github.com/blackdead263/03a9b40c9e3a9c395cfc60bef338abdd" rel="nofollow noreferrer">Sample output</a></p>
<p>Here's my code:</p>
<p><strong>mysrc.py</strong>:</p>
<pre class="lang-py prettyprint-override"><code>def keywords():
keywords = [
"auto",
"bool",
"break",
"case",
"catch",
"char",
"word",
"class",
"const",
"continue",
"delete",
"do",
"double",
"else",
"enum",
"false",
"float",
"for",
"goto",
"if",
"#include",
"int",
"long",
"namespace",
"not",
"or",
"private",
"protected",
"public",
"return",
"short",
"signed",
"sizeof",
"static",
"struct",
"switch",
"true",
"try",
"unsigned",
"void",
"while",
]
return keywords
def operators():
operators = {
"+": "PLUS",
"-": "MINUS",
"*": "MUL",
"/": "DIV",
"%": "MOD",
"+=": "PLUSEQ",
"-=": "MINUSEQ",
"*=": "MULEQ",
"/=": "DIVEQ",
"++": "INC",
"--": "DEC",
"|": "OR",
"&&": "AND",
}
return operators
def delimiters():
delimiters = {
"\t": "TAB",
"\n": "NEWLINE",
"(": "LPAR",
")": "RPAR",
"[": "LBRACE",
"]": "RBRACE",
"{": "LCBRACE",
"}": "RCBRACE",
"=": "ASSIGN",
":": "COLON",
",": "COMMA",
";": "SEMICOL",
"<<": "OUT",
">>": "IN",
}
return delimiters
</code></pre>
<p><strong>main file</strong>:</p>
<pre class="lang-py prettyprint-override"><code>import re
import mysrc
def basicCheck(token):
varPtrn = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]") # variables
headerPtrn = re.compile(r"\w[a-zA-Z]+[.]h") # header files
digitPtrn = re.compile(r'\d')
floatPtrn = re.compile(r'\d+[.]\d+')
if token in mysrc.keywords():
print(token + " KEYWORD")
elif token in mysrc.operators().keys():
print(token + " ", mysrc.operators()[token])
elif token in mysrc.delimiters():
description = mysrc.delimiters()[token]
if description == 'TAB' or description == 'NEWLINE':
print(description)
else:
print(token + " ", description)
elif re.search(headerPtrn, token):
print(token + " HEADER")
elif re.match(varPtrn, token) or "'" in token or '"' in token:
print(token + ' IDENTIFIER' )
elif re.match(digitPtrn, token):
if re.match(floatPtrn, token):
print(token + ' FLOAT')
else:
print(token + ' INT')
return True
def delimiterCorrection(line):
tokens = line.split(" ")
for delimiter in mysrc.delimiters().keys():
for token in tokens:
if token == delimiter:
pass
elif delimiter in token:
pos = token.find(delimiter)
tokens.remove(token)
token = token.replace(delimiter, " ")
extra = token[:pos]
token = token[pos + 1 :]
tokens.append(delimiter)
tokens.append(extra)
tokens.append(token)
else:
pass
for token in tokens:
if isWhiteSpace(token):
tokens.remove(token)
elif ' ' in token:
tokens.remove(token)
token = token.split(' ')
for d in token:
tokens.append(d)
return tokens
def isWhiteSpace(word):
ptrn = [ " ", "\t", "\n"]
for item in ptrn:
if word == item:
return True
else:
return False
#def hasWhiteSpace(token):
ptrn = ['\t', '\n']
if isWhiteSpace(token) == False:
for item in ptrn:
if item in token:
result = "'" + item + "'"
return result
else:
pass
return False
def tokenize(path):
try:
f = open(path).read()
lines = f.split("\n")
count = 0
for line in lines:
count = count + 1
tokens = delimiterCorrection(line)
print("\n#LINE ", count)
print("Tokens: ", tokens)
for token in tokens:
basicCheck(token)
return True
except FileNotFoundError:
print("\nInvald Path. Retry")
run()
def run():
path = input("Enter Source Code's Path: ")
tokenize(path)
again = int(input("""\n1. Retry\n2. Quit\n"""))
if again == 1:
run()
elif again == 2:
print("Quitting...")
else:
print('Invalid Request.')
run()
run()
</code></pre>
| [] | [
{
"body": "<p>You'll run out of stack memory if you recursively call <code>run()</code> at so many places. You can remove those. </p>\n\n<p>You should consider opening the file with a another context manager to avoid having the file handle kept open. </p>\n\n<p>Consider restricting the <code>try</code> block to only the part of code you expect to fail. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T04:08:02.637",
"Id": "425842",
"Score": "0",
"body": "thx. I edited that part."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T10:28:04.973",
"Id": "220225",
"ParentId": "220207",
"Score": "6"
}
},
{
"body": "<p>A lot of could be written in a more functional style. That means that functions return the result of their execution instead of printing it. It makes your code more readable, more composable and generally easier to reason about.\nAlso, docstrings at the beginning of all the function would help immensely in determining their purpose.</p>\n\n<p>For the details like naming and formatting, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> defines the Pythonic way</p>\n\n<p>Some functions that could be written more pythonic:</p>\n\n<pre><code>def isWhiteSpace(word):\n return word in [\" \", \"\\t\", \"\\n\"]\n</code></pre>\n\n<p>I partially rewrote the following functions and did a bit of obvious stuff,\nbut the starting paragraph still applies.</p>\n\n<pre><code>def delimiterCorrection(line):\n tokens = line.split(\" \")\n for delimiter in mysrc.delimiters().keys():\n for token in tokens:\n if token != delimiter and delimiter in token:\n pos = token.find(delimiter)\n tokens.remove(token)\n token = token.replace(delimiter, \" \")\n extra = token[:pos]\n token = token[pos + 1 :]\n tokens.append(delimiter)\n tokens.append(extra)\n tokens.append(token)\n\n for token in tokens:\n if ' ' in token:\n tokens.remove(token)\n token = token.split(' ')\n tokens += token\n return [t for t in tokens if not isWhiteSpace(token)] # Remove any tokens that are whitespace\n\ndef tokenize(path):\n \"\"\"Return a list of (line_number, [token]) pairs.\n Raise exception on error.\"\"\"\n if not isfile(path):\n raise ValueError(\"File \\\"\" + path + \"\\\" doesn't exist!\")\n\n res = []\n with open(path) as f:\n for line_count, line in enumerate(f):\n tokens = delimiterCorrection(line)\n res.append((line_count, tokens))\n for token in tokens:\n # This has a side effect which makes it hard to rewrite\n # Also, what does basic check do?\n basicCheck(token)\n return res\n</code></pre>\n\n<p>DISCLAIMER:\nI'm not a python expert in any way and my programming style is heavily inspired by functional programming. Feel free to disagree on everything I said.\nThe fact that you're making an effort to improve your programming style already sets you apart. I hope I provided may be one or two insights!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:15:00.093",
"Id": "220245",
"ParentId": "220207",
"Score": "6"
}
},
{
"body": "<blockquote>\n<pre><code>def run():\n path = input(\"Enter Source Code's Path: \")\n tokenize(path)\n again = int(input(\"\"\"\\n1. Retry\\n2. Quit\\n\"\"\"))\n if again == 1:\n run()\n elif again == 2:\n print(\"Quitting...\")\n else:\n print('Invalid Request.')\n run()\n</code></pre>\n</blockquote>\n\n<p>Instead of reinventing argument parsing, you should rely on the existing tools. The go-to module when dealing with user provided arguments is <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a>; so you could write something like:</p>\n\n<pre><code>import argparse\n\n\ndef run():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n 'files', metavar='FILE', nargs='+', type=argparse.FileType('r'),\n help='path to the files you want to tokenize')\n args = parser.parse_args()\n for f in files:\n with f:\n tokenize(f)\n</code></pre>\n\n<p>Note that, due to <code>argparse.FileType</code>, <code>f</code> are already opened files so you don't need to handle it yourself in <code>tokenize</code>. <code>argparse</code> will also handle invalid or unreadable files itself before returning from <code>parse_args</code>.</p>\n\n<hr>\n\n<p>Now, if your only arguments on the command-line are files that you want to read, the <a href=\"https://docs.python.org/3/library/fileinput.html\" rel=\"nofollow noreferrer\"><code>fileinput</code></a> module is even more specific for the task and you can get rid of <code>run</code> altogether:</p>\n\n<pre><code>import fileinput\n\n\ndef tokenize(path):\n for line in fileinput.input():\n count = fileinput.filelineno()\n tokens = delimiterCorrection(line)\n print(\"\\n#LINE \", count)\n print(\"Tokens: \", tokens)\n for token in tokens:\n if basicCheck(token) != None: # empty char -> ignore\n print(basicCheck(token))\n</code></pre>\n\n<hr>\n\n<p>Lastly, avoid calling code (such as <code>run()</code> here) from the top-level of the file and guard it with an <a href=\"https://stackoverflow.com/q/419163/5069029\"><code>if __name__ == '__main__'</code></a> clause.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T08:29:26.707",
"Id": "220402",
"ParentId": "220207",
"Score": "2"
}
},
{
"body": "<p>I have one answer - along with your questions about how to write the code, you should also consider writing unit tests for it. </p>\n\n<p>That is an answer to your question \"any suggestions for improvements?\" </p>\n\n<p>For instance you could write a module that imports unittest and in there import your module and create a test class per the unittest documentation. </p>\n\n<p>Then you'd write a function called <code>test_isWhiteSpace_truepositive</code> that calls <code><your module>.isWhiteSpace(\" \")</code> and then checks if the result is true. That test would tell you that your function correctly identifies a space as a whitespace character. You could then either add to that function a check for <code>\"\\t\"</code> and <code>\"\\n\"</code>, or you could write separate tests for those characters (I'd do them all in one).</p>\n\n<p>The tests would not need much maintenance unless you change your code - you'd write one for each function you create, they serve as documentation for the expected behavior of the function and they could be easily run (python mytestsuite.py) whenever you update your code, and they would tell you if you've broken anything. You could even automate them as part of your source code management (git, etc.) process.</p>\n\n<p>These lower level functions don't benefit very much from this but eventually your program is going to get large and as you make more changes, you might need to add different kinds of whitespace and it would be helpful to have this test to run against your updated function to make sure it behaves as expected. </p>\n\n<p>For instance you might change \"isWhiteSpace\" to take an entire string rather than one character, and then you'd want to really exercise it with <code>isWhiteSpace(\" \\t \\n \\t\\t \\n\\n\\n\\n\\n\")</code>, etc.</p>\n\n<p>Just a toy example, but it would be a suggestion for improving your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T11:15:57.290",
"Id": "224727",
"ParentId": "220207",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T22:20:15.390",
"Id": "220207",
"Score": "7",
"Tags": [
"python",
"compiler",
"lexer"
],
"Title": "Lexer for C++ in python"
} | 220207 |
<p>I would like to ask if this code is safe for user to log-in (save ID to session) and check if user is log-in when visiting site (Dashboard).</p>
<pre class="lang-py prettyprint-override"><code>@ll.route('/login', methods=['GET', 'POST'])
def LogIn():
if request.method == 'GET':
return render_template('login')
elif request.method == 'POST':
....Checking password, hashing.....
session.pop('User', None)
session['User'] = id_User
return redirect(url_for('LogINR.Dash'))
else:
return 'Method Not Allowed', 405
@ll.route('/dash')
def Dashboard():
if g.User:
return render_template('dash.html')
return redirect(url_for('LogINR.LogIn'))
@mod.before_request
def before_request():
g.User = None
if 'User' in session:
g.User = session['User']
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T09:24:00.243",
"Id": "425496",
"Score": "5",
"body": "Can you include all the relevant code into the question? Namely what you left out as \"checking password, hashing\" and the various undefined symbols (`g`, `session`, and the various imports from flask)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-13T22:44:26.217",
"Id": "220208",
"Score": "1",
"Tags": [
"python",
"authentication",
"flask"
],
"Title": "Safely log-in and save login info into session"
} | 220208 |
<p>Simple conversion of one type to another.</p>
<p>Is there a better way with streams :</p>
<pre><code> Map<String, Set<String>> result = new HashMap<>();
for (Pair<String, String> pair : resultList) {
Set<String> strSet = new HashSet<>();
strSet.add(pair.getRight());
result.merge(pair.getLeft(), strSet, new BiFunction<Set<String>, Set<String>, Set<String>>() {
@Override
public Set<String> apply(Set<String> current, Set<String> additional) {
if (current == null) {
return additional;
}
current.addAll(additional);
return current;
}
});
}
return result;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T05:53:49.793",
"Id": "425480",
"Score": "0",
"body": "Questions about how to do things are better suited in stackoverflow.com ."
}
] | [
{
"body": "<p>Sure. Use <code>Collectors.groupingBy</code> to build the <code>Map<String, Set<String>></code> for you.</p>\n\n<pre><code>return resultList.stream()\n .collect(Collectors.groupingBy(Pair::getLeft,\n Collectors.mapping(Pair::getRight, Collectors.toSet())));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T06:26:11.143",
"Id": "220217",
"ParentId": "220209",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T00:14:46.717",
"Id": "220209",
"Score": "-1",
"Tags": [
"java",
"stream"
],
"Title": "java for loop with map merge"
} | 220209 |
<p>Parser Combinators are the amazingly elegant way to write parsers that has evolved over on the functional programming side of the world, but have been less available or accessible for imperative languages. I have attempted somewhat to bridge this gap by <del>stealing</del> copying as many ideas from FP as were needed to make these combinators in C.</p>
<p>I've written an <a href="https://groups.google.com/d/topic/comp.lang.c/57QkBCuuzS8/discussion" rel="nofollow noreferrer">overview of Parser Combinators</a> and presentations of the <a href="https://groups.google.com/d/topic/comp.lang.c/dBbYwcK75gA/discussion" rel="nofollow noreferrer">basic lisp-like object system</a> and the <a href="https://groups.google.com/d/topic/comp.lang.c/oYpTRP6RYUM/discussion" rel="nofollow noreferrer">higher order functions</a> which supplement the basic objects. Of course <a href="https://en.wikipedia.org/wiki/Parser_combinator" rel="nofollow noreferrer">wikipedia</a> has a nice article on the topic, and my code mostly follows the excellent paper by <a href="http://www.cs.nott.ac.uk/%7Epszgmh/monparsing.pdf" rel="nofollow noreferrer">Hutton and Meijer</a> which is also a good introduction.</p>
<p>This code is the result of 16 (or so) re-writes of the code in my <a href="https://codereview.stackexchange.com/questions/166009/parser-combinators-in-oo-c">previous question</a>. I anticipate at least one more re-write to add more features like checking the offside rule both for parsing syntaxes lke Python which use this rule, or just checking that indentation in C code is reasonable.</p>
<p>A few remarks about the code overall: I'm trying the "McIllroy convention" which places header guards around the <code>#include</code> lines rather than inside the included files. The <code>object</code> type is a pointer to a union. Most of the <code>.c</code> files have a (name-mangled) <code>main()</code> function which does some simple tests; somewhere along the continuum between <em>real unit testing</em> and <em>not testing</em>.</p>
<p>I'm looking for review of the "weird stuff" if possible. Particularly the handling of <em>suspensions</em>, which represent values to be lazily evaluated. But of course anything weird or suspicious is fair game.</p>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/ppnarg.h" rel="nofollow noreferrer">ppnarg.h</a><br />
Written by Laurent Deniau for the <a href="https://arxiv.org/abs/1003.2547" rel="nofollow noreferrer">C Object System</a>. I have extended the maximum number of arguments a little. This macro supports the variadic combinators <code>PLUS</code> and <code>SEQ</code> which combine many subparsers together. It lets you pass a count of the variadic arguments into the function that processes them.</p>
<pre><code>/*
* The PP_NARG macro evaluates to the number of arguments that have been
* passed to it.
*
* Laurent Deniau, "__VA_NARG__," 17 January 2006, <comp.std.c> (29 November 2007).
*/
#define PP_NARG(...) PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
#define PP_NARG_(...) PP_ARG_N(__VA_ARGS__)
#define PP_ARG_N( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,_64,_65,_66,_67,_68,_69,_70, \
_71,N,...) N
#define PP_RSEQ_N() \
71,70, \
69,68,67,66,65,64,63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9obj.h" rel="nofollow noreferrer">pc9obj.h</a><br />
Public interface to the basic objects. All the constructors for various types of objects and lists. Especially, <code>chars_from_string</code> which produces a lazy list of characters. The symbol-typed objects are constructed with a unique numeric identifer and a print string. These unique ids are generated by declaring the names in an enum. The odd name <code>SYM1</code> is used to start the next enum in the next <em>layer</em> to add more symbols keeping all ids unique.</p>
<pre><code>#define PC9OBJ_H
#include <stdlib.h>
#include <stdio.h>
#define POINTER_TO *
typedef union uobject POINTER_TO object;
typedef object list;
typedef object parser;
typedef object oper;
typedef oper predicate;
typedef object boolean;
typedef object fSuspension( object );
typedef list fParser( object, list );
typedef object fOperator( object, object );
typedef boolean fPredicate( object, object );
typedef object fBinOper( object, object );
enum object_symbols {
T, F, X, A, B,
SYM1
};
object T_, NIL_;
int valid( object a );
object Int( int i );
list one( object a );
list cons( object a, object b );
object Suspension( object v, fSuspension *f );
parser Parser( object v, fParser *f );
oper Operator( object v, fOperator *f );
object String( char *s, int disposable );
object Symbol_( int sym, char *pname );
#define Symbol(n) Symbol_( n, #n )
object Void( void *v );
void add_global_root( object a );
int garbage_collect( object local_roots );
object x_( list a );
object xs_( list a );
list take( int n, list o );
list drop( int n, list o );
list chars_from_string( char *v );
list chars_from_file( FILE *v );
object string_from_chars( list o );
void print( object o );
void print_list( list a );
void print_flat( list a );
void print_data( list a );
#define PRINT_WRAPPER(_, __, ___) printf( "%s: %s %s= ", __func__, #__, ___ ), _( __ ), puts("")
#define PRINT(__) PRINT_WRAPPER( print_list, __, "" )
#define PRINT_FLAT(__) PRINT_WRAPPER( print_flat, __, "flat" )
#define PRINT_DATA(__) PRINT_WRAPPER( print_data, __, "data" )
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9objpriv.h" rel="nofollow noreferrer">pc9objpriv.h</a><br />
Private interface to the basic objects. Objects are represented as a pointer to a tagged union. The <code>at_</code> function forces execution of suspensions, but externally this action must be performed by calling <code>take</code> or <code>drop</code>.</p>
<pre><code>#define PC9OBJPRIV_H
#ifndef PC9OBJ_H
#include "pc9obj.h"
#endif
typedef enum object_tag {
INVALID, INTEGER, LIST, SUSPENSION, PARSER, OPERATOR, SYMBOL, STRING, VOID,
} tag;
union uobject { tag t;
struct { tag t; int i; } Int;
struct { tag t; object a, b; } List;
struct { tag t; object v; fSuspension *f; } Suspension;
struct { tag t; object v; fParser *f; } Parser;
struct { tag t; object v; fOperator *f; } Operator;
struct { tag t; int symbol; char *pname; object data; } Symbol;
struct { tag t; char *string; int disposable; } String;
struct { tag t; object next; } Header;
struct { tag t; void *v; } Void;
};
object new_( object a );
#define OBJECT(...) new_( (union uobject[]){{ __VA_ARGS__ }} )
object at_( object a );
object fill_string( char **s, list o );
int obj_main( void );
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9obj.c" rel="nofollow noreferrer">pc9obj.c</a><br />
Implementation of basic objects. Objects are allocated as two structs side by side with the hidden left object used as an allocation record. The allocation records form a singly linked list which is traversed during a sweep of the garbage collector. <code>x_</code> and <code>xs_</code> are the famous lisp <code>car</code> and <code>cdr</code> functions, but I like the haskell naming convention so I used those; but <code>x</code> is too useful as a local variable name so they got underscores appended.</p>
<pre><code>#include <stdio.h>
#include "pc9objpriv.h"
static void mark_objects( list a );
static int sweep_objects( list *po );
object T_ = (union uobject[]){{ .Symbol = { SYMBOL, T, "T" } }},
NIL_ = (union uobject[]){{ .t = INVALID }};
static list global_roots = NULL;
static list allocation_list = NULL;
object
new_( object a ){
object p = calloc( 2, sizeof *p );
return p ? p[0] = (union uobject){ .Header = { 0, allocation_list } },
allocation_list = p,
p[1] = *a,
&p[1]
: 0;
}
int
valid( object a ){
switch( a ? a->t : 0 ){
default:
return 0;
case INTEGER:
case LIST:
case SUSPENSION:
case PARSER:
case OPERATOR:
case SYMBOL:
case STRING:
return 1;
}
}
object
Int( int i ){
return OBJECT( .Int = { INTEGER, i } );
}
list
one( object a ){
return cons( a, NIL_ );
}
list
cons( object a, object b ){
return OBJECT( .List = { LIST, a, b } );
}
object
Suspension( object v, fSuspension *f ){
return OBJECT( .Suspension = { SUSPENSION, v, f } );
}
parser
Parser( object v, fParser *f ){
return OBJECT( .Parser = { PARSER, v, f } );
}
oper
Operator( object v, fOperator *f ){
return OBJECT( .Operator = { OPERATOR, v, f } );
}
object
String( char *s, int disposable ){
return OBJECT( .String = { STRING, s, disposable } );
}
object
Symbol_( int sym, char *pname ){
return OBJECT( .Symbol = { SYMBOL, sym, pname } );
}
object
Void( void *v ){
return OBJECT( .Void = { VOID, v } );
}
void
add_global_root( object a ){
global_roots = cons( a, global_roots );
}
int
garbage_collect( object local_roots ){
mark_objects( local_roots );
mark_objects( global_roots );
return sweep_objects( &allocation_list );
}
static tag *
mark( object a ){
return &a[-1].Header.t;
}
static void
mark_objects( list a ){
if( !valid(a) || *mark( a ) ) return;
*mark( a ) = 1;
switch( a->t ){
case LIST: mark_objects( a->List.a );
mark_objects( a->List.b ); break;
case PARSER: mark_objects( a->Parser.v ); break;
case OPERATOR: mark_objects( a->Operator.v ); break;
case SYMBOL: mark_objects( a->Symbol.data ); break;
case SUSPENSION: mark_objects( a->Suspension.v ); break;
}
}
static int
sweep_objects( list *po ){
int count = 0;
while( *po )
if( (*po)->t ){
(*po)->t = 0;
po = &(*po)->Header.next;
} else {
object z = *po;
*po = (*po)->Header.next;
if( z[1].t == STRING && z[1].String.disposable )
free( z[1].String.string );
free( z );
++count;
}
return count;
}
object
at_( object a ){
return valid( a ) && a->t == SUSPENSION ? at_( a->Suspension.f( a->Suspension.v ) ) : a;
}
object
px_( object v ){
list a = v;
*a = *at_( a );
return x_( a );
}
object
x_( list a ){
return valid( a ) ?
a->t == LIST ? a->List.a :
a->t == SUSPENSION ? Suspension( a, px_ ) : NIL_
: NIL_;
}
object
pxs_( object v ){
list a = v;
*a = *at_( a );
return xs_( a );
}
object
xs_( list a ){
return valid( a ) ?
a->t == LIST ? a->List.b :
a->t == SUSPENSION ? Suspension( a, pxs_ ) : NIL_
: NIL_;
}
list
take( int n, list o ){
if( n == 0 ) return NIL_;
*o = *at_( o );
return valid( o ) ? cons( x_( o ), take( n-1, xs_( o ) ) ) : NIL_;
}
list
drop( int n, list o ){
if( n == 0 ) return o;
*o = *at_( o );
return valid( o ) ? drop( n-1, xs_( o ) ) : NIL_;
}
list
pchars_from_string( object v ){
char *p = v->String.string;
return *p ? cons( Int( *p ), Suspension( String( p+1, 0 ), pchars_from_string ) ) : Symbol(EOF);
}
list
chars_from_string( char *p ){
return p ? Suspension( String( p, 0 ), pchars_from_string ) : NIL_;
}
list
pchars_from_file( object v ){
FILE *f = v->Void.v;
int c = fgetc( f );
return c != EOF ? cons( Int( c ), Suspension( v, pchars_from_file ) ) : Symbol(EOF);
}
list
chars_from_file( FILE *f ){
return f ? Suspension( Void( f ), pchars_from_file ) : NIL_;
}
static int
count_ints( list o ){
return !o ? 0 :
o->t == SUSPENSION ? *o = *at_( o ), count_ints( o ) :
o->t == INTEGER ? 1 :
o->t == LIST ? count_ints( o->List.a ) + count_ints( o->List.b ) :
0;
}
object
fill_string( char **s, list o ){
return !o ? NULL :
o->t == INTEGER ? *(*s)++ = o->Int.i, NULL :
o->t == LIST ? fill_string( s, o->List.a ), fill_string( s, o->List.b ) :
NULL;
}
object
string_from_chars( list o ){
char *s = calloc( count_ints( o ) + 1, 1 );
object z = String( s, 1 );
return fill_string( &s, o ), z;
}
void
print( object o ){
if( !o ){ printf( "() " ); return; }
switch( o->t ){
case INTEGER: printf( "%d ", o->Int.i ); break;
case LIST: printf( "(" );
print( o->List.a );
print( o->List.b );
printf( ") " ); break;
case SUSPENSION: printf( "... " ); break;
case PARSER: printf( "Parser " ); break;
case OPERATOR: printf( "Oper " ); break;
case STRING: printf( "\"%s\"", o->String.string ); break;
case SYMBOL: printf( "%s ", o->Symbol.pname ); break;
case INVALID: printf( "_ " ); break;
default: printf( "INVALID " ); break;
}
}
void
print_listn( list a ){
switch( a ? a->t : 0 ){
default: print( a ); return;
case LIST: print_list( x_( a ) ), print_listn( xs_( a ) ); return;
}
}
void
print_list( list a ){
switch( a ? a->t : 0 ){
default: print( a ); return;
case LIST: printf( "(" ), print_list( x_( a ) ), print_listn( xs_( a ) ), printf( ")" ); return;
}
}
void
print_flat( list a ){
if( !a ) return;
if( a->t != LIST ){ print( a ); return; }
print_flat( a->List.a );
print_flat( a->List.b );
}
void
print_data( list a ){
if( !a ) return;
switch( a->t ){
case LIST: print_data( a->List.a), print_data( a->List.b ); break;
case STRING: printf( "%s", a->String.string ); break;
case SYMBOL: print_data( a->Symbol.data ); break;
}
}
int
test_basics(){
list ch = chars_from_string( "abcdef" );
PRINT( ch );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 1, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( x_( ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( x_( xs_( ch ) ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 1, x_( xs_( ch ) ) ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 5, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( ch );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 6, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 1, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 2, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 2, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 2, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
PRINT( take( 2, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
return 0;
}
int obj_main(){ return test_basics(); }
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9fp.h" rel="nofollow noreferrer">pc9fp.h</a><br />
Interface to the "functional programming" functions. These have all been tweaked to deal nicely (?) with suspensions and force only enough execution to make progress on a computation.</p>
<pre><code>#define PC9FP_H
#ifndef PC9OBJ_H
#include "pc9obj.h"
#endif
boolean eq( object a, object b );
list env( list tail, int n, ... );
object assoc( object a, list b );
list copy( list a );
list append( list a, list b );
object apply( oper f, object o );
list map( oper f, list o );
list join( list o );
object collapse( fBinOper *f, list o );
object reduce( fBinOper *f, int n, object *po );
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9fp.c" rel="nofollow noreferrer">pc9fp.c</a><br />
Implementation of the "functional programming" functions.</p>
<pre><code>#include <stdarg.h>
#include <string.h>
#include "pc9fp.h"
#include "pc9objpriv.h"
boolean
eq( object a, object b ){
return (
!valid( a ) && !valid( b ) ? 1 :
!valid( a ) || !valid( b ) ? 0 :
a->t != b->t ? 0 :
a->t == SYMBOL ? a->Symbol.symbol == b->Symbol.symbol :
!memcmp( a, b, sizeof *a ) ? 1 : 0
) ? T_ : NIL_;
}
list
copy( list a ){
return !valid( a ) ? NIL_ :
a->t == LIST ? cons( copy( x_( a ) ), copy( xs_( a ) ) ) :
a;
}
list
env( list tail, int n, ... ){
va_list v;
va_start( v, n );
list r = tail;
while( n-- ){
object a = va_arg( v, object );
object b = va_arg( v, object );
r = cons( cons( a, b ), r );
}
va_end( v );
return r;
}
object
assoc( object a, list b ){
return !valid( b ) ? NIL_ :
valid( eq( a, x_( x_( b ) ) ) ) ? xs_( x_( b ) ) :
assoc( a, xs_( b ) );
}
static list
pappend( object v ){
list a = assoc( Symbol(A), v );
list b = assoc( Symbol(B), v );
*a = *at_( a );
return append( a, b );
}
list
append( list a, list b ){
return !valid( a ) ? b :
a->t == SUSPENSION ? Suspension( env( 0, 2, Symbol(A), a, Symbol(B), b ), pappend ) :
cons( x_( a ), append( xs_( a ), b ) );
}
static object
papply( object v ){
oper f = assoc( Symbol(F), v );
object o = assoc( Symbol(X), v );
*o = *at_( o );
return valid( o ) ? f->Operator.f( f->Operator.v, o ) : NIL_;
}
object
apply( oper f, object o ){
return f->t == OPERATOR ?
valid( o ) ?
o->t == SUSPENSION ? Suspension( env( 0, 2, Symbol(F), f, Symbol(X), o ), papply )
: f->Operator.f( f->Operator.v, o )
: f->Operator.f( f->Operator.v, o ) // for using( maybe(), ... )
: NIL_;
//return f->t == OPERATOR ? f->Operator.f( f->Operator.v, o ) : NIL_;
}
static list
pmap( object v ){
oper f = assoc( Symbol(F), v );
list o = assoc( Symbol(X), v );
*o = *at_( o );
return valid( o ) ? cons( apply( f, x_( o ) ), map( f, xs_( o ) ) ) : NIL_;
}
list
map( oper f, list o ){
return valid( o ) ?
o->t == SUSPENSION ? Suspension( env( 0, 2, Symbol(F), f, Symbol(X), o ), pmap ) :
cons( apply( f, x_( o ) ),
Suspension( env( 0, 2, Symbol(F), f, Symbol(X), xs_( o ) ), pmap ) )
: NIL_;
//return valid( o ) ? cons( apply( f, x_( o ) ), map( f, xs_( o ) ) ) : NIL_;
}
static list
pjoin( object v ){
list o = assoc( Symbol(X), v );
*o = *at_( o );
return append( x_( take( 1, o ) ), join( xs_( o ) ) );
}
list
join( list o ){
return valid( o ) ?
o->t == SUSPENSION ? Suspension( env( 0, 1, Symbol(X), o ), pjoin ) :
append( x_( o ), Suspension( env( 0, 1, Symbol(X), xs_( o ) ), pjoin ) )
: NIL_;
//return valid( o ) ? append( x_( o ), join( xs_( o ) ) ) : NIL_;
}
static object
do_collapse( fBinOper *f, object a, object b ){
return valid( b ) ? f( a, b ) : a;
}
object
collapse( fBinOper *f, list o ){
return valid( o ) ?
o->t == LIST ? do_collapse( f, collapse( f, x_( o ) ), collapse( f, xs_( o ) ) )
: o
: NIL_;
}
object
reduce( fBinOper *f, int n, object *po ){
return n==1 ? *po : f( *po, reduce( f, n-1, po+1 ) );
}
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9par.h" rel="nofollow noreferrer">pc9par.h</a><br />
Interface to the Parser Combinators. Constructing parsers for single characters <code>alpha</code> <code>digit</code> <code>sat</code> or combining parsers together <code>seq</code> <code>plus</code>. Construct a parser using a <code>regex</code>.</p>
<pre><code>#define PC9PAR_H
#ifndef PC9FP_H
#include "pc9fp.h"
#endif
#include "ppnarg.h"
enum parser_symbols {
VALUE = SYM1, PRED, P, PP, NN, Q, R, FF, XX, AA, ID, USE, ATOM,
SYM2
};
list parse( parser p, list input );
parser result( object a );
parser zero( void );
parser item( void );
parser bind( parser p, oper f );
parser plus( parser p, parser q );
#define PLUS(...) reduce( plus, PP_NARG(__VA_ARGS__), (object[]){ __VA_ARGS__ } )
parser sat( predicate pred );
parser alpha( void );
parser digit( void );
parser lit( object a );
parser chr( int c );
parser str( char *s );
parser anyof( char *s );
parser noneof( char *s );
parser seq( parser p, parser q );
#define SEQ(...) reduce( seq, PP_NARG(__VA_ARGS__), (object[]){ __VA_ARGS__ } )
parser xthen( parser p, parser q );
parser thenx( parser p, parser q );
parser into( parser p, object id, parser q );
parser maybe( parser p );
parser forward( void );
parser many( parser p );
parser some( parser p );
parser trim( parser p );
parser using( parser p, fOperator *f );
parser regex( char *re );
int par_main( void );
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9par.c" rel="nofollow noreferrer">pc9par.c</a><br />
Implementation of the Parser Combinators. Includes 3 "internal DSL" examples with the <code>regex()</code> function, and <code>pprintf()</code> and <code>pscanf()</code> functions.</p>
<pre><code>#include <ctype.h>
#include <stdarg.h>
#include <string.h>
#include "pc9par.h"
#include "pc9objpriv.h"
list
parse( parser p, list input ){
return valid( p ) && p->t == PARSER && valid( input ) ? p->Parser.f( p->Parser.v, input ) : NIL_;
}
static list
presult( object v, list input ){
return one( cons( assoc( Symbol(VALUE), v ), input ) );
}
parser
result( object a ){
return Parser( env( 0, 1, Symbol(VALUE), a ), presult );
}
static list
pzero( object v, list input ){
return NIL_;
}
parser
zero( void ){
return Parser( 0, pzero );
}
static list
pitem( object v, list input ){
drop( 1, input );
return valid( input ) ? one( cons( x_( input ), xs_( input ) ) ) : NIL_;
//return valid( input ) ? one( cons( x_( take( 1, input ) ), xs_( input ) ) ) : NIL_; //strict
//return valid( input ) ? one( cons( x_( input ), xs_( input ) ) ) : NIL_; //lazy
}
parser
item( void ){
return Parser( 0, pitem );
}
static list
pbind( object v, list input ){
parser p = assoc( Symbol(P), v );
oper f = assoc( Symbol(FF), v );
list r = parse( p, input );
return valid( r ) ? join( map( Operator( valid( f->Operator.v ) ?
append( copy( f->Operator.v ), v ) : v,
f->Operator.f ),
r ) )
: NIL_;
}
parser
bind( parser p, oper f ){
return Parser( env( 0, 2, Symbol(P), p, Symbol(FF), f ), pbind );
}
static list
bplus( object v ){
list r = assoc( Symbol(R), v );
object qq = assoc( Symbol(Q), v );
*r = *at_( r );
return valid( r ) ? append( r, qq ) : qq;
}
static list
cplus( object v ){
parser q = assoc( Symbol(Q), v );
list input = assoc( Symbol(X), v );
return parse( q, input );
}
static list
pplus( object v, list input ){
parser p = assoc( Symbol(P), v );
parser q = assoc( Symbol(Q), v );
list r = parse( p, input );
object qq = Suspension( env( 0, 2, Symbol(Q), q, Symbol(X), input ), cplus );
return valid( r ) ?
r->t == SUSPENSION ? Suspension( env( 0, 2, Symbol(R), r, Symbol(Q), qq ), bplus )
: append( r, qq )
: qq;
}
parser
plus( parser p, parser q ){
if( !q ) return p;
return Parser( env( 0, 2, Symbol(P), p, Symbol(Q), q ), pplus );
}
static list
psat( object v, list input ){
predicate pred = assoc( Symbol(PRED), v );
object r = apply( pred, x_( input ) );
return valid( r ) ? one( cons( x_( input ), xs_( input ) ) ) : NIL_;
}
parser
sat( predicate pred ){
return bind( item(), Operator( env( 0, 1, Symbol(PRED), pred ), psat ) );
}
static boolean
palpha( object v, object o ){
return isalpha( o->Int.i ) ? T_ : NIL_;
}
parser
alpha( void ){
return sat( Operator( 0, palpha ) );
}
static boolean
pdigit( object v, object o ){
return isdigit( o->Int.i ) ? T_ : NIL_;
}
parser
digit( void ){
return sat( Operator( 0, pdigit ) );
}
static boolean
plit( object v, object o ){
object a = assoc( Symbol(X), v );
return eq( a, o );
}
parser
lit( object a ){
return sat( Operator( env( 0, 1, Symbol(X), a ), plit ) );
}
parser
chr( int c ){
return lit( Int( c ) );
}
parser
str( char *s ){
return *s ? seq( chr( *s ), str( s+1 ) ) : result(0);
}
parser
anyof( char *s ){
return *s ? plus( chr( *s ), anyof( s+1 ) ) : zero();
}
static list
pnone( object v, list input ){
parser p = assoc( Symbol(NN), v );
object r = parse( p, input );
*r = *at_( r );
return valid( r ) ? NIL_ : pitem( 0, input );
}
parser
noneof( char *s ){
return Parser( env( 0, 1, Symbol(NN), anyof( s ) ), pnone );
}
static list
pprepend( object v, list o ){
object a = assoc( Symbol(AA), v );
return valid( a ) ? cons( cons( a, x_( o ) ), xs_( o ) ) : o;
}
static list
prepend( list a, list b ){
return map( Operator( env( 0, 1, Symbol(AA), a ), pprepend ), b );
}
static list
pseq( object v, list output ){
parser q = assoc( Symbol(Q), v );
return prepend( x_( output ), parse( q, xs_( output ) ) );
}
parser
seq( parser p, parser q ){
if( !q ) return p;
return bind( p, Operator( env( 0, 1, Symbol(Q), q ), pseq ) );
}
static list
pxthen( object v, list o ){
return one( cons( xs_( x_( o ) ), xs_( o ) ) );
}
parser
xthen( parser p, parser q ){
return bind( seq( p, q ), Operator( 0, pxthen ) );
}
static list
pthenx( object v, list o ){
return one( cons( x_( x_( o ) ), xs_( o ) ) );
}
parser
thenx( parser p, parser q ){
return bind( seq( p, q ), Operator( 0, pthenx ) );
}
static list
pinto( object v, list o ){
object id = assoc( Symbol(ID), v );
parser q = assoc( Symbol(Q), v );
return parse( Parser( env( q->Parser.v, 1, id, x_( o ) ), q->Parser.f ), xs_( o ) );
}
parser
into( parser p, object id, parser q ){
return bind( p, Operator( env( 0, 2, Symbol(ID), id, Symbol(Q), q ), pinto ) );
}
parser
maybe( parser p ){
return plus( p, result(0) );
}
parser
forward( void ){
return Parser( 0, 0 );
}
parser
many( parser p ){
parser q = forward();
parser r = maybe( seq( p, q ) );
*q = *r;
return r;
}
parser
some( parser p ){
return seq( p, many( p ) );
}
static list
ptrim( object v, list input ){
parser p = assoc( Symbol(PP), v );
list r = parse( p, input );
return valid( r ) ? one( x_( take( 1, r ) ) ) : r;
}
parser
trim( parser p ){
return Parser( env( 0, 1, Symbol(PP), p ), ptrim );
}
static list
pusing( object v, list o ){
oper f = assoc( Symbol(USE), v );
return one( cons( apply( f, x_( o ) ), xs_( o ) ) );
}
parser
using( parser p, fOperator *f ){
return bind( p, Operator( env( 0, 1, Symbol(USE), Operator( 0, f ) ), pusing ) );
}
static parser
do_meta( parser a, object o ){
switch( o->Int.i ){
case '*': return many( a ); break;
case '+': return some( a ); break;
case '?': return maybe( a ); break;
} return a;
}
static parser
on_meta( object v, object o ){
parser atom = assoc( Symbol(ATOM), v );
return valid( o ) ? do_meta( atom, o ) : atom;
}
static parser on_dot( object v, object o ){ return item(); }
static parser on_chr( object v, object o ){ return lit( o ); }
static parser on_term( object v, object o ){ return collapse( seq, o ); }
static parser on_expr( object v, object o ){ return collapse( plus, o ); }
#define META "*+?"
#define SPECIAL META ".|()"
parser
regex( char *re ){
static parser p;
if( !p ){
parser dot = using( chr('.'), on_dot );
parser meta = anyof( META );
parser escape = xthen( chr('\\'), anyof( SPECIAL "\\" ) );
parser chr_ = using( plus( escape, noneof( SPECIAL ) ), on_chr );
parser expr_ = forward();
parser atom = PLUS( dot,
xthen( chr('('), thenx( expr_, chr(')') ) ),
chr_ );
parser factor = into( atom, Symbol(ATOM), using( maybe( meta ), on_meta ) );
parser term = using( some( factor ), on_term );
parser expr = using( seq( term, many( xthen( chr('|'), term ) ) ), on_expr );
*expr_ = *expr;
p = trim( expr );
add_global_root( p );
}
list r = parse( p, chars_from_string( re ) );
return valid( r ) ? ( x_( x_( r ) ) ) : r;
}
parser
vusing( parser p, object v, fOperator *f ){
return bind( p, Operator( env( 0, 1, Symbol(USE), Operator( v, f ) ), pusing ) );
}
object sum( object a, object b ){ return Int( a->Int.i + b->Int.i ); }
boolean nz( object v, object o ){ return o->Int.i ? T_ : NIL_; }
static object p_char( object v, list o ){
va_list *p = (void *)v; return putchar(va_arg( *p, int )), Int(1);
}
static object p_string( object v, list o ){
va_list *p = (void *)v;
char *s = va_arg( *p, char* );
return fputs( s, stdout ), Int(strlen( s ));
}
static object p_lit( object v, list o ){
return putchar( o->Int.i ), Int(1);
}
static object on_fmt( object v, list o ){ return collapse( sum, o ); }
int
pprintf( char const *fmt, ... ){
if( !fmt ) return 0;
static va_list v;
va_start( v, fmt );
static parser p;
if( !p ){
parser directive = PLUS( using( chr('%'), p_lit ),
vusing( chr('c'), (void *)&v, p_char ),
vusing( chr('s'), (void *)&v, p_string ) );
parser term = PLUS( xthen( chr('%'), directive ),
using( sat( Operator( 0, nz ) ), p_lit ) );
parser format = many( term );
p = using( format, on_fmt );
add_global_root( p );
}
object r = parse( p, chars_from_string( (char*)fmt ) );
drop( 1, r );
va_end( v );
return x_( x_( r ) )->Int.i;
}
static object convert_char( object v, list o ){
va_list *p = (void *)v;
char *cp = va_arg( *p, char* );
*cp = o->Int.i;
return Int(1);
}
static object convert_string( object v, list o ){
va_list *p = (void *)v;
char *sp = va_arg( *p, char* );
fill_string( &sp, o );
return Int(1);
}
static parser on_char( object v, list o ){
return vusing( item(), v, convert_char );
}
static parser on_string( object v, list o ){
return vusing( xthen( many( anyof( " \t\n" ) ), many( noneof( " \t\n" ) ) ), v, convert_string );
}
static object r_zero( object v, list o ){ return Int(0); }
static parser pass( parser p ){ return using( p, r_zero ); }
static parser on_space( object v, list o ){ return valid( o ) ? pass( many( anyof( " \t\n" ) ) ) : o; }
static parser on_percent( object v, list o ){ return pass( chr('%') ); }
static parser on_lit( object v, list o ){ return pass( lit( o ) ); }
static object sum_up( object v, list o ){ return collapse( sum, o ); }
static parser on_terms( object v, list o ){ return using( collapse( seq, o ), sum_up ); }
int
pscanf( char const *fmt, ... ){
if( !fmt ) return 0;
static va_list v;
va_start( v, fmt );
static parser p;
if( !p ){
parser space = using( many( anyof( " \t\n" ) ), on_space );
parser directive = PLUS( using( chr('%'), on_percent ),
vusing( chr('c'), (void *)&v, on_char ),
vusing( chr('s'), (void *)&v, on_string ) );
parser term = PLUS( xthen( chr('%'), directive ),
using( sat( Operator( 0, nz ) ), on_lit ) );
parser format = many( seq( space, term ) );
p = using( format, on_terms );
add_global_root( p );
}
list fp = parse( p, chars_from_string( (char*)fmt ) );
drop( 1, fp );
parser f = x_( x_( fp ) );
if( !valid( f ) ) return 0;
list r = parse( f, chars_from_file( stdin ) );
drop( 1, r );
va_end( v );
return valid( r ) ? x_( x_( r ) )->Int.i : 0;
}
int test_pscanf(){
char c;
PRINT( Int( pscanf( "" ) ) );
PRINT( Int( pscanf( "abc" ) ) );
PRINT( Int( pscanf( " %c", &c ) ) );
PRINT( string_from_chars( Int( c ) ) );
char buf[100];
PRINT( Int( pscanf( "%s", buf ) ) );
PRINT( String( buf, 0 ) );
return 0;
}
int test_pprintf(){
PRINT( Int( pprintf( "%% abc %c %s\n", 'x', "123" ) ) );
return 0;
}
int test_regex(){
parser a;
PRINT( a = regex( "\\." ) );
PRINT( parse( a, chars_from_string( "a" ) ) );
PRINT( parse( a, chars_from_string( "." ) ) );
PRINT( parse( a, chars_from_string( "\\." ) ) );
parser b;
PRINT( b = regex( "\\\\\\." ) );
PRINT( parse( b, chars_from_string( "\\." ) ) );
PRINT( take( 3, parse( b, chars_from_string( "\\." ) ) ) );
parser r;
PRINT( r = regex( "a?b+(c).|def" ) );
PRINT( parse( r, chars_from_string( "abc" ) ) );
PRINT( parse( r, chars_from_string( "abbcc" ) ) );
PRINT( Int( garbage_collect( r ) ) );
list s;
PRINT( s = parse( r, chars_from_string( "def" ) ) );
PRINT( take( 3, s ) );
PRINT( parse( r, chars_from_string( "deff" ) ) );
PRINT( parse( r, chars_from_string( "adef" ) ) );
PRINT( parse( r, chars_from_string( "bcdef" ) ) );
PRINT( Int( garbage_collect( cons( r, s ) ) ) );
parser t;
PRINT( t = regex( "ac|bd" ) );
PRINT( parse( t, chars_from_string( "ac" ) ) );
PRINT( take( 1, parse( t, chars_from_string( "bd" ) ) ) );
PRINT( Int( garbage_collect( t ) ) );
parser u;
PRINT( u = regex( "ab|cd|ef" ) );
PRINT( parse( u, chars_from_string( "ab" ) ) );
PRINT( parse( u, chars_from_string( "cd" ) ) );
PRINT( take( 1, parse( u, chars_from_string( "cd" ) ) ) );
PRINT( parse( u, chars_from_string( "ef" ) ) );
PRINT( take( 1, parse( u, chars_from_string( "ef" ) ) ) );
PRINT( Int( garbage_collect( u ) ) );
parser v;
PRINT( v = regex( "ab+(c).|def" ) );
PRINT( parse( v, chars_from_string( "def" ) ) );
PRINT( take( 2, parse( v, chars_from_string( "def" ) ) ) );
parser w;
PRINT( w = regex( "a?b|c" ) );
PRINT( parse( w, chars_from_string( "a" ) ) );
PRINT( parse( w, chars_from_string( "b" ) ) );
PRINT( take( 3, parse( w, chars_from_string( "c" ) ) ) );
PRINT( Int( garbage_collect( w ) ) );
return 0;
}
int test_env(){
object e = env( 0, 2, Symbol(F), Int(2), Symbol(X), Int(4) );
PRINT( e );
PRINT( assoc( Symbol(F), e ) );
PRINT( assoc( Symbol(X), e ) );
return 0;
}
object b( object v, object o ){
return one( cons( Int( - x_( o )->Int.i ), xs_( o ) ) );
}
int test_parsers(){
list ch = chars_from_string( "a b c 1 2 3 d e f 4 5 6" );
{
parser p = result( Int(42) );
PRINT( parse( p, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
}
{
parser q = zero();
PRINT( parse( q, ch ) );
PRINT( Int( garbage_collect( ch ) ) );
}
{
parser r = item();
PRINT( r );
PRINT( parse( r, ch ) );
PRINT( x_( parse( r, ch ) ) );
PRINT( take( 1, x_( parse( r, ch ) ) ) );
PRINT( x_( take( 1, x_( parse( r, ch ) ) ) ) );
PRINT( take( 1, x_( take( 1, x_( parse( r, ch ) ) ) ) ) );
PRINT( parse( bind( r, Operator( 0, b ) ), ch ) );
PRINT( Int( garbage_collect( cons( ch, r ) ) ) );
}
{
parser s = plus( item(), alpha() );
PRINT( s );
PRINT( parse( s, ch ) );
PRINT( take( 2, parse( s, ch ) ) );
PRINT( Int( garbage_collect( ch ) ) );
}
{
parser t = lit( Int( 'a' ) );
PRINT( parse( t, ch ) );
parser u = str( "a b c" );
PRINT( parse( u, ch ) );
PRINT( Int( garbage_collect( cons( ch, cons( t, u ) ) ) ) );
}
return 0;
}
int par_main(){
return
obj_main(),
test_env(), test_parsers(),
test_regex(),
test_pprintf(),
test_pscanf(),
0;
}
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9tok.h" rel="nofollow noreferrer">pc9tok.h</a><br />
Interface to the example tokenizer for <a href="https://www.bell-labs.com/usr/dmr/www/cman.pdf" rel="nofollow noreferrer">circa 1975 pre-K&R C</a>. Perhaps too much macro stuff? All the keywords and operators and punctuation which can be matched as exact strings are defined in an X-macro table which associates each string with an identifier. The identifiers are all defined in the enum for use with the symbol typed objects.</p>
<pre><code>#define PC9TOK_H
#ifndef PC9PAR_H
#include "pc9par.h"
#endif
#define Each_Symbolic(_) \
_("int", k_int) _("char", k_char) _("float", k_float) _("double", k_double) _("struct", k_struct) \
_("auto", k_auto) _("extern", k_extern) _("register", k_register) _("static", k_static) \
_("goto", k_goto) _("return", k_return) _("sizeof", k_sizeof) \
_("break", k_break) _("continue", k_continue) \
_("if", k_if) _("else", k_else) \
_("for", k_for) _("do", k_do) _("while", k_while) \
_("switch", k_switch) _("case", k_case) _("default", k_default) \
/*_("entry", k_entry)*/ \
_("*", o_star) _("++", o_plusplus) _("+", o_plus) _(".", o_dot) \
_("->", o_arrow) _("--", o_minusminus) _("-", o_minus) _("!=", o_ne) _("!", o_bang) _("~", o_tilde) \
_("&&", o_ampamp) _("&", o_amp) _("==", o_equalequal) _("=", o_equal) \
_("^", o_caret) _("||", o_pipepipe) _("|", o_pipe) \
_("/", o_slant) _("%", o_percent) \
_("<<", o_ltlt) _("<=", o_le) _("<", o_lt) _(">>", o_gtgt) _(">=", o_ge) _(">", o_gt) \
_("=+", o_eplus) _("=-", o_eminus) _("=*", o_estar) _("=/", o_eslant) _("=%", o_epercent) \
_("=>>", o_egtgt) _("=<<", o_eltlt) _("=&", o_eamp) _("=^", o_ecaret) _("=|", o_epipe) \
_("(", lparen) _(")", rparen) _(",", comma) _(";", semi) _(":", colon) _("?", quest) \
_("{", lbrace) _("}", rbrace) _("[", lbrack) _("]", rbrack) \
//End Symbolic
#define Enum_name(x,y) y ,
enum token_symbols {
t_id = SYM2,
c_int, c_float, c_char, c_string,
Each_Symbolic( Enum_name )
SYM3
};
list tokens_from_chars( object v );
int tok_main( void );
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9tok.c" rel="nofollow noreferrer">pc9tok.c</a><br />
Implementation of the tokenizer for pre-K&R C. All of the identifiers from the table in the header file are converted into parsers which match the associated string and yield the symbol as output. The next layer can easily match against these symbols. The symbol type object also has an extra <code>data</code> pointer to hold extra stuff. The token functions pack the actual input string and any preliminary whitespace in this pointer in the symbol object. So this data isn't lost, but it's hidden from the parser layer which just deals with token symbols.</p>
<pre><code>#include "pc9tok.h"
#include "pc9objpriv.h"
static object on_spaces( object v, list o ){ return string_from_chars( o ); }
static object on_integer( object v, list o ){ return cons( Symbol(c_int), string_from_chars( o ) ); }
static object on_floating( object v, list o ){ return cons( Symbol(c_float), string_from_chars( o ) ); }
static object on_character( object v, list o ){ return cons( Symbol(c_char), string_from_chars( o ) ); }
static object on_string( object v, list o ){ return cons( Symbol(c_string), string_from_chars( o ) ); }
static object on_identifier( object s, list o ){ return cons( Symbol(t_id), string_from_chars( o ) ); }
#define On_Symbolic(a,b) \
static object on_##b( object v, list o ){ return cons( Symbol(b), string_from_chars( o ) ); }
Each_Symbolic( On_Symbolic )
static parser
token_parser( void ){
parser space = using( many( anyof( " \t\n" ) ), on_spaces );
parser alpha_ = plus( alpha(), chr('_') );
parser integer = using( some( digit() ), on_integer );
parser floating = using( SEQ( plus( SEQ( some( digit() ), chr('.'), many( digit() ) ),
seq( chr('.'), some( digit() ) ) ),
maybe( SEQ( anyof("eE"), maybe( anyof("+-") ), some( digit() ) ) ) ),
on_floating );
parser escape = seq( chr('\\'),
plus( seq( digit(), maybe( seq( digit(), maybe( digit() ) ) ) ),
anyof( "'\"bnrt\\" ) ) );
parser char_ = plus( escape, noneof( "'\n" ) );
parser schar_ = plus( escape, noneof( "\"\n" ) );
parser character = using( SEQ( chr('\''), char_, chr('\'') ), on_character );
parser string = using( SEQ( chr('"'), many( schar_ ), chr('"') ), on_string );
parser constant = PLUS( floating, integer, character, string );
# define Handle_Symbolic(a,b) using( str( a ), on_##b ),
parser symbolic = PLUS( Each_Symbolic( Handle_Symbolic ) zero() );
parser identifier = using( seq( alpha_, many( plus( alpha_, digit() ) ) ), on_identifier );
return seq( space, PLUS( constant, symbolic, identifier ) );
}
static object on_token( object v, list o ){
object space = x_( o );
object symbol = x_( xs_( o ) );
object string = xs_( xs_( o ) );
return symbol->Symbol.data = cons( space, string ), symbol;
return cons( symbol, cons( space, string ) );
}
list
ptokens_from_chars( object s ){
if( !valid( s ) ) return Symbol(EOF);
static parser p;
if( !p ){
p = using( token_parser(), on_token );
add_global_root( p );
}
list r = parse( p, s );
take( 1, r );
r = x_( r );
return cons( x_( r ), Suspension( xs_( r ), ptokens_from_chars ) );
}
list
tokens_from_chars( object s ){
return valid( s ) ? Suspension( s, ptokens_from_chars ) : Symbol(EOF);
}
int test_tokens(){
list tokens = tokens_from_chars( chars_from_string( "'x' auto \"abc\" 12 ;*++'\\42' '\\n' 123 if" ) );
PRINT( tokens );
PRINT( take( 1, tokens ) );
PRINT( take( 2, tokens ) );
PRINT( drop( 1, tokens ) );
PRINT( take( 2, drop( 1, tokens ) ) );
drop( 7, tokens );
PRINT( tokens );
PRINT( Int( garbage_collect( tokens ) ) );
return 0;
}
int tok_main(){
return
par_main(),
test_tokens(),
0;
}
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9syn.h" rel="nofollow noreferrer">pc9syn.h</a><br />
Interface to the Syntax Analyzer for pre-K&R C. Pretty simple this time, just extending the symbol ids and declaring the main parser function.</p>
<pre><code>#define PC9SYN_H
#ifndef PC9TOK_H
#include "pc9tok.h"
#endif
enum syntax_analysis_symbols {
func_def = SYM3,
data_def,
SYM4
};
list tree_from_tokens( object s );
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/pc9syn.c" rel="nofollow noreferrer">pc9syn.c</a><br />
Implementation of the Syntax Analyzer for pre-K&R C. All of the symbols from the tokenizer are converted into parsers which match those symbols and are named with an extra underscore appended. So <code>c_float</code> is an enum, <code>Symbol(c_float)</code> is a symbol object, and <code>c_float_</code> (with extra underscore) is a parser which matches that token symbol. So all the names in here with underscores, like <code>comma_</code> <code>semi_</code> <code>k_if_</code>, are parsers which match against the tokens coming from the input list.</p>
<pre><code>#include "pc9syn.h"
#include "pc9objpriv.h"
#define Extra_Symbols(_) \
_(t_id) _(c_int) _(c_float) _(c_char) _(c_string)
#define Parser_for_symbolic_(a,b) parser b##_ = lit( Symbol(b) );
#define Parser_for_symbol_(b) parser b##_ = lit( Symbol(b) );
static object on_func_def( object v, list o ){
object s = Symbol(func_def); return s->Symbol.data = o, s;
return cons( Symbol(func_def), o );
}
static object on_data_def( object v, list o ){
object s = Symbol(data_def); return s->Symbol.data = o, s;
}
parser
parser_for_grammar( void ){
Each_Symbolic( Parser_for_symbolic_ )
Extra_Symbols( Parser_for_symbol_ )
parser identifier = t_id_;
parser asgnop = PLUS( o_equal_, o_eplus_, o_eminus_, o_estar_, o_eslant_, o_epercent_,
o_egtgt_, o_eltlt_, o_eamp_, o_ecaret_, o_epipe_ );
parser constant = PLUS( c_int_, c_float_, c_char_, c_string_ );
parser lvalue = forward();
parser expression = forward();
*lvalue =
*PLUS(
identifier,
seq( o_star_, expression ),
//SEQ( primary, o_arrow_, identifier ), // introduces a left-recursion indirectly
SEQ( lparen_, lvalue, rparen_ )
);
parser expression_list = seq( expression, many( seq( comma_, expression ) ) );
parser primary =
seq(
PLUS(
identifier,
constant,
SEQ( lparen_, expression, rparen_ ),
SEQ( lvalue, o_dot_, identifier )
),
maybe( PLUS(
SEQ( lparen_, expression_list, rparen_ ),
SEQ( lbrack_, expression, rbrack_ ),
seq( o_arrow_, identifier )
) )
);
*expression =
*seq(
PLUS(
primary,
seq( o_star_, expression ),
seq( o_amp_, expression ),
seq( o_minus_, expression ),
seq( o_bang_, expression ),
seq( o_tilde_, expression ),
seq( o_plusplus_, lvalue ),
seq( o_minusminus_, lvalue ),
seq( lvalue, o_plusplus_ ),
seq( lvalue, o_minusminus_ ),
seq( k_sizeof_, expression ),
SEQ( lvalue, asgnop, expression )
),
maybe( PLUS(
seq( PLUS( o_star_, o_slant_, o_percent_ ), expression ),
seq( PLUS( o_plus_, o_minus_ ), expression ),
seq( PLUS( o_ltlt_, o_gtgt_ ), expression ),
seq( PLUS( o_lt_, o_le_, o_gt_, o_ge_ ), expression ),
seq( PLUS( o_equalequal_, o_ne_ ), expression ),
seq( o_amp_, expression ),
seq( o_caret_, expression ),
seq( o_pipe_, expression ),
seq( o_ampamp_, expression ),
seq( o_pipepipe_, expression ),
SEQ( quest_, expression, colon_, expression ),
seq( comma_, expression )
) )
);
parser constant_expression = expression;
parser statement = forward();
parser statement_list = many( statement );
*statement =
*PLUS(
seq( expression, semi_ ),
SEQ( lbrace_, statement_list, rbrace_ ),
SEQ( k_if_, lparen_, expression, rparen_, statement ),
SEQ( k_if_, lparen_, expression, rparen_, statement, k_else_, statement ),
SEQ( k_do_, statement, k_while_, lparen_, expression, rparen_, semi_ ),
SEQ( k_while_, lparen_, expression, rparen_, statement ),
SEQ( k_for_, lparen_,
maybe( expression ), semi_, maybe( expression ), semi_, maybe( expression ),
rparen_, statement ),
SEQ( k_switch_, lparen_, expression, rparen_, statement ),
SEQ( k_case_, constant_expression, colon_, statement ),
SEQ( k_default_, colon_, statement ),
seq( k_break_, semi_ ),
seq( k_continue_, semi_ ),
seq( k_return_, semi_ ),
SEQ( k_return_, expression, semi_ ),
SEQ( k_goto_, expression, semi_ ),
SEQ( identifier, colon_, statement ),
semi_
);
parser constant_expression_list = seq( constant_expression, many( seq( comma_, constant_expression ) ) );
parser initializer = plus( constant, constant_expression_list );
parser type_specifier = forward();
parser declarator_list = forward();
parser type_declaration = SEQ( type_specifier, declarator_list, semi_ );
parser type_decl_list = some( type_declaration );
parser sc_specifier = PLUS( k_auto_, k_static_, k_extern_, k_register_ );
*type_specifier = *PLUS(
k_int_, k_char_, k_float_, k_double_,
SEQ( k_struct_, lbrace_, type_decl_list, rbrace_ ),
SEQ( k_struct_, identifier, lbrace_, type_decl_list, rbrace_ ),
SEQ( k_struct_, identifier )
);
parser declarator = forward();
*declarator = *seq( PLUS(
identifier,
seq( o_star_, declarator ),
SEQ( lparen_, declarator, rparen_ )
), maybe( PLUS(
seq( lparen_, rparen_ ),
SEQ( lbrack_, constant_expression, rbrack_ )
) )
);
*declarator_list = *seq( declarator, many( seq( comma_, declarator ) ) );
parser decl_specifiers = PLUS( type_specifier, sc_specifier,
seq( type_specifier, sc_specifier ),
seq( sc_specifier, type_specifier ) );
parser declaration = seq( decl_specifiers, maybe( declarator_list ) );
parser declaration_list = seq( declaration, many( seq( comma_, declaration ) ) );
parser init_declarator = seq( declarator, maybe( initializer ) );
parser init_declarator_list = seq( init_declarator, many( seq( comma_, init_declarator ) ) );
parser data_def = using( SEQ( maybe( k_extern_ ),
maybe( type_specifier ),
maybe( init_declarator_list ), semi_ ),
on_data_def );
parser parameter_list = maybe( seq( expression, many( seq( comma_, expression ) ) ) );
parser function_declarator = SEQ( declarator, lparen_, parameter_list, rparen_ );
parser function_statement = SEQ( lbrace_, maybe( declaration_list ), many( statement ), rbrace_ );
parser function_body = seq( maybe( type_decl_list ), function_statement );
parser function_def = using( SEQ( maybe( type_specifier ), function_declarator, function_body ),
on_func_def );
parser external_def = plus( function_def, data_def );
parser program = some( external_def );
return program;
}
list
tree_from_tokens( object s ){
if( !s ) return NIL_;
static parser p;
if( !p ){
p = parser_for_grammar();
add_global_root( p );
}
return parse( p, s );
}
int test_syntax(){
char *source =
"\n"
"int i,j,k 5;\n"
"float d 3.4;\n"
"int max(a, b, c)\n"
"int a, b, c;\n"
"{\n"
" int m;\n"
" m = (a>b)? a:b;\n"
" return(m>c? m:c);\n"
"}\n"
"main( ) {\n"
"\tprintf(\"Hello, world\");\n"
"}\n"
"\t if( 2 ){\n\t x = 5;\n\t } int auto";
object tokens = tokens_from_chars( chars_from_string( source ) );
add_global_root( tokens );
PRINT( take( 4, tokens ) );
object program = tree_from_tokens( tokens );
PRINT( program );
PRINT( x_( x_( ( drop( 1, program ), program ) ) ) );
PRINT_FLAT( x_( x_( program ) ) );
PRINT_DATA( x_( x_( program ) ) );
PRINT( xs_( x_( program ) ) );
PRINT( Int( garbage_collect( program ) ) );
return 0;
}
int main(){
return tok_main(),
test_syntax(),
0;
}
</code></pre>
<p><a href="https://github.com/luser-dr00g/pcomb/blob/7236d34a059a432414b486672344e17de197d2cb/Makefile" rel="nofollow noreferrer">Makefile</a></p>
<p>The input to the test is for the <code>pscanf()</code> calls which looks for the literal <code>"abc"</code> then a <code>%c</code> then a <code>%s</code>. And <code>test</code> is the first rule, so a simple <code>make</code> command will compile and then run the test rule/script.</p>
<pre><code>CFLAGS= -std=c99 -g -Wall -Wpedantic -Wno-switch -Wreturn-type -Wunused-variable
CFLAGS+= $(cflags)
test : pc9
echo abc j string | ./$<
clean :
rm *.o
pc9 : pc9obj.o pc9fp.o pc9par.o pc9tok.o pc9syn.o
$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
</code></pre>
<p>All told, it's just under 1500 lines.</p>
<pre><code>$ wc -l *[ch]
128 pc9fp.c
19 pc9fp.h
316 pc9obj.c
54 pc9obj.h
24 pc9objpriv.h
529 pc9par.c
48 pc9par.h
208 pc9syn.c
12 pc9syn.h
85 pc9tok.c
38 pc9tok.h
28 ppnarg.h
1489 total
</code></pre>
<p>Output from simple tests. At the very end, the <code>print_data</code> function is used to recover all the strings hidden inside the token symbols in the syntax tree, reconstructing the source code.</p>
<pre><code>$ make -k
cc -std=c99 -g -Wall -Wpedantic -Wno-switch -Wreturn-type -Wunused-variable -c -o pc9obj.o pc9obj.c
cc -std=c99 -g -Wall -Wpedantic -Wno-switch -Wreturn-type -Wunused-variable -c -o pc9fp.o pc9fp.c
cc -std=c99 -g -Wall -Wpedantic -Wno-switch -Wreturn-type -Wunused-variable -c -o pc9par.o pc9par.c
cc -std=c99 -g -Wall -Wpedantic -Wno-switch -Wreturn-type -Wunused-variable -c -o pc9tok.o pc9tok.c
cc -std=c99 -g -Wall -Wpedantic -Wno-switch -Wreturn-type -Wunused-variable -c -o pc9syn.o pc9syn.c
cc -std=c99 -g -Wall -Wpedantic -Wno-switch -Wreturn-type -Wunused-variable -o pc9 pc9obj.o pc9fp.o pc9par.o pc9tok.o pc9syn.o
echo abc j string | ./pc9
test_basics: ch = ...
test_basics: Int( garbage_collect( ch ) ) = 0
test_basics: take( 1, ch ) = (97 _ )
test_basics: Int( garbage_collect( ch ) ) = 4
test_basics: x_( ch ) = 97
test_basics: Int( garbage_collect( ch ) ) = 1
test_basics: x_( xs_( ch ) ) = ...
test_basics: Int( garbage_collect( ch ) ) = 2
test_basics: take( 1, x_( xs_( ch ) ) ) = (_ _ )
test_basics: Int( garbage_collect( ch ) ) = 5
test_basics: take( 5, ch ) = (97 98 99 100 101 _ )
test_basics: Int( garbage_collect( ch ) ) = 12
test_basics: ch = (97 98 99 100 101 ... )
test_basics: Int( garbage_collect( ch ) ) = 1
test_basics: take( 6, ch ) = (97 98 99 100 101 102 _ )
test_basics: Int( garbage_collect( ch ) ) = 9
test_basics: take( 1, ch ) = (97 _ )
test_basics: Int( garbage_collect( ch ) ) = 2
test_basics: take( 2, ch ) = (97 98 _ )
test_basics: Int( garbage_collect( ch ) ) = 3
test_basics: take( 2, ch ) = (97 98 _ )
test_basics: Int( garbage_collect( ch ) ) = 3
test_basics: take( 2, ch ) = (97 98 _ )
test_basics: Int( garbage_collect( ch ) ) = 3
test_basics: take( 2, ch ) = (97 98 _ )
test_basics: Int( garbage_collect( ch ) ) = 3
test_env: e = ((X 4 )(F 2 )() )
test_env: assoc( Symbol_( F, "F" ), e ) = 2
test_env: assoc( Symbol_( X, "X" ), e ) = 4
test_parsers: parse( p, ch ) = ((42 ... )_ )
test_parsers: Int( garbage_collect( ch ) ) = 33
test_parsers: parse( q, ch ) = _
test_parsers: Int( garbage_collect( ch ) ) = 2
test_parsers: r = Parser
test_parsers: parse( r, ch ) = ((97 ... )_ )
test_parsers: x_( parse( r, ch ) ) = (97 ... )
test_parsers: take( 1, x_( parse( r, ch ) ) ) = (97 _ )
test_parsers: x_( take( 1, x_( parse( r, ch ) ) ) ) = 97
test_parsers: take( 1, x_( take( 1, x_( parse( r, ch ) ) ) ) ) = (_ _ )
test_parsers: parse( bind( r, Operator( 0, b ) ), ch ) = ((-97 ... )... )
test_parsers: Int( garbage_collect( cons( ch, r ) ) ) = 46
test_parsers: s = Parser
test_parsers: parse( s, ch ) = ((97 ... )... )
test_parsers: take( 2, parse( s, ch ) ) = ((97 ... )(97 ... )_ )
test_parsers: Int( garbage_collect( ch ) ) = 76
test_parsers: parse( t, ch ) = ((97 ... )... )
test_parsers: parse( u, ch ) = (((97 32 98 32 99 () )... )... )
test_parsers: Int( garbage_collect( cons( ch, cons( t, u ) ) ) ) = 372
test_regex: a = regex( "\\." ) = _
test_regex: parse( a, chars_from_string( "a" ) ) = _
test_regex: parse( a, chars_from_string( "." ) ) = _
test_regex: parse( a, chars_from_string( "\\." ) ) = _
test_regex: b = regex( "\\\\\\." ) = _
test_regex: parse( b, chars_from_string( "\\." ) ) = _
test_regex: take( 3, parse( b, chars_from_string( "\\." ) ) ) = _
test_regex: r = regex( "a?b+(c).|def" ) = Parser
test_regex: parse( r, chars_from_string( "abc" ) ) = ...
test_regex: parse( r, chars_from_string( "abbcc" ) ) = ...
test_regex: Int( garbage_collect( r ) ) = 13660
test_regex: s = parse( r, chars_from_string( "def" ) ) = ...
test_regex: take( 3, s ) = _
test_regex: parse( r, chars_from_string( "deff" ) ) = ...
test_regex: parse( r, chars_from_string( "adef" ) ) = ...
test_regex: parse( r, chars_from_string( "bcdef" ) ) = ...
test_regex: Int( garbage_collect( cons( r, s ) ) ) = 130
test_regex: t = regex( "ac|bd" ) = _
test_regex: parse( t, chars_from_string( "ac" ) ) = _
test_regex: take( 1, parse( t, chars_from_string( "bd" ) ) ) = _
test_regex: Int( garbage_collect( t ) ) = 5294
test_regex: u = regex( "ab|cd|ef" ) = _
test_regex: parse( u, chars_from_string( "ab" ) ) = _
test_regex: parse( u, chars_from_string( "cd" ) ) = _
test_regex: take( 1, parse( u, chars_from_string( "cd" ) ) ) = _
test_regex: parse( u, chars_from_string( "ef" ) ) = _
test_regex: take( 1, parse( u, chars_from_string( "ef" ) ) ) = _
test_regex: Int( garbage_collect( u ) ) = 7804
test_regex: v = regex( "ab+(c).|def" ) = Parser
test_regex: parse( v, chars_from_string( "def" ) ) = _
test_regex: take( 2, parse( v, chars_from_string( "def" ) ) ) = _
test_regex: w = regex( "a?b|c" ) = Parser
test_regex: parse( w, chars_from_string( "a" ) ) = ...
test_regex: parse( w, chars_from_string( "b" ) ) = ...
test_regex: take( 3, parse( w, chars_from_string( "c" ) ) ) = ((() ... )_ )
test_regex: Int( garbage_collect( w ) ) = 13306
test_pprintf: Int( pprintf( "%% abc %c %s\n", 'x', "123" ) ) = % abc x 123
12
test_pscanf: Int( pscanf( "" ) ) = 0
test_pscanf: Int( pscanf( "abc" ) ) = 0
test_pscanf: Int( pscanf( " %c", &c ) ) = 1
test_pscanf: string_from_chars( Int( c ) ) = "j"
test_pscanf: Int( pscanf( "%s", buf ) ) = 1
test_pscanf: String( buf, 0 ) = "string"
test_tokens: tokens = ...
test_tokens: take( 1, tokens ) = (c_char _ )
test_tokens: take( 2, tokens ) = (c_char k_auto _ )
test_tokens: drop( 1, tokens ) = (k_auto ... )
test_tokens: take( 2, drop( 1, tokens ) ) = (k_auto c_string _ )
test_tokens: tokens = (c_char k_auto c_string c_int semi o_star o_plusplus ... )
test_tokens: Int( garbage_collect( tokens ) ) = 28834
test_syntax: take( 4, tokens ) = (k_int t_id comma t_id _ )
test_syntax: program = ...
test_syntax: x_( x_( ( drop( 1, program ), program ) ) ) = (data_def data_def func_def func_def () )
test_syntax: x_( x_( program ) ) flat= data_def data_def func_def func_def
test_syntax: x_( x_( program ) ) data=
int i,j,k 5;
float d 3.4;
int max(a, b, c)
int a, b, c;
{
int m;
m = (a>b)? a:b;
return(m>c? m:c);
}
main( ) {
printf("Hello, world");
}
test_syntax: xs_( x_( program ) ) = (k_if ... )
test_syntax: Int( garbage_collect( program ) ) = 434910
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T05:33:10.670",
"Id": "425479",
"Score": "0",
"body": "An earlier, less lazy version of this code was posted in [comp.lang.c](https://groups.google.com/d/topic/comp.lang.c/8X7r8kacvrA/discussion) and received helpful comments which have been applied in the code here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T07:36:01.317",
"Id": "430893",
"Score": "0",
"body": "Have you considered `CFLAGS += -Wextra` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-19T18:04:07.507",
"Id": "430956",
"Score": "0",
"body": "@TobySpeight I hadn't before, but trying it now it just tells me about unused parameters. They're all in `fOper` functions which don't use the environment parameter. It's a good point that I should have checked this, but I think it doesn't tell me anything interesting."
}
] | [
{
"body": "<h2>Bug: singleton objects have no allocation record</h2>\n<p>Since the garbage collector will try to set the <code>mark()</code> in a <code>SYMBOL</code> object, the <code>T_</code> object needs a dummy allocation record. <code>NIL_</code> doesn't need one since an <code>INVALID</code> object will not get marked.</p>\n<p>pc9obj.c:</p>\n<pre><code>object T_ = &(1[(union uobject[]){{ .t = 0 },{ .Symbol = { SYMBOL, T, "T" } }}]),\n NIL_ = (union uobject[]){{ .t = INVALID }};\n</code></pre>\n<h2>Bug: using object fields for non-object data</h2>\n<p>In the <code>pprintf()</code> and <code>pscanf()</code> functions, the <code>object</code> field in <code>OPERATOR</code> objects sometimes contains a <code>va_list *</code>! The garbage collector might fiddle with the memory around this address if it tries to set the (non-existant) <code>mark()</code>. The copious <code>(void *)</code> casts are a code smell. Better to use the <code>VOID</code> type object to hold this pointer.</p>\n<h2>Missing functions</h2>\n<p>There's <code>some</code> for 1 or more, <code>many</code> for 0 or more, <code>maybe</code> for 0 or 1.\nBut there's no function to match <em>n times</em>, or <em>n or more</em>, or <em>n up to m times</em> — these kind of quantifiers.</p>\n<h2>Poor namespacing for internal symbols</h2>\n<pre><code>enum parser_symbols {\n VALUE = SYM1, PRED, P, PP, NN, Q, R, FF, XX, AA, ID, USE, ATOM,\n SYM2\n};\n</code></pre>\n<p>What are <code>P, PP, NN, Q, R, FF, XX, AA</code>? <code>VALUE</code> <code>PRED</code> and <code>ATOM</code> are better but still kinda vague.</p>\n<h2>Short-circuit tests (and maybe actually test stuff)</h2>\n<pre><code>int par_main(){\n return \n obj_main(),\n test_env(), test_parsers(),\n test_regex(),\n test_pprintf(),\n test_pscanf(),\n 0;\n}\n</code></pre>\n<p>Bonus formatting error. Better to short-circuit the tests based on the return values.</p>\n<pre><code>int par_main(){\n return 0\n || obj_main()\n || test_env()\n || test_parsers()\n || test_regex()\n || test_pprintf()\n || test_pscanf()\n || 0;\n}\n</code></pre>\n<p>Then the testing functions can return non-zero to stop producing output.</p>\n<h2>No error reporting</h2>\n<p>A syntax error during parsing will result in an empty list being returned. <a href=\"https://www.google.com/url?q=https%3A%2F%2Fpdfs.semanticscholar.org%2F6669%2Ff223fba59edaeed7fabe02b667809a5744d9.pdf&sa=D&sntz=1&usg=AFQjCNFu6zqDwrbgnj91tHgwq0qjkm9s7g\" rel=\"nofollow noreferrer\">Graham Hutton's paper</a> describes how to rewrite the basic parser combinators so that meaningful error messages can be produced -- without using Monad Transformers which is the more typical way in functional languages.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T03:34:58.283",
"Id": "220265",
"ParentId": "220214",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T04:26:38.427",
"Id": "220214",
"Score": "9",
"Tags": [
"c",
"parsing",
"functional-programming",
"lazy"
],
"Title": "Lazy, Functional Parser Combinators"
} | 220214 |
<p>I have a websocket connection with 3-rd party API. The API returns a lot of data, in a peak hours it returns hundreds messages per second. I need to process the data for two purposes: save everything in a DB and send some data to RabbitMq.</p>
<p>The idea is the following:<br>
I want to save data to DB when batch size is 1000 or by timeout which is equal to 3 seconds. </p>
<p>I want to publish data to RabbitMQ by 1 second timeout. It's a kind of throttling, because there are a lot of data. Moreover, I need to select the last record for the specific ticker, I have done it in the <code>ActionBlock</code>, f.e: we have the following records in the batch: </p>
<blockquote>
<p>{"Ticker": "MSFT", "DateTime": '2019-05-14T10:00:00:100'} <br>
{"Ticker": "MSFT", "DateTime": '2019-05-14T10:00:00:150'} <br>
{"Ticker": "AAPL", "DateTime": '2019-05-14T10:00:00:300'}</p>
</blockquote>
<p>I need to publish the last for the specific ticker only, so after filtering there will be 2 records that I am going to publish:</p>
<blockquote>
<p>{"Ticker": "MSFT", "DateTime": '2019-05-14T10:00:00:150'} <br>
{"Ticker": "AAPL", "DateTime": '2019-05-14T10:00:00:300'}</p>
</blockquote>
<p>Full code: </p>
<pre><code>public class StreamMessagePipeline < T > where T: StreamingMessage {
private readonly BatchBlock < T > _saveBatchBlock;
private readonly BatchBlock < T > _publishBatchBlock;
public StreamMessagePipeline() {
_saveBatchBlock = new BatchBlock < T > (1000);
_publishBatchBlock = new BatchBlock < T > (500);
SetupSaveBatchPipeline();
SetupPublishBatchPipeline();
}
private void SetupSaveBatchPipeline() {
var saveBatchTimeOut = TimeSpan.FromSeconds(3);
var saveBatchTimer = new Timer(saveBatchTimeOut.TotalMilliseconds);
saveBatchTimer.Elapsed += (s, e) = >_saveBatchBlock.TriggerBatch();
var actionBlockSave = new ActionBlock < IEnumerable < T >> (x = >{
//Reset the timeout since we got a batch
saveBatchTimer.Stop();
saveBatchTimer.Start();
Console.WriteLine($ "Save to DB : {x.Count()}");
});
_saveBatchBlock.LinkTo(actionBlockSave, new DataflowLinkOptions {
PropagateCompletion = true
});
}
private void SetupPublishBatchPipeline() {
var publishBatchTimeOut = TimeSpan.FromSeconds(1);
var publishBatchTimer = new Timer(publishBatchTimeOut.TotalMilliseconds);
publishBatchTimer.Elapsed += (s, e) = >_publishBatchBlock.TriggerBatch();
var actionBlockPublic = new ActionBlock < IEnumerable < T >> (x = >{
var res = x.GroupBy(d => d.Ticker).Select(d = >d.OrderByDescending(s =>s.DateTime).FirstOrDefault()).ToList();
Console.WriteLine($ "Publish data to somewhere : {res.Count()}");
//Reset the timeout since we got a batch
publishBatchTimer.Stop();
publishBatchTimer.Start();
});
_publishBatchBlock.LinkTo(actionBlockPublic, new DataflowLinkOptions {
PropagateCompletion = true
});
}
public async Task Handle(T record) {
await _saveBatchBlock.SendAsync(record);
await _publishBatchBlock.SendAsync(record);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T13:08:25.950",
"Id": "425510",
"Score": "0",
"body": "I wouldn't use `Console.WriteLine` for this task. Instead inject some type of `ILogger` into your class as a dependency and use that. `Console.Write` may throw exceptions depending on where your code is running (i.e. Azure App Service)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:58:04.620",
"Id": "425589",
"Score": "0",
"body": "@BradM Thanks for the comment. I will delete `Console` of course, it's a just a prototype. I didnt mention it but I am interested in the review of DataFlow specific things, do I use it correct for the my task and so on."
}
] | [
{
"body": "<p><strong>General comments</strong>: I would move the timeout and batch sizes into private fields. I don't know what version of c# you are using but you could create a class or if you have the nice tuple support you can just create it like so</p>\n\n<pre><code>private readonly (TimeSpan timeout, int buffer) _saveBatchSettings = (TimeSpan.FromSeconds(3), 1000);\nprivate readonly (TimeSpan timeout, int buffer) _publishBatchSettings = (TimeSpan.FromSeconds(1), 500);\n</code></pre>\n\n<p>It's nice to have these outside the main program because typically with batching you have to tweak the timeouts and size to find the sweet spot and this make it simpler to find what you need to change. </p>\n\n<p>Also you have no way to complete the source. I would recommend making the class IDisposable and in the dispose mark the source as complete. </p>\n\n<p><strong>TPL DataFlow comments</strong>: Why not use a BroadcastBlock that is tied to the BatchBlocks then it's one send and not two. </p>\n\n<p>Move this</p>\n\n<pre><code>var res = x.GroupBy(d => d.Ticker).Select(d = >d.OrderByDescending(s =>s.DateTime).FirstOrDefault()).ToList();\n</code></pre>\n\n<p>Into a TransformBlock and make the ActionBlock just contain the code to publish the result.</p>\n\n<p>For ActionBlock, this is just my preference, I make a method that the action block calls to instead of inline lambda it. That code is typically the processing code and it's easier to maintain and read if it's in it's own method and outside the pipeline setup. </p>\n\n<p><strong>ReactiveExtensions</strong>: If you are willing to add ReactiveExtensions to your project you can mix and Rx and TPL DataFlow Blocks. Rx has a built in method for your buffering called <a href=\"https://docs.microsoft.com/en-us/previous-versions/dotnet/reactive-extensions/hh229200(v%3Dvs.103)\" rel=\"nofollow noreferrer\">Buffer</a>. The DataFlow blocks has an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.dataflowblock.asobservable?view=netcore-2.2#System_Threading_Tasks_Dataflow_DataflowBlock_AsObservable__1_System_Threading_Tasks_Dataflow_ISourceBlock___0__\" rel=\"nofollow noreferrer\">AsObservable</a> and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.dataflowblock.asobserver?view=netcore-2.2\" rel=\"nofollow noreferrer\">AsObserver</a> to switch to and from Rx and TPL. This would be an example for using Rx with TPL</p>\n\n<pre><code>public class StreamMessagePipeline<T> : IDisposable\n where T : StreamingMessage\n{\n private BroadcastBlock<T> _source;\n\n private readonly (TimeSpan timeout, int buffer) _saveBatchSettings = (TimeSpan.FromSeconds(3), 1000);\n private readonly (TimeSpan timeout, int buffer) _publishBatchSettings = (TimeSpan.FromSeconds(1), 500);\n\n public StreamMessagePipeline()\n {\n _source = new BroadcastBlock<T>(x => x);\n SetupSaveBatchPipeline();\n SetupPublishBatchPipeline();\n }\n\n public async Task Handle(T record)\n {\n await _source.SendAsync(record);\n }\n\n private void SetupSaveBatchPipeline()\n {\n var actionBlockSave = new ActionBlock<IList<T>>(SaveBatch);\n\n // Instead of action block you could stay in Rx and just use Subscribe \n _source.AsObservable()\n .Buffer(_saveBatchSettings.timeout, _saveBatchSettings.buffer)\n .Where(x => x.Count > 0) // unlike TriggerBatch Buffer will send out an empty list\n .Subscribe(actionBlockSave.AsObserver());\n }\n\n private void SetupPublishBatchPipeline()\n {\n\n var transformBlock = new TransformBlock<IList<T>, IList<T>>(x =>\n {\n return x.GroupBy(d => d.Ticker)\n .Select(d => d.OrderByDescending(s => s.DateTime).FirstOrDefault()).ToList();\n });\n\n var actionBlockPublish = new ActionBlock<IList<T>>(PublishBatch);\n\n transformBlock.LinkTo(actionBlockPublish, new DataflowLinkOptions()\n {\n PropagateCompletion = true,\n });\n\n _source.AsObservable()\n .Buffer(_publishBatchSettings.timeout, _publishBatchSettings.buffer)\n .Where(x => x.Count > 0) // unlike TriggerBatch Buffer will send out an empty list\n .Subscribe(transformBlock.AsObserver());\n }\n\n private void SaveBatch(IList<T> messages)\n {\n // Save the batch\n }\n\n private void PublishBatch(IList<T> messages)\n {\n // publish the batch \n }\n\n #region IDisposable Support\n private bool disposedValue = false; // To detect redundant calls\n\n protected virtual void Dispose(bool disposing)\n {\n if (!disposedValue)\n {\n if (disposing)\n {\n _source.Complete();\n }\n disposedValue = true;\n }\n }\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n #endregion\n\n}\n</code></pre>\n\n<p><strong>Update</strong> If you don't want to use Rx you can still make a custom block to that has the same functionality. </p>\n\n<pre><code>public static class TimerBatchBlock\n{\n public static IPropagatorBlock<T, T[]> Create<T>(int batchSize, TimeSpan timeSpan, GroupingDataflowBlockOptions options = null)\n {\n var batchBlock = new BatchBlock<T>(batchSize, options ?? new GroupingDataflowBlockOptions());\n var broadCastBlock = new BroadcastBlock<T[]>(x => x);\n var bufferBlock = new BufferBlock<T[]>();\n\n // timer setup (System.Threading.Timer)\n var timer = new Timer(x => ((BatchBlock<T>)x).TriggerBatch(), batchBlock, timeSpan, timeSpan);\n var resetTimerBlock = new ActionBlock<T[]>(_ => timer.Change(timeSpan, timeSpan)); // reset timer each time buffer outputs\n resetTimerBlock.Completion.ContinueWith(_ => timer.Dispose());\n\n // link everything up\n var linkOptions = new DataflowLinkOptions()\n {\n PropagateCompletion = true,\n };\n broadCastBlock.LinkTo(resetTimerBlock, linkOptions);\n broadCastBlock.LinkTo(bufferBlock, linkOptions);\n batchBlock.LinkTo(broadCastBlock, linkOptions);\n\n return DataflowBlock.Encapsulate(batchBlock, bufferBlock);\n }\n}\n</code></pre>\n\n<p>You would link BroadCastBlock -> TimerBatchBlock -> ActionBlock</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:05:10.037",
"Id": "425521",
"Score": "0",
"body": "`async/await` may be safely removed from the `Handle` method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T09:01:36.083",
"Id": "425590",
"Score": "0",
"body": "yeah didn't think about broadcast block. I know about rx, use rxjs significally. But, not sure about using it here, don't want to mix. Big thanks for the example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:58:08.470",
"Id": "425639",
"Score": "1",
"body": "@user348173 updated answer to have a custom dataflow block instead of Rx."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T17:11:54.460",
"Id": "425780",
"Score": "0",
"body": "@CharlesNRice it looks awesome. Thank you very much."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:35:00.460",
"Id": "220237",
"ParentId": "220215",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220237",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T05:08:50.797",
"Id": "220215",
"Score": "5",
"Tags": [
"c#",
"tpl-dataflow"
],
"Title": "Handle stream data with Dataflow"
} | 220215 |
<p>The following code works fine. When a user clicks on an element, an AJAX request is made, which will return the query result. The results are being displayed in a view. I read many articles where everyone is doing HTML code in controller when getting data with AJAX and show in view as same I did. Any good suggestions to avoid HTML code in controller make controller view and script separate.</p>
<p><strong>Controller:</strong></p>
<pre><code>public function ajax(Request $request){
// $data = $request->all();
$data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();
foreach ($data['products'] as $product){
echo $product->name;
}
// dd($data);
// if($request->ajax()){
// return "AJAX";
// }
// return "HTTP";
// $data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();
// return $data;
</code></pre>
<p>}</p>
<p><strong>Script</strong></p>
<pre><code> <script type="text/javascript">
// $.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
$(document).ready(function(){
// Load more data
$('.load-more').click(function(){
var row = Number($('#row').val());
var allcount = Number($('#all').val());
var rowperpage = 3;
// row = row + rowperpage;
row = row + 3;
if(row <= allcount){
$("#row").val(row);
$.ajax({
url: "{{ route('ajax') }}",
type: 'post',
datatype: 'JSON',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data: {row:row},
// error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert('hi');
// }
success: function(response){
// Setting little delay while displaying new content
setTimeout(function() {
// appending posts after last post with class="post"
$(".post:last").after(response).show().fadeIn("slow");
var rowno = row + 3;
// checking row value is greater than allcount or not
if(rowno > allcount){
// Change the text and background
$('.load-more').text("show less");
$('.load-more').css("background","darkorchid");
}else{
$(".load-more").text("Load more");
}
}, 2000);
}
});
}else{
$('.load-more').text("Loading...");
// Setting little delay while removing contents
setTimeout(function() {
// When row is greater than allcount then remove all class='post' element after 3 element
$('.post:nth-child(3)').nextAll('.post').remove().fadeIn("slow");
// Reset the value of row
$("#row").val(0);
// Change the text and background
$('.load-more').text("Load more");
$('.load-more').css("background","#15a9ce");
}, 2000);
}
});
});
</script>
</code></pre>
<p><strong>view</strong></p>
<pre><code> @foreach($leedManufacturers as $leedsManufacturer)
{{-- @foreach($leedManufacturers as $leedsManufacturer) --}}
<div class="post" id="post{{$leedsManufacturer['id']}}">
<label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['name'], 300)}}
<input type="checkbox">
<span class="checkmark"></span>
</label>
</div>
{{-- for load more script --}}
{{-- <input type="hidden" id="row" value="0"> --}}
{{-- <input type="hidden" id="all" value="{{$total_manufacturers}}"> --}}
@endforeach
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T16:32:10.180",
"Id": "428742",
"Score": "0",
"body": "[Cross posted from Stack overflow](https://stackoverflow.com/q/56146607/1575353)"
}
] | [
{
"body": "<p>Your example:</p>\n\n<pre><code>public function ajax(Request $request){ \n$data['products'] = Product::select('products.id', 'products.name', 'products.banner')->get();\n\nforeach ($data['products'] as $product){\n echo $product->name;\n}\n</code></pre>\n\n<p><em>Attn: I omit commented string.</em></p>\n\n<p>You do not need to get the query results into $data, especially if before you perform <code>$data = $request->all();</code>. Use another variable, in this case the $products may be okay.</p>\n\n<p>If your 'Product' model is correct, then in the query you not need to use products.id - i.e. table name, need just field name.</p>\n\n<p>Next, when you want pass the result to view, you need to do so as described in Doc:</p>\n\n<p><code>return view('your_view_name', ['products' => $products]);</code></p>\n\n<p>As described <a href=\"https://laravel.com/docs/5.3/controllers\" rel=\"nofollow noreferrer\">in official documentation</a> - versions there are from 5.0 up to 5.8, choose any you need.</p>\n\n<p>So, this part of your code becomes:</p>\n\n<pre><code>public function ajax(Request $request){ \n $products = Product::select('id', 'name', 'banner')->get();\n return view('your_view_name', ['products' => $products]);\n}\n</code></pre>\n\n<p><strong>Remember 2 things</strong>: </p>\n\n<ol>\n<li>With that query you'll get all products from DB and there may be a huge number of results.</li>\n<li>the view has to be a <em>blade</em> type of template.</li>\n</ol>\n\n<p>In your 'view' I see this line:</p>\n\n<p><code>@foreach($leedManufacturers as $leedsManufacturer)</code></p>\n\n<p>but I do not see a variable $leedManufacturers in the controller so you have no data for it.</p>\n\n<p>To show $products result use the same but for $products, like:</p>\n\n<pre><code><ol>\n @foreach($products as $product)\n <li>\n <div>id: {{$product->id}}, name: {{$product->name}}</div>\n <div>{{$product->banner}}</div>\n </li>\n @endforeach\n</ol>\n</code></pre>\n\n<p>Also, when you need , you may use this (example)</p>\n\n<pre><code>@if (xxxxxxxxx === 1)\n I have one record!\n@elseif (yyyyyyyyyy > 1)\n I have multiple records!\n@else\n I don't have any records!\n@endif\n</code></pre>\n\n<p><a href=\"https://laravel.com/docs/5.3/blade#if-statements\" rel=\"nofollow noreferrer\">https://laravel.com/docs/5.3/blade#if-statements</a></p>\n\n<p>And in view you can use even</p>\n\n<pre><code>@php\n pure php code here\n@endphp\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T15:07:22.793",
"Id": "221660",
"ParentId": "220220",
"Score": "3"
}
},
{
"body": "<h2>Responding to your prompt</h2>\n\n<blockquote>\n <p>Any good suggestions to avoid HTML code in controller make controller view and script separate.</p>\n</blockquote>\n\n<p>I would suggest you consider using a template on the client-side, and having the AJAX request return data in JSON format. That way the Laravel controller doesn't have to worry about the HTML formatted-data.</p>\n\n<h2>Review Feedback</h2>\n\n<p>That name <code>ajax</code> seems very non-descriptive for the route and Laravel Controller method name. Obviously it is intended to be used with an AJAX call but what happens when you want to have another AJAX call to load separate data? Perhaps a better name would be something like <code>loadProducts</code>.</p>\n\n<p>As @Vlad suggested in <a href=\"https://codereview.stackexchange.com/a/221660/120114\">his answer</a> that query will get all results because it doesn't appear to be filtered or limited to any number of results. Perhaps utilizing page number parameters or other filters would be useful.</p>\n\n<hr>\n\n<p>I see <code>$('.load-more')</code> multiple times in the JavaScript code. How many elements are there with that class name <em><code>load-more</code></em>? If there is only one, then perhaps it would be more fitting to use an <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\"><em>id</em></a> attribute instead of a class name to select that element. </p>\n\n<p>Also, it would be wise to store DOM element references instead of querying the DOM each time. For example, </p>\n\n<pre><code>var loadMoreContainer = $('.load-more');\n</code></pre>\n\n<p>could then be used to simplify code like:</p>\n\n<blockquote>\n<pre><code>if(rowno > allcount){\n // Change the text and background\n $('.load-more').text(\"show less\");\n $('.load-more').css(\"background\",\"darkorchid\");\n}else{\n $(\".load-more\").text(\"Load more\");\n}\n</code></pre>\n</blockquote>\n\n<p>To this:</p>\n\n<pre><code>if(rowno > allcount){\n // Change the text and background\n loadMoreContainer.text(\"show less\") //note we are chaining here\n .css(\"background\",\"darkorchid\");\n}else{\n loadMoreContainer.text(\"Load more\");\n}\n</code></pre>\n\n<p>Note how the call to <code>.css</code> was chained to the previous line, where the semi-colon was removed from the end of the line.</p>\n\n<hr>\n\n<p>While that syntax of <code>$(document).ready()</code> still works with the latest jQuery version (i.e. 3.3.1 at the time of typing), it is deprecated and the recommended syntax is simply <code>$(function() {})</code><sup><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n\n<p><sup>1</sup><sub><a href=\"https://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">https://api.jquery.com/ready/</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-04T16:25:51.970",
"Id": "221665",
"ParentId": "220220",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T08:16:09.890",
"Id": "220220",
"Score": "0",
"Tags": [
"javascript",
"php",
"ajax",
"dom",
"laravel"
],
"Title": "Asynchronous query to load products from laravel controller"
} | 220220 |
<p>I'm developing an app that use socket to receive messages from a chat.
I'm using an MVP approach and I store the data in a Singleton class named <code>DataBridge</code> like this:</p>
<pre><code>class myApplication: Application() {
val dataBridge: DataBridge = DataBridge()
val deviceManager: DeviceManager = DeviceManager(this)
override fun onCreate() {
super.onCreate()
instance = this
//init Logger
TimberImplementation.init()
//init Maps
Mapbox.getInstance(this, MAP_ACCESS_TOKEN)
}
companion object {
lateinit var instance: InfiniteApplication
private set
}
}
</code></pre>
<p>I have the following scenario:</p>
<ul>
<li>Main Activity: create socket connection and update data in <code>DataBridge</code> class. It has a <code>ViewPagerAdapter</code> with 4 fragments. Each Fragment has it's own <code>Presenter</code>.</li>
<li>Chat Activity: listen changes from <code>DataBridge</code> like <code>onNewMessage</code> (fired by <code>HomeActivity</code>) and display the chat</li>
</ul>
<p>The question is: is a good practice to share Live Model by Application and make it accessible from presenter of different activities?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T11:17:11.173",
"Id": "425499",
"Score": "0",
"body": "Welcome to Code Review! Your code does seem to be a *code stub*, since there are likely relevant parts missing, so the results you get from the code review might be suboptimal."
}
] | [
{
"body": "<p>Is a good practice to share LiveData?\n<strong>Yeah</strong></p>\n\n<p>Here as you are using the data in databridge as a single source of truth and it is used hold data which is needed to be shared across multiple screen with live updates, Livedata is a really good option as it will also handle the lifecycle for you.</p>\n\n<p>Android docs also has sample on <a href=\"https://developer.android.com/topic/libraries/architecture/livedata\" rel=\"nofollow noreferrer\">Extending LiveData</a> to create your own singleton data source which you may find helpful.</p>\n\n<p>Also you can leverage the feature of <a href=\"https://kotlinlang.org/docs/reference/object-declarations.html\" rel=\"nofollow noreferrer\">Object declarations</a> in kotlin to lazy initialize your DataBridge rather than in Application class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-24T09:39:26.130",
"Id": "489792",
"Score": "0",
"body": "Can you give some other example of Extending LiveData or can you tell what code should be there in StockManager? Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-20T08:28:11.260",
"Id": "224540",
"ParentId": "220223",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T09:50:32.390",
"Id": "220223",
"Score": "1",
"Tags": [
"android",
"kotlin"
],
"Title": "Android LiveData Shared between activities by Application Session"
} | 220223 |
<p>I had a technical interview the other day and failed a certain question:</p>
<blockquote>
<blockquote>
<p>Given a CSS selector (can just be a class name, id or an arbitrary
number of selectors), return the parent DOM element in an array. The caveat is that you cannot use external libraries or use
<code>document.querySelector</code> or <code>document.querySelectorAll</code>. Use
the HTML code below:</p>
</blockquote>
<pre><code><div></div>
<div id="idOne" class="classOne classTwo"></div>
<img id="IdTwo" class="classTwo classThree"></img>
</code></pre>
</blockquote>
<p>For example, if given a CSS selector of <code>img.ClassTwo</code> it would return the <code>img</code> tag, where if the given CSS selector was <code>div#idOne.classTwo</code> it would return 1 <code>div</code>, whereas if the selector was just <code>div</code>, it would return 2 <code>divs</code>. Whereas if I was given <code>img#One</code> it would return an empty array.</p>
<p>My code below works, but I feel that it is too 'cheeky' as it doesn't use either <code>document.querySelector</code> or <code>document.querySelectorAll</code> directly, but uses a variation of <code>document.querySelectorAll</code> - as I can't think of an alternative method that can cater for an arbitrary number of CSS selectors unlike how <code>document.querySelector</code> or <code>document.querySelectorAll</code> can.</p>
<p>Is my code correct? Or can it be improved anyway?</p>
<pre><code>var theFunction = function (input) {
let arr = [];
let body = document.getElementsByTagName("BODY")[0];
let selectors = body.querySelectorAll(input);
for (i = 0; i < selectors.length; ++i) {
arr.push(selectors[i].nodeName);
}
console.log(arr);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:12:33.470",
"Id": "425514",
"Score": "0",
"body": "The way I understood the question `return the parent DOM element` is that given `<div><img ...></div>` and a selector `img`, it would need to return the `<div>`, i.e. its **parent element**. But with the given example DOM it wouldn't work (or would return whatever the surrounding element actually is, e.g. `<body>`)."
}
] | [
{
"body": "<p>Your method doesn't work because it fails to select elements outside the body.</p>\n\n<p>I think what you were supposed to do is:</p>\n\n<ul>\n<li><p>split the input into class / ID / tagName (using REGEX or whatever)</p></li>\n<li><p>request elements using <code>document.getElementByID()</code> / <code>document.getElementsByClassName()</code> / <code>document.getElementsByTagName()</code> </p></li>\n<li><p>return only the elements that match all 3 requests.</p></li>\n</ul>\n\n<p>Essentially, you code your own <code>querySelectorAll</code> function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T19:33:53.737",
"Id": "425537",
"Score": "0",
"body": "Yeah, I see the logic. But wouldn't that return all CSS selectors? Not the selectors that belong to one HTML element? EG, if I was given CSS selectors of `img#idOne` that should return an empty array, but if used with your algorithm, it would return true as all CSS selectors exist in the DOM"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T14:47:42.370",
"Id": "220232",
"ParentId": "220226",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T10:34:18.793",
"Id": "220226",
"Score": "2",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Searching for selectors not using document.querySelector/document.querySelectorAll"
} | 220226 |
<p><strong>The task</strong></p>
<p>is taken from <a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Given a string, find the length of the longest substring without
repeating characters.</p>
<p><strong>Example 1:</strong></p>
<p>Input: "abcabcbb"</p>
<p>Output: 3 </p>
<p>Explanation: The answer is "abc", with the length of 3. </p>
<p><strong>Example 2:</strong></p>
<p>Input: "bbbbb"</p>
<p>Output: 1</p>
<p>Explanation: The answer is "b", with the length of 1.</p>
<p><strong>Example 3:</strong></p>
<p>Input: "pwwkew"</p>
<p>Output: 3</p>
<p>Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.</p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>var lengthOfLongestSubstring = function(s) {
const len = s.length;
if (len < 2) { return len; }
let res = [];
let tmp = [];
[...s].forEach(x => {
if (tmp.includes(x)) {
tmp = [...tmp.slice(tmp.findIndex(y => y === x ) + 1)];
}
tmp.push(x);
if (tmp.length > res.length) { res = tmp; }
});
return res.length;
};
</code></pre>
| [] | [
{
"body": "<h2>Style</h2>\n\n<ul>\n<li><p>Nice usage of arrow functions and spread operators. You can extend this to the function name as well: </p>\n\n<pre><code>const lengthOfLongestSubstring = s => { ... };\n</code></pre></li>\n<li><p>The code switches between two and four spaces within a block and between blocks. Choose one and stick with it throughout the entire program (the auto-formatter built into Stack Exchange does the job well).</p></li>\n<li><p>Avoid the intermediate variable <code>len</code> here:</p>\n\n<pre><code> const len = s.length;\n if (len < 2) { return len; }\n</code></pre>\n\n<p>The extra variable obfuscates the direct and explicit <code>s.length</code> and offers no performance benefit (as it would in C with <code>strlen</code>, which is linear). <code>s.length</code> is a numerical property and doesn't walk the list per call.</p></li>\n<li><p>Use vertical whitespace around blocks. Here's how I'd rewrite the above lines:</p>\n\n<pre><code> ...\n if (s.length < 2) { \n return s.length; \n }\n\n let res = [];\n ...\n</code></pre>\n\n<p>Then again, I prefer to omit this logic because the rest of the function body will handle the precondition automatically.</p></li>\n<li><p>Variable names can be a bit more specific: <code>tmp</code> => <code>seen</code>, <code>x</code> => <code>char</code>, <code>res</code> => <code>longest</code>.</p></li>\n</ul>\n\n<h2>Performance</h2>\n\n<p>Your solution runs in O(len(longest_subsequence) * n) time, which is in the 70th percentile of solutions for this problem. The culprits are <code>includes</code>, <code>findIndex</code>, <code>slice</code> and spread inside the <code>for</code> loop, all of which require visiting up to every element in <code>tmp</code>.</p>\n\n<p>We can improve the time complexity to linear and reach the 99th percentile. The key is using an object as a hash map instead of an array to keep track of the history. For each character in <code>s</code>, add it to the object with a value of its latest-seen index. Keep track of the start of the current candidate run. Whenever we encounter an item already in the map, check to ensure its index is indeed inside the current run. If so, record a new longest (if applicable) and begin a new candidate run.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>const lengthOfLongestSubstring = s => {\n let longest = 0;\n let start = 0;\n const seen = {};\n\n [...s].forEach((char, i) => {\n if (char in seen && start <= seen[char]) {\n longest = Math.max(i - start, longest);\n start = seen[char] + 1;\n }\n\n seen[char] = i;\n });\n\n return Math.max(s.length - start, longest);\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T05:35:56.150",
"Id": "425565",
"Score": "0",
"body": "How do you know its the 70th percentile of solutions for this problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T15:23:28.817",
"Id": "425620",
"Score": "1",
"body": "Click on the \"submissions\" tab in the challenge, then click on your \"accepted\" attempt. This takes you to a page with a bar chart and sample code at different time brackets. Sometimes, this can be taken with a grain of salt, but in this case, it's pretty revealing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T14:23:46.683",
"Id": "220231",
"ParentId": "220228",
"Score": "4"
}
},
{
"body": "<p>The answer by <a href=\"https://codereview.stackexchange.com/users/171065/ggorlen\">ggorlen</a> covers most of the points and the alternative that was presented is very efficient, well sort of. In terms of complexity it is less complex and that shows when you compare your function.</p>\n<p>If we use your algorithm and clean up some of the nasty bits, we get.</p>\n<pre><code>function longestSubstr(str) {\n var res = 0, tmp = [];\n for (const char of str){\n const idx = tmp.indexOf(char);\n if (idx > -1) { tmp = tmp.slice(idx + 1) }\n tmp.push(char); \n if (tmp.length > res) { res = tmp.length }\n }\n return res;\n}\n</code></pre>\n<p>Which makes it competitive up to about 160-180 characters, at which point using a hashing function beats the cost of stepping over each character.</p>\n<p>If you consider a string 1Mb long your function does not stand a chance.</p>\n<h2>Beating the hashing function.</h2>\n<p>All the benefit of maps and sets come from the hash function. It takes an object (in this case a character) and turns it into a unique index that gives you the memory address of the data you are after.</p>\n<p>In JavaScript the hash function must work for any type of data, not just strings and it is impressive at how well it does, but in this case, with 2 caveats, there is an even faster way.</p>\n<h3>The caveats:</h3>\n<ul>\n<li><p>The string must be a ACSII string (8bits)</p>\n</li>\n<li><p>We can hold some reserved memory to avoid allocation overhead.</p>\n</li>\n</ul>\n<p>It takes 256 array items to hold all the ASCII characters and we can create a unique hash directly from the ASCII character code.</p>\n<p>The resulting function has the same complexity but by avoiding the JS hash calculation we get an order of magnitude better performance.</p>\n<p>The following runs 10times faster than the existing answer. The algorithm (some slight mods) is <a href=\"https://codereview.stackexchange.com/users/171065/ggorlen\">ggorlen</a>'s so the credit is belongs to him</p>\n<pre><code>const longestASCIISubStr = (() => {\n const charLookup = new Uint32Array(256);\n return function (str) {\n var max = 0, start = 0, i = 0, char;\n charLookup.fill(0);\n const len = str.length;\n while (i < len) { \n const pos = charLookup[char = str.charCodeAt(i)];\n if (pos && start < pos) {\n max < i - start && (max = i - start);\n if (max > len - pos && i + max >= len) { return max }\n start = pos;\n }\n charLookup[char] = ++i;\n }\n return Math.max(len - start, max);\n } \n})();\n</code></pre>\n<p>I do not know the conditions of leetcode runtime environment so it may not work as allocating the lookup array is costly and will bring the average down for short strings.</p>\n<p>The following does not require the reserved memory and is only about 5 times as fast for long string and equal at about 30 character strings but may be accepted as valid.</p>\n<pre><code>function longestASCIISubStr(str) {\n var max = 0, start = 0, i = 0, char;\n const charLookup = new Uint32Array(256);\n const len = str.length;\n while (i < len) { \n const pos = charLookup[char = str.charCodeAt(i)];\n if (pos && start < pos) {\n max < i - start && (max = i - start);\n if (max > len - pos && i + max >= len) { return max }\n start = pos;\n }\n charLookup[char] = ++i;\n }\n return Math.max(len - start, max);\n} \n</code></pre>\n<p>The problem with the less complex solution is that it comes with considerable overhead. The hashing function is complex compared to searching a dozen characters.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T02:44:42.047",
"Id": "425562",
"Score": "0",
"body": "Thanks. I appreciate your answer and explanation for this - and also any other - question of mine. Even though your answer is the most compete and elaborate answer so far, I’d like to accept a different one as the best answer, in order to also give others a chance to earn points"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:08:16.543",
"Id": "220257",
"ParentId": "220228",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220231",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T11:39:17.597",
"Id": "220228",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"ecmascript-6"
],
"Title": "Longest Substring Without Repeating Characters in JS"
} | 220228 |
<p>Actually I got a form with multiple input (around 39) on which I wish to perform some check and display customs messages based on sets of conditions.</p>
<p>I found a way to address my problem but I'm wondering (and I'm barely sure there is) if there's any better way to approach this.</p>
<p>My trouble come from the fact there's a lot of custom field I need to address to (many input to check with custom error displayer per input and sometimes more than custom message to send / display) plus quite lot of check to perform.</p>
<pre><code>function hideShowError(elem, sub) {
sub = sub || false;
parentElem = getBoxParent($(elem), sub);
if (parentElem != false)
parentElem.addClass('errorWrapper');
return false;
}
function hideShowErrorWithMessage(elem, message, special, sub, noBorder) {
sub = sub || false;
special = special || false;
noBorder = noBorder || false;
parentElem = getBoxParent($(elem), sub);
if (parentElem != false) {
parentElem.addClass('errorWrapper');
if (noBorder)
parentElem.addClass('errorWrapper-no-border');
parentElem.find('.errorSpe').text(message);
special ? parentElem.find('.disable-error').addClass("active") : parentElem.find('.disable-error-pb').removeClass("active");
}
return false;
}
function getBoxParent(childElem, sub) {
childElem = childElem || "";
sub = sub || false;
if (childElem != "") {
if (!sub)
return childElem.closest('.questBox3');
return childElem.closest('.subQuestBox3');
}
return false;
}
function testInput() {
var input1 = $('input1-t').is(':checked') || $('input1-f').is(':checked');
var input2 = $('input2-f').is(':checked');
var input3 = !$('input3-t').is(':checked') && !$('input2-f').is(':checked');
var input4 = $('input4-f').is(':checked');
var input5 = !$('input5-t').is(':checked') && !$('input4-f').is(':checked');
var input6 = $('input6-f').is(':checked');
var input7 = !$('input7-t').is(':checked') && !$('input6-f').is(':checked');
var input8 = $('input8-f').is(':checked');
var input9 = !$('input9-t').is(':checked') && !$('input8-f').is(':checked');
var input10 = $('input10-t').is(':checked');
var input11 = !$('input11-f').is(':checked') && !$('input10-t').is(':checked');
var input12 = $('input12-t').is(':checked') || $('input12-f').is(':checked');
var input13 = $('input13-t').is(':checked') || $('input13-f').is(':checked');
var input14 = $('input14-t').is(':checked') || $('input14-f').is(':checked');
var input15 = $('input15-f').is(':checked');
var input16 = $('input16select option:selected').length > 0 && $('input16select option:selected').val() != 0;
var input17 = $('input17select option:selected').length > 0 && $('input17select option:selected').val() != 0;
var input18 = $('input18').val().length > 0;
var input19 = $('input19').val().length > 0;
var input20 = $('input20').val().length > 0;
var input21 = $('input21').val().length > 0;
var input22 = $('input22').val().length > 0;
var input23 = $('input23').val().length > 0;
var input24 = $('input24').val().length > 0;
var input25 = $('input25-t').is(':checked') || $('input25-f').is(':checked');
var input26 = $('input26-t').is(':checked') || $('input26-f').is(':checked');
var input27 = $('input27-t').is(':checked') || $('input27-f').is(':checked');
var input28 = $('input28').val().length > 0 || $('input28-2').val().length > 0 || $('input28-3').val().length > 0;
var input29 = $('input29-t').is(':checked') || $('input30-f').is(':checked');
var input30 = $('input30-f').is(':checked');
var input31 = $('input31-t').is(':checked') || $('input32-f').is(':checked');
var input32 = $('input32-f').is(':checked');
var input33 = $('input33').val().length > 0;
var input34 = $('input33').val() != "" && (!$.isNumeric($('input33').val()) || ($('input33').val() > 99 || $('input33').val() < 0));
// checkbox input
var input35 = $('input35:checked').length;
var input36 = $('input36:checked').length;
// siret control
var numSiret = ($('input28').val().toString()).replace(/\s+/g, '');
var validSiret = ("" == numSiret || (verif_siren_siret(numSiret, 9) && verif_siren_siret(numSiret, 14)))
// Get CP (97, 971, 972 ...)
var departement = '<%= @adresse.try(:departement) %>'.match("^97");
// Error check Question 1 (input)
if (!input1)
ret = hideShowError('input1-t');
// Error check Question 9 (input)
if (input2 && !input3)
ret = hideShowErrorWithMessage('input2-f', "<%= t('sometrad1') %>", false, false, true);
// Error check Question 10 (input)
if (input4 && !input5)
ret = hideShowErrorWithMessage('input4-f', "<%= t('sometrad1') %>", false, false, true);
// Error check Question 11 (input)
if (input6 && !input7)
ret = hideShowErrorWithMessage('input6-f', "<%= t('sometrad1') %>", false, false, true);
// Error check Question 12 (input)
if (input8 && !input9)
ret = hideShowErrorWithMessage('input8-f', "<%= t('sometrad1') %>", false, false, true);
// Error check Question 13 (input)
if (input10 && !input11)
ret = hideShowErrorWithMessage('input10-t', "<%= t('sometrad1') %>", false, false, true);
if (!input2 && input3)
ret = hideShowErrorWithMessage('input2-f', "<%= t('sometrad2') %>", false);
if (!input4 && input5)
ret = hideShowErrorWithMessage('input4-f', "<%= t('sometrad2') %>", false);
if (!input6 && input7)
ret = hideShowErrorWithMessage('input6-f', "<%= t('sometrad2') %>", false);
if (!input8 && input9)
ret = hideShowErrorWithMessage('input8-f', "<%= t('sometrad2') %>", false);
if (!input10 && input11)
ret = hideShowErrorWithMessage('input10-t', "<%= t('sometrad2') %>", false);
if (!input12)
ret = hideShowError('input12-t');
if ($('input12-t').is(':checked') && !input13)
ret = hideShowErrorWithMessage('input13-t', "<%= t('sometrad2') %>", false, true);
if (!input14)
ret = hideShowErrorWithMessage('input14-t', "<%= t('sometrad2') %>", false, true);
if (input15)
ret = hideShowErrorWithMessage('input13-t', "<%= t('sometrad3') %>", false, true);
if (!input16)
ret = hideShowError('input16select');
if (!input17)
ret = hideShowError('input17select');
if (!input18)
ret = hideShowError('input18');
if (!input19)
ret = hideShowError('input19');
if (!input25)
ret = hideShowError('input25-t');
if ($('input25-t').is(':checked') && !input20)
ret = hideShowError('input20');
if ($('input25-t').is(':checked') && !input21)
ret = hideShowError('input21');
if ($('input25-t').is(':checked') && !input22)
ret = hideShowError('input22');
if ($('input25-t').is(':checked') && !input23)
ret = hideShowError('input23');
if ($('input25-t').is(':checked') && !input24 && null != departement)
ret = hideShowError('input24');
if (!input26)
ret = hideShowError('input26-t');
if (input26 && !input27)
ret = hideShowErrorWithMessage('input27-t', "<%= t('sometrad2') %>", false);
if ($('input27-t').is(':checked') && !input28) {
ret = hideShowErrorWithMessage('input28', "<%= t('sometrad4') %>", false);
ret = hideShowErrorWithMessage('input28-2', "<%= t('sometrad4') %>", false);
ret = hideShowErrorWithMessage('input28-3', "<%= t('sometrad4') %>", false);
}
if ($('input27-t').is(':checked') && $('input28').val().length > 0 && !validSiret)
ret = hideShowErrorWithMessage('input28', "<%= t('sometrad5') %>", false);
// Error check Question 13 (checkbox)
if (input35 > 0)
ret = hideShowErrorWithMessage('#pb-decence-1', "<%= t('sometrad2') %>", false, false, true);
if (input35 == 0 && input36 == 0)
ret = hideShowErrorWithMessage('#pb-decence-1', "<%= t('sometrad2') %>", false);
if (!input29)
ret = hideShowErrorWithMessage('input29-t', "<%= t('sometrad2') %>", false);
if (input30)
ret = hideShowErrorWithMessage('input29-t', "<%= t('sometrad6') %>", false);
if (!input31)
ret = hideShowErrorWithMessage('input31-t', "<%= t('sometrad2') %>", false);
if (input32)
ret = hideShowErrorWithMessage('input31-t', "<%= t('sometrad7') %>", false, false, true);
if (!input33)
ret = hideShowErrorWithMessage('input33', "<%= t('sometrad8') %>", false);
if (input34)
ret = hideShowErrorWithMessage('input33', "<%= t('sometrad2') %>", false);
}
</code></pre>
<p>I also add an HTML (slim) block of code, though all input are not the sames the general structure is mostly the same</p>
<pre><code>div.questGridWrapper
div.questBox
span= t('quest_9')
div.questBox
span.special-info
span= t('quest_error_warn.warn_0') + " "
<i class="fa fa-question-circle"></i>
div.no-display-info
br
span= t('quest_9_prec.sub_1')
br
br
ul
li.li-style
span= t('input.sub_2')
span.color OR
li.li-style
span= t('input.sub_3')
div.questGridWrapper
div.questBox3
div.form-group.radio_buttons
div.form-check-hacked
span.radio
label for="input-t"
- if @pb_projet_courant.pb_logement.espace_suffisant == true
input.form-check-input.radio_buttons type="radio" name="input[value]" checked="checked" id="input-t" value="true"
= t('generic.quest_yes')
- else
input.form-check-input.radio_buttons type="radio" name="input[value]" id="input-t" value="true"
= t('generic.quest_yes')
span.radio
label for="input-f"
- if @pb_projet_courant.pb_logement.espace_suffisant == false
input.form-check-input.radio_buttons type="radio" name="input[value]" checked="checked" id="input-f" value="false"
= t('generic.quest_no')
- else
input.form-check-input.radio_buttons type="radio" name="input[value]" id="input-f" value="false"
= t('generic.quest_no')
.error-message
span.errorSpe.errorSpe-noBorder= t('someDefaultTrad')
</code></pre>
<p>(I had to anonymize the code before posting, so sadly getting a working exemple may take some times but the code itself actually work, I'm looking for way to improve my if statements if there's any regarding the numbers of conditions that are checked.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:19:54.997",
"Id": "425515",
"Score": "0",
"body": "Welcome to code review, where we review working code. We understand the need to anonymize code, but if it's not working it is off-topic and we can't review it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:28:57.997",
"Id": "425516",
"Score": "0",
"body": "Thx, the code itself is working, it just need quite lot of context (mostly HTML) to be fully working, my main concern is about the whole testInput() function, and how to best optimise the whole \"if\" part"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T21:25:14.297",
"Id": "425547",
"Score": "1",
"body": "Even if you [anonymize the code](https://codereview.meta.stackexchange.com/q/7249/9357), it still needs to be realistic enough so that we can understand what is going on, so that we can give you proper advice. This code is, in my opinion, too obfuscated to review. For example, why is the `if (input15)` check not negated like the others, and why does it trigger an error message for `input13-t`? Voting to close for lack of context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:16:16.747",
"Id": "425585",
"Score": "0",
"body": "Thx for your return I get your point, in your exemple input15 is not negated like other 'cause it's a simple check , input15 condition is only one check (if the radio button is ticked on false) and that's the only condition to trigger the error, for the error message it's triggered in input13-t 'cause it's the parent element in my HTML, but yep I get your point. My asking is more about how to optimise the whole \"var =\" and \"if\" statement part, I didn't though the whole HTML was needed for this, still I can provide more code but it gonna take some time as there's quite lot of HTML"
}
] | [
{
"body": "<p>There's A LOT or repeated code. Start by DRYing your code, for example:</p>\n\n<p>All this lines are too similar:</p>\n\n<pre><code>var input3 = !$('input3-t').is(':checked') && !$('input2-f').is(':checked');\nvar input5 = !$('input5-t').is(':checked') && !$('input4-f').is(':checked');\nvar input7 = !$('input7-t').is(':checked') && !$('input6-f').is(':checked');\nvar input9 = !$('input9-t').is(':checked') && !$('input8-f').is(':checked');\n</code></pre>\n\n<p>you could have a function:</p>\n\n<pre><code>function is_not_checked(inputNum) {\n return !$('input'+inputNum+'-t').is(':checked') && !$('input'+(inputNum-1)+'-f').is(':checked');\n}\n</code></pre>\n\n<p>Now you can do</p>\n\n<pre><code>var input3 = is_not_checked(3);\nvar input5 = is_not_checked(5);\nvar input7 = is_not_checked(7);\nvar input9 = is_not_checked(9);\n</code></pre>\n\n<p>And you don't even need to set the variable, it's consice enough to use as the if condition:</p>\n\n<pre><code>if (is_checked(2) && is_not_checked(3)) //you could have that `is_checked` function too\n ret = hideShowErrorWithMessage('input2-f', \"<%= t('sometrad1') %>\", false, false, true);\n</code></pre>\n\n<p>You can also move that <code>ret = hideShow.....</code> line to another function so you don't have to repeat that same call to the <code>hideShow...</code> function.</p>\n\n<p>Use the same idea on the other <code>inputX</code> assignments and the if conditions. When you finish removing all the repeated code you'll end up with a cleaner code that will be easier to analyze to simplify the logic (maybe after refactoring you find even more repeated patterns).</p>\n\n<p>EDIT:</p>\n\n<p>You are also doing <code>ret = ....</code> every time and you don't use ret anywhere after that, remove all those assignements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:17:21.677",
"Id": "425586",
"Score": "0",
"body": "Thanks for your answer, yep the ret is an artifact I forgot my bad, I was using it to get to know in other functions if there was an error but indeed it's not used anymore.\n\nI get the point of using a function and quite like the idea, one question though I was using \"variable\" storage to get only one call as some input are used multiple times isn't it more optimum to store the \"check\" instead of calling it each time in a ressource perspective ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T12:19:04.510",
"Id": "425601",
"Score": "0",
"body": "You could save the returned value if you need to use it multiple times, sure. Just follow the DRY principle."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T23:28:58.557",
"Id": "220262",
"ParentId": "220233",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220262",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T14:55:36.247",
"Id": "220233",
"Score": "0",
"Tags": [
"jquery",
"ruby-on-rails",
"slim"
],
"Title": "Is there any better / improved / optimise way to approach these input checker?"
} | 220233 |
<p>I'm attempting to create a basic wiki for personal use. I've got a pretty good start, but the code is beginning to become cumbersome to modify, and some of the things I'm doing feel very fragile. I've heard and looked into using the MVC pattern, but I'm having trouble understanding how I would even implement my current project using that pattern. If at all I'd like to avoid suggestions such as "use a framework," as my goal is to learn how to do things by hand.</p>
<p>Highlights include:</p>
<ul>
<li>Trying to cut down on edit.php. There's two forms that are pretty much exactly the same, but call slightly different database queries.</li>
<li>Making sure my routing is solid with the <code>/wiki.php?title=article-name</code> format (although I'd love to figure out how to properly implement a front controller).</li>
<li>I'm pretty sure I don't have any error-checking going on like I should.</li>
</ul>
<p><strong><code>index.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code><?php
session_start();
require_once "database.php";
/**
* TODO: Basic user authentication.
* TODO: Categories for articles.
* TODO: Articles broken down into sections that can be edited independently?
* TODO: Make links to articles that don't exist a different color?
*/
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Webdev</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<?php if (isset($_SESSION["message"])): ?>
<p><?= htmlspecialchars($_SESSION["message"]); ?></p>
<?php endif; ?>
<?php unset($_SESSION["message"]); ?>
<div><a href="/edit.php">[Create Article]</a> <a href="/documentation.php">[Documentation]</a></div>
<?php
$stmt = $pdo->query("SELECT title, slug FROM articles");
$articles = $stmt->fetchAll();
?>
<?php if ($articles): ?>
<ul>
<?php foreach ($articles as $article): ?>
<li><a href="/wiki.php?title=<?= $article["slug"]; ?>"><?= htmlspecialchars($article["title"]); ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<script src="main.js"></script>
</body>
</html>
</code></pre>
<p><strong><code>wiki.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code><?php
session_start();
require_once "vendor/autoload.php";
require_once "database.php";
function slugify($str) {
$str = strtolower($str);
$str = trim($str);
$str = preg_replace("/[^A-Za-z0-9 -]/", "", $str);
$str = preg_replace("/\s+/", " ", $str);
$str = str_replace(" ", "-", $str);
return $str;
}
$ParsedownExtra = new ParsedownExtra();
$ParsedownExtra->setSafeMode(true);
$title = htmlspecialchars($_GET["title"]);
$slug = "";
if ($title !== slugify($title)) {
$slug = slugify($title);
} else {
$slug = $title;
}
$stmt = $pdo->prepare("SELECT id, title, slug, body FROM articles WHERE slug = ?");
$stmt->execute([$slug]);
$article = $stmt->fetch();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Webdev | Wiki - <?= $article["title"] ?? "Article"; ?></title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<?php if (isset($_SESSION["message"])): ?>
<p><?= htmlspecialchars($_SESSION["message"]); ?></p>
<?php endif; ?>
<?php unset($_SESSION["message"]); ?>
<?php if ($article): ?>
<div><a href="/">[Home]</a> <a href="/edit.php?title=<?= $article["slug"]; ?>">[Edit Article]</a> <a href="/documentation.php">[Documentation]</a></div>
<?= $ParsedownExtra->text($article["body"]); ?>
<?php else: ?>
<div><a href="/">[Home]</a></div>
<p>Unknown article ID. <a href="/edit.php?title=<?= $title; ?>">[Create Article]</a></p>
<?php endif; ?>
<script src="main.js"></script>
</body>
</html>
</code></pre>
<p><strong><code>edit.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code><?php
session_start();
require_once "database.php";
function slugify($str) {
$str = strtolower($str);
$str = trim($str);
$str = preg_replace("/[^A-Za-z0-9 -]/", "", $str);
$str = preg_replace("/\s+/", " ", $str);
$str = str_replace(" ", "-", $str);
return $str;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Webdev | Edit</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<?php if (!empty($_SESSION["message"])): ?>
<p><?= htmlspecialchars($_SESSION["message"]); ?></p>
<?php endif; ?>
<?php unset($_SESSION["message"]); ?>
<div><a href="/">[Home]</a> <a href="/documentation.php">[Documentation]</a></div>
<?php
$errors = [];
$title = htmlspecialchars($_GET["title"] ?? "");
$slug = "";
if ($title !== slugify($title)) {
$slug = slugify($title);
} else {
$slug = $title;
}
$stmt = $pdo->prepare("SELECT id, title, slug, body FROM articles WHERE slug = ?");
$stmt->execute([$slug]);
$article = $stmt->fetch();
?>
<?php if ($article): ?>
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!empty($_POST["edit-article"])) {
$title = $_POST["title"];
$body = $_POST["body"];
$slug = slugify($title);
if (empty(trim($title))) {
$errors[] = "No title. Please enter a title.";
} elseif (strlen($title) > 32) {
$errors[] = "Title too long. Please enter a title less than or equal to 32 characters.";
} elseif (slugify($title) !== $article["slug"]) {
$errors[] = "Title may only change in capitalization or by having additional symbols added.";
}
if (strlen($body) > 10000) {
$errors[] = "Body too long. Please enter a body less than or equal to 10,000 characters.";
}
if (empty($errors)) {
$stmt = $pdo->prepare("UPDATE articles SET title = ?, body = ? WHERE id = ?");
$stmt->execute([$title, $body, $article["id"]]);
$_SESSION["message"] = "Article successfully updated.";
header("Location: /wiki.php?title=" . $article["slug"]);
exit();
}
}
}
?>
<?php if (!empty($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form action="/edit.php?title=<?= $article["title"]; ?>" method="post" name="form-edit-article">
<div><label for="title">Title</label></div>
<div><input type="text" name="title" id="title" size="40" value="<?= htmlspecialchars($article["title"]); ?>" required></div>
<div><label for="body">Body</label></div>
<div><textarea name="body" id="body" rows="30" cols="120" maxlength="10000"><?= htmlspecialchars($article["body"]); ?></textarea></div>
<div><span id="character-counter"></span></div>
<div><input type="submit" name="edit-article" value="Edit Article"></div>
</form>
<?php else: ?>
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!empty($_POST["create-article"])) {
$title = $_POST["title"];
$body = $_POST["body"];
$slug = slugify($title);
if (empty(trim($title))) {
$errors[] = "No title. Please enter a title.";
} elseif (strlen($title) > 32) {
$errors[] = "Title too long. Please enter a title less than or equal to 32 characters.";
}
$stmt = $pdo->prepare("SELECT title, slug FROM articles WHERE title = ? OR slug = ?");
$stmt->execute([$title, $slug]);
$article_exists = $stmt->fetch();
if ($article_exists) {
$errors[] = "An article by that title already exists. Please choose a different title.";
}
if (strlen($body) > 10000) {
$errors[] = "Body too long. Please enter a body less than or equal to 10,000 characters.";
}
if (empty($errors)) {
$stmt = $pdo->prepare("INSERT INTO articles (title, slug, body) VALUES (?, ?, ?)");
$stmt->execute([$title, $slug, $body]);
$_SESSION["message"] = "Article successfully created.";
header("Location: /wiki.php?title=" . $slug);
exit();
}
}
}
?>
<?php if (!empty($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form action="/edit.php" method="post" name="create-article-form">
<div><label for="title">Title</label></div>
<div><input type="text" name="title" id="title" size="40" value="<?= htmlspecialchars($title); ?>" required></div>
<div><label for="body">Body</label></div>
<div><textarea name="body" id="body" rows="30" cols="120" maxlength="10000"><?= htmlspecialchars($_POST["body"] ?? ""); ?></textarea></div>
<div><span id="character-counter"></span></div>
<div><input type="submit" name="create-article" value="Create Article"></div>
</form>
<?php endif; ?>
<script src="main.js"></script>
</body>
</html>
</code></pre>
<p><strong><code>database.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code><?php
try {
// TODO: Move database to a directory above the root directory.
$pdo = new PDO("sqlite:wiki.db");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY,
title TEXT,
slug TEXT,
body TEXT
)");
$pdo->exec("CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY,
name TEXT
)");
} catch (PDOException $e) {
$error_message = date("Y-m-d G:i:s") . " ERROR: " . $e->getMessage() . "\n";
file_put_contents("pdoerrors.txt", $error_message, FILE_APPEND);
$pdo = null;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:50:04.390",
"Id": "425519",
"Score": "1",
"body": "I am sure you can figure out how to deduplicate edit.php. To decide which database query to run you need just a single if statement, don't you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:52:02.393",
"Id": "425553",
"Score": "1",
"body": "@Robert Why do you have `A-Z` in your negated character class if you have already called `strtolower()` on the input string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T14:08:48.127",
"Id": "425615",
"Score": "0",
"body": "@mickmackusa Didn't even think about that, haha. Thanks for pointing that out!"
}
] | [
{
"body": "<p>I would say your code is pretty good for a beginner. </p>\n\n<p>Of course in time it could grow up, along with your own experience but for the current level it is mostly ok.<br>\nThere are mostly minor improvements</p>\n\n<p><strong>bootstrap.php</strong></p>\n\n<p>You may notice that a certain block of code is repeated in every file. Once you see a repetition it's signal for refactoring. Here it's simple one - just put this code in a distinct file and then include it in every other file</p>\n\n<pre><code><?php\nsession_start();\nrequire_once \"vendor/autoload.php\";\nrequire_once \"database.php\";\n\nfunction slugify($str) {\n $str = strtolower($str);\n $str = trim($str);\n $str = preg_replace(\"/[^A-Za-z0-9 -]/\", \"\", $str);\n $str = preg_replace(\"/\\s+/\", \" \", $str);\n $str = str_replace(\" \", \"-\", $str);\n\n return $str;\n}\n</code></pre>\n\n<p>But it is very important not to add any HTML in this file. HTML is a completely different thing, some of your files aren't supposed to display anything, so HTML is never a part of a bootstrap file.</p>\n\n<p><strong>template/design.php</strong></p>\n\n<p>However, it is still a very good idea to put the site design into a distinct file, to again avoid duplication. Imagine you will decide to add some rich design - then you will have to edit every file. It won't do. What I would propose is to implement a very simple template system. Let's create a folder called <code>template</code> and put there all files responsible for showing HTML to the user. the first one would be <code>design.php</code> to hold the global design of your site, that you would include in your scripts.</p>\n\n<pre><code><!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Webdev | Wiki - <?= $title ?></title>\n <link href=\"style.css\" rel=\"stylesheet\">\n</head>\n<body>\n<?php if($message): ?>\n <p><?= htmlspecialchars($message) ?></p>\n<?php endif; ?>\n\n<?php include __DIR__.\"/\".$template ?>\n\n<script src=\"main.js\"></script>\n\n</body>\n</html>\n</code></pre>\n\n<p>as you can see, it contains two variables that must be defined before including this file.</p>\n\n<p><strong>index.php</strong></p>\n\n<p>Now let's refactor your index.php splitting it into two files, <em>the business logic</em> part and <em>the presentation logic</em> part</p>\n\n<pre><code><?php\ninclude 'bootstrap.php';\n\n$message = $_SESSION[\"message\"] ?? '';\nunset($_SESSION[\"message\"])\n\n$articles = $pdo->query(\"SELECT title, slug FROM articles\")->fetchAll();\n\n$title = \"Articles\";\n$template = \"index.php\";\ninclude 'template/design.php';\n</code></pre>\n\n<p>here we are preparing all the necessary data, so we won't litter the template with the business logic.</p>\n\n<p><strong>template/index.php</strong></p>\n\n<p>here we have all the output required for the index page</p>\n\n<pre><code> <div>\n <a href=\"/edit.php\">[Create Article]</a> \n <a href=\"/documentation.php\">[Documentation]</a>\n </div>\n<?php if ($articles): ?>\n <ul>\n <?php foreach ($articles as $article): ?>\n <li><a href=\"/wiki.php?title=<?= $article[\"slug\"]; ?>\">\n <?= htmlspecialchars($article[\"title\"]); ?>\n </a>\n </li>\n <?php endforeach; ?>\n </ul>\n<?php endif; ?>\n</code></pre>\n\n<p>as you can see, both files became much more tidy.</p>\n\n<p>So you can refactor all other files the same way.</p>\n\n<p><strong>wiki.php</strong></p>\n\n<pre><code><?php\ninclude 'bootstrap.php';\n\n$ParsedownExtra = new ParsedownExtra();\n$ParsedownExtra->setSafeMode(true);\n$title = htmlspecialchars($_GET[\"title\"]);\n\nif ($title !== slugify($title)) {\n $slug = slugify($title);\n} else {\n $slug = $title;\n}\n$stmt = $pdo->prepare(\"SELECT id, title, slug, body FROM articles WHERE slug = ?\");\n$stmt->execute([$slug]);\n$article = $stmt->fetch();\n\n$title = $article[\"title\"];\n$template = \"wiki.php\";\ninclude 'template/design.php';\n</code></pre>\n\n<p><strong>template/wiki.php</strong></p>\n\n<pre><code><?php if ($article): ?>\n <div>\n <a href=\"/\">[Home]</a> \n <a href=\"/edit.php?title=<?= $article[\"slug\"]; ?>\">[Edit Article]</a>\n <a href=\"/documentation.php\">[Documentation]</a>\n </div>\n <?= $ParsedownExtra->text($article[\"body\"]); ?>\n<?php else: ?>\n <div><a href=\"/\">[Home]</a></div>\n <p>Unknown article ID. \n <a href=\"/edit.php?title=<?= $title; ?>\">[Create Article]</a>\n </p>\n<?php endif; ?>\n</code></pre>\n\n<p>again, as you can see, separating the pure PHP from HTML mixed with PHP for the output makes both files much cleaner. </p>\n\n<p>Sorry for not covering your edit.php, it's a distinct review of it's own and I have my own work to do. I am sure someone else will show you this. Or you can try it yourself and then post as another question for the review.</p>\n\n<p>One last part. </p>\n\n<p><strong>database.php</strong></p>\n\n<p>You did it almost right, it just makes no sense to have a distinct error log for PDO connection errors. All errors should go into a single error log and it's none of database.php's business to decide which one. Just make PDO throw the error the safe way (as not to reveal the database credentials), as it shown in my article on <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"nofollow noreferrer\">how to properly connect with PDO</a>:</p>\n\n<pre><code>$options = [\n \\PDO::ATTR_ERRMODE => \\PDO::ERRMODE_EXCEPTION,\n \\PDO::ATTR_DEFAULT_FETCH_MODE => \\PDO::FETCH_ASSOC,\n \\PDO::ATTR_EMULATE_PREPARES => false,\n];\ntry {\n // TODO: Move database to a directory above the root directory.\n $pdo = new PDO(\"sqlite:wiki.db\", null, null, $options);\n} catch (\\PDOException $e) {\n throw new \\PDOException($e->getMessage(), (int)$e->getCode());\n}\n\n$pdo->exec(\"CREATE TABLE IF NOT EXISTS articles (...\n</code></pre>\n\n<p>and that's all you need to do regarding error reporting in this file. The rest should be configured elsewhere, as it's explained in detail in my article on <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T13:29:16.563",
"Id": "425609",
"Score": "0",
"body": "Thank you so much for this write-up; it's been very enlightening! A few questions:\n\nWould it make sense to also include the `$message` handling in `bootstrap.php` as well? I use it across multiple pages, and it looks like a case of repeating code.\n\nThe part of setting the article title, template, and rendering the base layout seems like another instance where I could reduce it to, say, a function. Would this be a good route?\n\nIn `database.php`, is there any significance to doing `throw new \\PDOException...` vs. `throw new PDOException`? I'm confused as to what the back-slash is for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T13:43:10.193",
"Id": "425612",
"Score": "1",
"body": "Good questions. Not sure about $massage. It is a little bit specific. At least name it less generic. Regarding thetemplate, better already look towards Twig. And a backslash is a namespace issue. You will learn it in time, but with \\ it's just universal, works both with or without namespaces and without a baskslash it would fail with namespaces, so we have it just in case"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T13:59:32.933",
"Id": "425614",
"Score": "0",
"body": "Ah, gotcha on the namespace thing. $message (and in turn, $_SESSION[\"message\"]) is what I believe is called a flash message. It's used to let users know when something succeeds after a POST request."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:43:54.200",
"Id": "220272",
"ParentId": "220235",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220272",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T15:09:13.740",
"Id": "220235",
"Score": "1",
"Tags": [
"performance",
"php",
"mvc"
],
"Title": "Simple wiki with PHP"
} | 220235 |
<p>I am building a CLI that wraps an API for work. The CLI is being build to handle the "common" tasks users can perform with the API so that they don't need to get into the details. If they want to do more, they are able to but have to use the API. </p>
<p>The problem I'm running into is that it seems very inefficient to pluck out only the fields I want from the API and list them individually. I have two types of results in the CLI. </p>
<p>Result 1 is a detailed view of a single item. <code>port</code> contains a JSON object that was returned by the API. The fields I have listed, as the only ones I care about. The JSON object is much larger than these few fields. </p>
<pre><code>port_details = [
["Interface ID", port["port_id"]],
["Description", port["description"]],
["Market", port["location"]["market"]["market_code"]],
["Site", port["location"]["site"]["site_name"]],
["Time Created", port["created"]],
["Time Updated", port["updated"]],
["Device Name", port["device_data"]["device_name"]],
["Interface Speed", port["device_data"]["speed"]],
["Status", port["state"]],
]
headers = ["", "Value"]
port_table = show_table(
ctx,
port_details,
column_headers=headers,
max_width=250,
)
click.echo(port_table)
</code></pre>
<p>This results in a table that looks like this:</p>
<pre><code> Value
------------------ ------------------------------------------
Interface ID IF-LAB1-7785421
Description Test Port LAB1
Market LAB1
Site LAB1a
Time Created 2019-05-14T11:10:09-05:00
Time Updated 2019-05-14T11:10:16-05:00
Device Name lab1.sw1
Interface Speed 1G
Status Active
</code></pre>
<p>The second result is a table of items. You'd use this view to see an overview and then you can drill down for details on a specific item using the above.</p>
<pre><code>circuit_details = [
[
circuit["circuit_id"],
circuit["description"],
circuit["vlan_id"],
circuit["status"],
circuit["attr"]["limit_in"]
circuit["attr"]["limit_out"]
]
for circuit in circuits
]
circuit_headers = [
"Circuit ID",
"Description",
"VLAN",
"Status",
"Rate Limit In",
"Rate Limit Out",
]
circuit_table = show_table(
ctx,
circuit_details,
column_headers=circuit_headers,
max_width=250,
)
click.echo(circuit_table)
</code></pre>
<p>This results in a table like this:</p>
<pre><code> Circuit ID Description VLAN Status Rate Limit In Rate Limit Out
----------------------- -------------------- ------ -------- --------------- ----------------
CIRCUIT-LAB1-LAB2-842 Test Circuit 1 5 active 1000 1000
CIRCUIT-LAB1-LAB2-846 Test Circuit 2 6 active 250 250
</code></pre>
<p>Both of these are using a call to <code>show_tables</code> which uses the Python <a href="https://pypi.org/project/beautifultable/" rel="nofollow noreferrer">BeautifulTable</a> package:</p>
<pre><code>def show_table(
ctx,
data,
column_headers=[],
good_values=[],
bad_values=[],
sort_column=None,
max_width=200,
alignments={},
):
"""
Create a table of data with optional headers, style, and highlighted values
The table will utilize the default printing style and will highlight all
values in the table that are in `good_values` as the color GREEN and all
values in the table that are in `bad_values` as the color RED.
Parameters
----------
ctx: context object, required
The click context object (holds the table style)
data: list of lists, required
Each sublist must contain the values for a single row in the table
column_headers: list, optional
A list of the table headers
max_width: integer, optional
Set the width of the table. Defaults to 200 characters
"""
table = BeautifulTable(max_width=max_width)
if column_headers:
table.column_headers = column_headers
table.set_style(TableStyle[ctx.obj["PRINT_TABLE"]].value)
for row in data:
for idx, val in enumerate(row):
if str(val).lower() in good_values:
row[idx] = click.style(str(val), fg="green")
if str(val).lower() in bad_values:
row[idx] = click.style(str(val), fg="red")
table.append_row(row)
if sort_column:
table.sort(sort_column)
for column, align in alignments.items():
table.column_alignments[column] = ColumnAlignment[align].value
return table
</code></pre>
<hr>
<p>I am looking for ways to improve the listing of table rows (the <code>*_details</code> variables that are lists of lists). I have some subcommands that list 20-30 JSON data points. My code seems like massive lists - one for the data and one for the column headers - and then a call to <code>show_tables</code>.</p>
<p>Is there a better way to do this and eliminate these massive lists?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T01:32:43.937",
"Id": "429433",
"Score": "0",
"body": "Do you have code that makes these detail lists? If so you should provide the code, otherwise it's impossible to accurately improve code we don't have access to. You've also tagged this performance, what is most important to you improving the detail lists or improving the performance of `show_table`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T02:35:51.653",
"Id": "429524",
"Score": "0",
"body": "@Peilonrayz No, I do not have a dedicated function to create these lists. Since each API call returns a different set of fields, I've manually built these lists for my CLI. So, either I have the lists here, or I image I supply a list to a function that says \"take these fields from an API response\" - which isn't a horrible idea - I still have these large lists. I am not unhappy with the performance of `show_table`. I am unhappy with the lists themselves."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T16:03:45.463",
"Id": "220239",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Eliminate massive number of lists in table generation"
} | 220239 |
<p>I have a csv file with sales transactions. Each transaction includes person identifiers (which are sometimes/often missing) and transaction data. Person identifiers are fname, lname, phone, email and social security number. I want to link each transaction to a unique person. As a business rule, I have set that two transactions belong to the same person if fname and lname are identical AND at least one of the 3 other person identifiers are identical. As an outcome, I need to have two dataframes (and ultimately two csv files): one with the unique persons and one copy of the initial data with an additional column for the person id.</p>
<p>I have written code that works very well for solving the problem for small files. Except that when the file gets really long (hundreds of thousands of lines), it gets stuck. I am almost sure that my code is not optimized and I think I can find a better way using agreggate functions like groupby() or unique(), which I think are much faster. But I can't figure out how.</p>
<pre><code>import pandas as pd
workDir=r"D:\fichiers\perso\perso\python\unicity\\"
sourceFile='rawdata.csv'
inFrame=pd.read_csv(workDir+sourceFile, sep=";",encoding='ISO-8859-1')
personFrame=pd.DataFrame(columns=('id','fname','lname','email', 'phone','social security number'))
outFrame=pd.DataFrame(columns=inFrame.columns)
idPerson=0
#print(inFrame)
def samePerson(p1, p2):
response=0
if p1['fname']==p2['fname'] and p1['lname']==p2['lname']:
if p1['email']==p2['email'] or p1['phone']==p2['phone'] or p1['social security number']==p2['social security number']:
response=1
return(response)
def completePerson(old, new):
#complete with new line missing data in ols version of the person
for theColumn in ('fname','lname','email', 'phone','social security number'):
if pd.isnull(old[theColumn]) :
old [theColumn]=new[theColumn]
return(old)
def processLine(theLine):
global personFrame
global idPerson
global outFrame
theFlag=0
for indexPerson, thePerson in personFrame.iterrows():
if theFlag==0:
if samePerson(theLine,thePerson):
theLine['idPerson']=thePerson.idPerson
personFrame.loc[indexPerson]=completePerson(thePerson, theLine)
theFlag=1
if theFlag==0:
theLine['idPerson']=idPerson
idPerson=idPerson+1
personFrame=personFrame.append(theLine)
outFrame=outFrame.append(theLine)
def processdf():
inFrame.apply(processLine, axis=1)
with open(workDir+'persons.csv','w', encoding='ISO-8859-1') as f:
personFrame.to_csv(f, index='false')
with open(workDir+'transactionss.csv','w', encoding='ISO-8859-1') as f:
outFrame.to_csv(f, index='false')
processdf()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T23:03:13.143",
"Id": "425557",
"Score": "0",
"body": "Is the program crashing? Do you have some code to indicate progress to show the code is still running?"
}
] | [
{
"body": "<p>Here's a much faster algorithm:</p>\n\n<p>Create a Person object containing fields like fname, lname, etc and a list of associated Transaction objects. </p>\n\n<p>Then, create a dictionary with \"fname,lname\" as the key and a list of Person objects as the value. Iterate through your CSV line-by-line, and if that \"fname,lname\" key isn't in the dictionary, add it along with a Person object that defines the person's details.</p>\n\n<p>However, if the key <em>is</em> in the dictionary then check the other details to make sure it's an actual match. If it is an actual match, add the transaction to that Person's Transaction array. If not, add a new person item to the end of the array. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T19:23:39.803",
"Id": "220249",
"ParentId": "220242",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T16:30:30.037",
"Id": "220242",
"Score": "2",
"Tags": [
"python",
"performance",
"csv",
"pandas"
],
"Title": "Grouping sales transactions by person"
} | 220242 |
<p>I am trying to learn the basics about neural networks by coding from scratch the perceptron model. </p>
<p>Since I am not a programmer and would like to improve my coding skills I would like to get your comments about this code. What do you think about it (I tried to respect the different steps: forward and backward for backpropagation)? I suppose it is quite horrific for a Python programmer and would be pleased to gain some insight about some of my evidently bad practices ;)</p>
<p>Here is my work (inspired by Rashka book):</p>
<pre><code>class Perceptron(object):
def __init__(self, eta=0.01, epochs=50):
self.eta = eta
self.epochs = epochs
def fit(self, X, Y):
self.w_ = np.zeros(X.shape[1])
self.b_=0
self.cost_ = []
for _ in range(self.epochs):
errors=0
for x_i,y_i in zip(X,Y):
y_hat=self.forward(x_i)
gradL_W,gradL_b=self.backward(y_i,y_hat,x_i)
self.w_,self.b_=self.update(gradL_W,gradL_b)
errors+=(y_hat!=y_i)*1
self.cost_.append(errors)
return self
def net_input(self, x):
"""Calculate net input"""
return x.dot(self.w_) + self.b_
def activation(self,z):
heaviside= lambda x: (1, -1)[x<0]
return heaviside(z)
def forward(self,x):
s= self.net_input(x)
y_hat=self.activation(s)
return y_hat
def backward(self,y,y_hat,x):
error=-(y-y_hat)
gradL_b=error*1
gradL_W=error*x
return gradL_W,gradL_b
def update(self,gradL_W,gradL_b):
self.w_=self.w_-self.eta*gradL_W
self.b_=self.b_-self.eta*gradL_b
return self.w_,self.b_
def predict(self,X):
s=X.dot(self.w_)+self.b_
y_hat=list(map(lambda x: (1, -1)[x<0],s))
return y_hat
</code></pre>
| [] | [
{
"body": "<h2>Style</h2>\n\n<p>Python comes with an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a> often just called PEP8, and especially as a beginnger it's a good starting point to get going. Of course coding style is often a matter of choice, however, there are aspects you should definitely follow.</p>\n\n<p><strong>Whitespace</strong><br/>\nAs you know, Python's code structure is build upon indentation, so some parts are already language-defined. The style guide also has recommendations on how to use <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">whitespace within statements and expressions</a>. For example, <code>,</code> should always be followed be a single space character, while <code>=</code> is preceded and followed by a single space when used in assignments (there should be no whitespace around <code>=</code> if used as keyword arguments to functions such as <code>foo(batz='bar')</code>). So you would go from</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>gradL_W,gradL_b=self.backward(y_i,y_hat,x_i)\nself.w_,self.b_=self.update(gradL_W,gradL_b)\n</code></pre>\n\n<p>to</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>gradL_W, gradL_b = self.backward(y_i, y_hat, x_i)\nself.w_, self.b_ = self.update(gradL_W, gradL_b)\n</code></pre>\n\n<p>which does look way cleaner IMHO.</p>\n\n<p><strong>Variable names</strong><br/>\nIt's always good practice to use descriptive variable names. Simply writing <code>self.weights</code> instead of <code>self.w_</code> wont hurt that much. Apart from that, the Style Guide also recommends to use a single leading underscore for non-public variable names. Note, this is only a convention, since Python has no \"real\" private member variables as you may know from other languages.</p>\n\n<p><strong>Documentation</strong><br/>\nThere is a single function in your perceptron class that has a) documentation and b) also follows the <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">docstring-style</a> from the Style Guide. You should apply that to the other functions and maybe even to the class as well. Your current project might be simple, but if projects become more complex, good documentation will save you a lot of headache. Following the official docstring style also has the nice benefit that Python's <code>help(...)</code> function as well as most IDEs will easily find it.</p>\n\n<h2>The code</h2>\n\n<p>Apart from the stylistic issues mentioned above, there are some more direct code-focused aspects you should work on.</p>\n\n<p><strong>Code duplication</strong><br/>\nThere is some duplicated code in your implementation of the perceptron model. E.g., you implement the scalar product at the input of the perceptron twice! The first time at <code>net_input</code>, which is likely where it's supposed to go, and the second time in <code>predict</code>. <code>predict</code> also reimplements pretty much the whole point of <code>activation</code>. It's pretty straightforward to implement <code>predict</code> using <code>net_input</code> and <code>activation</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def predict(self, X):\n s = self.net_input(X)\n y_hat = list(map(self.activation, s))\n return y_hat\n</code></pre>\n\n<p>If you use Python for a while you will also learn to use list comprehensions more often than the <code>list(map(...))</code> construct, simply because it's more flexible and readable. Rewriting the calculation of <code>y_hat</code> as list comprehension would look like <code>y_hat = [self.activation(i) for i in s]</code>. After you have arrived at</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def predict(self, X):\n s = self.net_input(X)\n y_hat = [self.activation(i) for i in s]\n return y_hat\n</code></pre>\n\n<p>you may also find the similarity between <code>predict</code> and <code>forward</code> quite striking. <code>forward</code> can now be boiled down to simply</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def forward(self, x):\n return self.predict(x)[0]\n</code></pre>\n\n<p>Getting the \"first\" result of the return value using <code>[0]</code> is mainly to ensure that the new version just returns a single number as it was before. Otherwise it would be a list with a single element.</p>\n\n<p><strong>Explicit is better than implicit</strong><br/></p>\n\n<p>(Taken from the <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">Zen of Python</a>)</p>\n\n<p>Using code like </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>heaviside = lambda x: (1, -1)[x < 0]\nreturn heaviside(z)\n</code></pre>\n\n<p>might be clever, but clever does not equal good or readable most of the time. The same thing can also be expressed as <code>return -1 if z < 0 else 1</code>, which is almost a verbatim translation of the mathematical definition of the step function as presented by Rashka. If you don't like the inline-if, you may also write it as \"normal\" if condition:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if z < 0:\n return -1\nelse:\n return 1\n</code></pre>\n\n<p><code>gradL_b = error * 1</code> is another instance of cleverness. This time, I am not even sure what you are actually trying to accomplish here. Depending on the type of your labels <code>y</code>, <code>error</code> will either be of type <code>int</code> or maybe also <code>float</code>, and multiplying it with <code>1</code> will not change that.</p>\n\n<p><code>errors += (y_hat != y_i) * 1</code> is more obvious, but could also be expressed explicitly as <code>errors += int(y_hat != y_i)</code>. Python should even be able to do <code>errors += y_hat != y_i</code> without changing the end result.</p>\n\n<p><strong>Return values</strong><br/>\nI'm not 100% sure what you are trying to accomplish with some of your function return values. For example, I cannot see the point in <code>fit</code> returning <code>self</code>. <code>update</code>is another instance of that topic. I can see you're using it as <code>self.w_, self.b_ = self.update(gradL_W, gradL_b)</code>, but there is not a real reason to do this, since <code>update</code> already modifies the weights internally.</p>\n\n<p>You will likely have to think about that topic as you further progress in your journey into the depths of neural networks (pun intended). Often, the multilayer perceptron is one of the next logical steps in this process. At this stage, you will need the gradients of previous layers to be able to propagate errors through the network. But time will tell<sup>1</sup>.</p>\n\n<p>Until then: Happy coding!</p>\n\n<hr>\n\n<p><sub><sup>1</sup>You will also probably soon find out that modelling single neurons is not sufficient (and computationally efficient) for what there is to come. Depending on your learning materials, matrix operations will pop up more and more often. This is the time where the NumPy library will help you shine.</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:36:01.373",
"Id": "425696",
"Score": "0",
"body": "Thanks for your help. Concerning the \"self\" for the fit method, i mimic what S. Raschka do in his train method https://sebastianraschka.com/Articles/2015_singlelayer_neurons.html#frank-rosenblatts-perceptron; i thought i was perhaps missing something ... if someone know a good reason to add return self it interest me ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T08:10:06.177",
"Id": "425705",
"Score": "0",
"body": "Returning `self` would allow you to do some kind of \"chaining\" like `nn.fit(X, Y).fit(other_X, other_Y)`, but in your implementation there is no point in doing this since the network parameters are reset each time. Apart from that you can always express it as `nn.fit(X, Y)`, followed by `nn.fit(other_X, other_Y)`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T21:51:56.723",
"Id": "220318",
"ParentId": "220243",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220318",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T16:53:12.017",
"Id": "220243",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"neural-network"
],
"Title": "Implementation of perceptron, inspired by Rashka"
} | 220243 |
<p>Based on feedback on my <a href="/q/220138">previous question</a>, I made many small adjustments to the code, added more APIs and tried to follow through with delivering on the excellent advice I have received in regards to my code. I have updated my code with small summaries to provide more documentation.</p>
<p>Here is the <em>updated</em> interface.</p>
<pre><code>namespace Constrainable
{
public interface IConstrainableSet<T>
{
T AlterInput(T Value);
T AlterInputConstrainedStore(T Value);
ConstrainableSet<T> ChainLinkClone();
ConstrainableSet<N> ChainLinkNew<N>(Predicate<N> CheckBeforeSet = null, Func<N, N> ModifyBeforeSet = null, Action<ConstrainableSet<N>> FailAction = null, Action<ConstrainableSet<N>> SuccessAction = null);
T ConstrainedStore(T Value);
T GetStoredData();
bool IsValid(T Value);
}
public interface IConnectable
{
public object Root { get; set; }
public object Next { get; set; }
public object Parent { get; set; }
}
}
</code></pre>
<p>And here is the new code.</p>
<pre><code>using System;
namespace Constrainable
{
public class Connectable : IConnectable
{
public object Root { get; set; }
public object Next { get; set; }
public object Parent { get; set; }
}
/// <summary>
/// ConstrainableSet is intended to Allow full control over what data gets set in the inner field `data,
/// You can optioning modify the input. This is also intended to be a test of idea's,
/// new and/or interesting ways of accomplishing tasks.
/// </summary>
/// <typeparam name="T"></typeparam>
public class ConstrainableSet<T> : Connectable, IConstrainableSet<T>
{
public ConstrainableSet(Predicate<T> CheckBeforeSet = default, Func<T, T> ModifyBeforeSet = default, Action<ConstrainableSet<T>> FailAction = default, Action<ConstrainableSet<T>> SuccessAction = default)
{
_failAction = FailAction;
_checkBeforeSet = CheckBeforeSet;
_modifyBeforeSet = ModifyBeforeSet;
_successAction = SuccessAction;
}
#region ControlFlow
/// <summary>
///`_failAction` field recieves the `FailAction` parameter in the constructor.
///This Parameter is a callback that is run when a failure occurs in `ConstrainedStore()`,
///for both Callbacks the whole `ConstrainableSet` Object is passed as a parameter.
/// </summary>
private readonly Action<ConstrainableSet<T>> _failAction;
/// <summary>
/// _successAction field recieves the `SuccessAction` parameter in the constructor.
/// This Parameter is a `Callback` , this function is called on in `ConstrainedStore()`
/// and only after successful set of the inner private field `data`.
/// </summary>
private readonly Action<ConstrainableSet<T>> _successAction;
/// <summary>
/// _checkBeforeSet is a bool lambda expression which evaluates the Parameter
/// to be set, and must return true for the data to be set
/// </summary>
private readonly Predicate<T> _checkBeforeSet;
/// <summary>
/// _modifyBeforeSet this routine Takes type T as input and returns type T
/// this function is for Encryption or Concatenating or anything that involves modifying the parameter passed in to it
/// </summary>
private readonly Func<T, T> _modifyBeforeSet;
#endregion
private T data;
/// <summary>
/// The ConstrainableStore Function is the combined input of
/// 3 parameters in this fashiion (PreCheck ? SuccessAction : FailAction)
/// if there is no _checkBeforeSet function defined then this simply returns the value passed in,
/// if there is an _checkBeforeSet function defined, it calls that function and based on success or failure.
/// if that Action is defined for success it moves the value into storage then calls SuccessAction,
/// if there is no success action it sets the successful checked value and returns the value,
/// if there is no FailAction defined at this point then it returns the default value for this type
/// </summary>
/// <param name="Value"></param>
/// <returns>T</returns>
public virtual T ConstrainedStore(T Value)
{
if (_checkBeforeSet != default)
{
if (_checkBeforeSet(Value))
{
if (_successAction != default)
{
data = Value;
_successAction(this);
}
data = Value;
return Value;
}
if (_failAction != default)
{
_failAction(this);
}
return default;
}
return Value;
}
/// <summary>
/// IsValid runs the define checkBeforeSet function and returns result.
/// </summary>
/// <param name="Value"></param>
/// <returns>bool</returns>
public virtual bool IsValid(T Value)
{
if (_checkBeforeSet != null)
{
return _checkBeforeSet(Value);
}
return false;
}
/// <summary>
/// This is the interesting function,
/// I think with this simple function actionable values can be achieved
/// many tasks could benefit from Actionable `Validated` values imho.
/// Actionable values is values that can be used in some way(s) to get a new value or object,
/// or encrypting the value passed in, this could be used for something like that.
/// </summary>
/// <param name="Value"></param>
/// <returns></returns>
public virtual T AlterInput(T Value)
{
if (_modifyBeforeSet != default)
{
return _modifyBeforeSet(Value);
}
return Value;
}
//Combined usage
public virtual T AlterInputConstrainedStore(T Value)
{
return ConstrainedStore(AlterInput(Value));
}
/// <summary>
/// I made a simple way to link objects together
/// I simply needed to pinpoint Cloning and Creation and
/// push the proper values to these objects during cloning or creation.
/// </summary>
/// <returns></returns>
public ConstrainableSet<T> ChainLinkClone()
{
if(Root == default)
{
Root = this;
}
ConstrainableSet<T> newpo = new ConstrainableSet<T>(_checkBeforeSet, _modifyBeforeSet, _failAction, _successAction);
IConnectable Iterator;
if (Next != default)
{
Iterator = Next as IConnectable;
while (Iterator.Next != default)
{
Iterator = Iterator.Next as IConnectable;
}
Iterator.Next = newpo;
newpo.Root = Root;
newpo.Parent = this;
return newpo;
}
else
{
Next = newpo;
newpo.Root = Root;
newpo.Parent = this;
return newpo;
}
}
public ConstrainableSet<N> ChainLinkNew<N>(Predicate<N> CheckBeforeSet = default, Func<N, N> ModifyBeforeSet = default, Action<ConstrainableSet<N>> FailAction = default, Action<ConstrainableSet<N>> SuccessAction = default)
{
if (Root == default)
{
Root = this;
}
ConstrainableSet<N> newpo = new ConstrainableSet<N>(CheckBeforeSet, ModifyBeforeSet, FailAction, SuccessAction);
IConnectable Iterator;
if (Next != default)
{
Iterator = Next as IConnectable;
while (Iterator.Next != default)
{
Iterator = Iterator.Next as IConnectable;
}
Iterator.Next = newpo;
newpo.Root = Root;
newpo.Parent = this;
return newpo;
}
else
{
Next = newpo;
newpo.Parent = this;
newpo.Root = Root;
return newpo;
}
}
//returns the data field.
public T GetStoredData()
{
return data;
}
}
}
</code></pre>
<p>I would also like to provide a example of usage. This example demonstrates the new ChainLinkNew Function which can be used in the SuccessCallback function to chain validations and data stores together, or in the way I accomplish this below. Any input on my approach is highly appreciated.</p>
<pre><code> public Test()
{
ConstrainableSet<int> programmable = new ConstrainableSet<int>(
CheckBeforeSet: x => x == 100
).ChainLinkNew<int>(
CheckBeforeSet: x => x == 10 | x == 1,
ModifyBeforeSet: x => x / 10,
FailureCallBack,
SuccessCallBack)
.Root as ConstrainableSet<int>;
void FailureCallBack(ConstrainableSet<int> set)
{
}
void SuccessCallBack(ConstrainableSet<int> set)
{
}
((ConstrainableSet<int>)programmable.Next).AlterInputConstrainedStore(programmable.ConstrainedStore(100));
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T18:05:29.917",
"Id": "425531",
"Score": "0",
"body": "Bah realized I introduced a flaw.. although workable as it is I will still fix it anyways..\nThe flaw is that IConstrainableSet interface defined root next and parent, so that means Root, Next and Parent in my implementation class also define these 3 items each, to remedy this I will make a impl class for this interface.. please do not review until I make this change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T18:41:29.660",
"Id": "425533",
"Score": "0",
"body": "updated per last comment, please review the horrible hack I just implemented.. :["
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T07:30:43.503",
"Id": "425704",
"Score": "1",
"body": "What exactly are your goals/requirements for this code? What actual problems are you trying to solve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:23:05.347",
"Id": "425728",
"Score": "0",
"body": "Well my goals are: I want a tool that can be used to validate input and store or alter that input. I also want connect them together, and easily reuse th. I think maybe I covered all the ground I can Setting a field.. tbh this all started with just wanting to code better, and learn more, and tackle a topic that is simple and often not considered useful, property set. I dislike declaring data, so this tool is a experiment to abstract that away, as well.. I came up with the original generic design, which was closed, and wanted to improve upon it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:50:02.083",
"Id": "425733",
"Score": "0",
"body": "That still sounds fairly abstract. So this is meant to replace properties - instead of `person.FirstName = \"John\";`, with some validation logic in the setter, you'd write `person.FirstName.AlterInputConstrainedStore(\"John\");`? What does this offer that you can't (easily) do with 'normal' properties? And why would you need to connect these properties together? Or did you have a different use-case in mind?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:30:08.220",
"Id": "425742",
"Score": "0",
"body": "ConstrainableSet<ReadOnlyMemory<char>> FullName = \n new ConstrainableSet<ReadOnlyMemory<char>>()\n .Store(new ReadOnlyMemory<char>(\"John\".ToCharArray()))\n .ChainLinkClone().Store(new ReadOnlyMemory<char>(\"Doe\".ToCharArray()));\n\nDoes this help ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:54:54.627",
"Id": "425760",
"Score": "0",
"body": "No - the current code doesn't support that, but even with the changes that that implies I still don't see _why_ you'd want to do that, or where this would actually be useful. Why not just write `person.FirstName = \"John\"; person.LastName = \"Doe\";`, and have a `string FullName => $\"{FirstName} {LastName}\";` property instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T08:33:34.157",
"Id": "425864",
"Score": "2",
"body": "You should only ask for code review on working code. This code doesn't compile, so it is definitely not working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T07:10:02.900",
"Id": "426127",
"Score": "0",
"body": "I suggest asking a new question with improved code, description and especially a _real-world_ example. This example could be a simple `Person` class with a couple of properties like `FirstName`, `LastName`, `DateOfBirth` or whatever so that you can clearly show us how you are going to use this tool in action. The test's usefulness is very limited because it only shows whether it works, it lacks an example showing how it is intended to be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-24T16:21:37.460",
"Id": "426973",
"Score": "0",
"body": "I did a ton of research to try and figure out how I could safely communicate between different types, in a functionally repeatable fashion.. Finally came down to just using the DLR to do a few tasks for me, and implementing a function to accept a parameter. Now I can present a good example, I hope..."
}
] | [
{
"body": "<p>Like Pieter Witvoet I don't quite understand which problem this code is trying to solve. There is an <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1?view=netframework-4.8\" rel=\"nofollow noreferrer\">ObservableCollection Class</a> that partly does the same. Together with validation logic in properties and possibly the implementation of <code>INotifyPropertyChanged</code>, this comes close to your solution.</p>\n\n<p>Apart from this, your code has problems and can be improved.</p>\n\n<ul>\n<li><p>It does not compile, because interface members in <code>IConnectable</code> are declared as public. Interface members are always public (C# 8 will change this, but we are not quite there yet). You should always post compilable code on Code Review.</p></li>\n<li><p><code>ChainLinkNew<N></code> allows to add elements of another type to the collection. The purpose of generics is to provide type safety while allowing you to create type variants at design time. With this construct you are losing type safety, as the type of added elements in the set will be determined at run time. Use the class' type parameter <code>T</code> instead. If you need to add items of different types, create a <code>ConstrainableSet<object></code> or use a base type common to all elements. Like this, at least your constrainable set is consistent and type safe, even if the data is not. Otherwise none of them will be.</p></li>\n<li><p>The interface <code>IConstrainableSet<T></code> depends on its own implementation! As explained <a href=\"https://stackoverflow.com/a/9112750/880990\">here</a>,</p>\n\n<blockquote>\n <p>The point of the interfaces is to have something that is common to all implementations. By trying to do this you destroy the whole reason why interfaces exist.</p>\n</blockquote>\n\n<p>Change the interface to (and adapt the implementation) </p>\n\n<pre><code>public interface IConstrainableSet<T>\n{\n ...\n IConstrainableSet<T> ChainLinkClone();\n IConstrainableSet<T> ChainLinkNew(Predicate<T> CheckBeforeSet = null,\n Func<T, T> ModifyBeforeSet = null, Action<IConstrainableSet<T>> FailAction = null,\n Action<IConstrainableSet<T>> SuccessAction = null);\n ...\n}\n</code></pre></li>\n<li><p>The <code>IConnectable</code> interface should be generic.</p>\n\n<pre><code>public interface IConnectable<T>\n{\n T Root { get; set; }\n T Next { get; set; }\n T Parent { get; set; }\n}\n</code></pre></li>\n<li><p>The <code>Connectable</code> class can be <code>abstract</code> and must implement <code>IConnectable<T></code>. <code>Connectable</code> by itself does not contain data and does not seem to be useful other than as base class. If it contained a <code>Data</code> field it would make sense to instantiate a <code>Connectable</code>. As it is now, you could only create a doubly linked list containing empty nodes.</p>\n\n<pre><code>public abstract class Connectable<T> : IConnectable<T>\n</code></pre></li>\n<li><p>These improvements require some changes in the implementation but also allow some simplifications. E.g. in <code>ChainLinkClone</code></p>\n\n<pre><code>var newpo = new ConstrainableSet<T>(_checkBeforeSet, _modifyBeforeSet, _failAction,\n _successAction);\nif (Next != default) {\n ConstrainableSet<T> Iterator = Next;\n while (Iterator.Next != default) {\n Iterator = Iterator.Next;\n }\n...\n} else {\n ...\n}\n</code></pre>\n\n<ul>\n<li>Use <code>var</code> in the <code>new</code> statement to avoid rewriting the lengthy type name.</li>\n<li>Move <code>Iterator</code> inside <code>if</code> and use an initializer.</li>\n<li>We can drop some casts.</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T02:02:10.727",
"Id": "425838",
"Score": "0",
"body": "thank you for reviewing, it's a WIP, and I really want to make it as DRY as possible, and solidly reviewed, before expanding upon it. My vision is to eventually make the data transient, and add configurable data flow to the created ConstrainableSet, to allow IO between the created items in a defined way. I am having trouble understanding why Connectable can/should be abstract, and why it should implement the IConnectable<T>. if I move the interface to ConstrainableSet then I can do IConnectable<IConstrainableSet<T>>, does this work well or is it bad taste?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:12:15.910",
"Id": "425881",
"Score": "0",
"body": "`Connectable` by itself does not contain data and does not seem to be useful other than as base class. If it contained a `Data` field it would make sense to instantiate a `Connectable`. As it is now, you could only create a doubly linked list containing empty nodes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:17:43.567",
"Id": "220359",
"ParentId": "220244",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:07:42.580",
"Id": "220244",
"Score": "0",
"Tags": [
"c#",
"validation",
"callback",
"properties",
"fluent-interface"
],
"Title": "Chaining ConstrainableSet<T>"
} | 220244 |
<p>I have a container. This container has exactly this structure:</p>
<pre><code>['unique_id_1'] => [
'base' => Object,
'style' => Object,
'id' => 'unique_id_1',
'type' => 'warning'
],
['unique_id_2'] => [
'base' => Object
'style' => Object,
'id' => 'unique_id_2',
'type' => 'normal'
]
</code></pre>
<p>It's important to know that the <code>style</code> key holds an object that is dynamically built, as in: based on certain data flags, it is either the default object, or a custom one and for this, I use a replacer object of some sorts:</p>
<pre><code>public function replaceStyleForId( $id, StyleInterface $new_style )
{
$this->replacement_data[$id] = [ 'id' => $id, 'replace_with' => $new_style ];
}
</code></pre>
<p>Where <code>replace_with</code> is my new style object that I'll use. Now, as you can tell, it also has an <code>id</code>. I use this to identify my original data in the container and say "aha, the replacer's telling me that any item with this ID must have its style object changed. Assuming I did <code>replaceStyleForId( 'unique_id_2', new CustomStyle)</code>, my system would then, when it finds, in the original data, items with this ID, replace their style with <code>CustomStyle</code>.</p>
<p>So, we're dealing with two arrays here and I'm first, searching by either <code>id</code> or <code>type</code> to see if it's found, then perform operations if so.</p>
<p>Great! A way to safely plug & play objects even with PHP's limiting interfaces. But hold on. This is what my factory looks like when it's doing this exact thing:</p>
<pre><code> /**
* Retrieves the data from the replacer. This data will solely be used to replace
* style objects of certain notifications based on either type or ID.
*/
$replacer_data = $this->replacer->getDataForReplacement();
foreach( $notifications_data as $notification_data ) {
if( $replacer_data ) {
foreach( $replacer_data as $replacement_data_handle => $replacement_data_package ) {
if( array_key_exists( 'type', $replacement_data_package ) ) {
if( $notification_data['type'] == $replacement_data_package['type'] ) {
$this->addBundledNotificationPackage(
new Base\BasicNotification( $notification_data, $notification_data['id'] ),
$replacement_data_package['replace_with']
);
} else {
$this->addBundledNotificationPackage(
new Base\BasicNotification( $notification_data, $notification_data['id'] ),
new Base\BasicNotificationStyle()
);
}
}
if( array_key_exists( 'id', $replacement_data_package ) ) {
if( $notification_data['id'] == $replacement_data_package['id'] ) {
$this->addBundledNotificationPackage(
new Base\BasicNotification( $notification_data, $notification_data['id'] ),
$replacement_data_package['replace_with']
);
} else {
/**
* If nothing is inside the replacer, then we simply just create the notification using the base objects.
*/
$this->addBundledNotificationPackage(
new Base\BasicNotification( $notification_data, $notification_data['id'] ),
new Base\BasicNotificationStyle()
);
}
}
}
} else {
/**
* If nothing is inside the replacer, then we simply just create the notification using the base objects.
*/
$this->addBundledNotificationPackage(
new Base\BasicNotification( $notification_data, $notification_data['id'] ),
new Base\BasicNotificationStyle()
);
}
}
</code></pre>
<p>Except, this is hell. First of all, I loop through all of my original data, then, for each loop, I check if there's data to replace and then I do 2 more checks to look at what I need to replace by. Is it by <code>id</code>, is it by <code>type</code>? If so, then go ahead and create my object package to pass it to the container as a final "after all these checks with the replacer, this is your final package".</p>
<p>The logic is sound and although it looks complex, it makes sense. I abstracted as much as I could so I don't repeat myself, but this is clearly not clean.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T05:48:31.623",
"Id": "425567",
"Score": "1",
"body": "@mickmackusa Edited. Sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T06:01:20.783",
"Id": "425568",
"Score": "0",
"body": "So `$replacement_data_handle` is always redundantly stored in `$replacement_data_package['id']`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T06:18:37.733",
"Id": "425570",
"Score": "0",
"body": "@mickmackusa Correct, the handle from the replacement data will always correspond to `$replacement_data_package['id']` and furthermore, they could (this is a case my code handles) correspond to a notification's `id`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T12:41:51.307",
"Id": "425726",
"Score": "0",
"body": "Can I just confirm that there is no benefit to potentially replacing twice for the same set of data? In other words, you have `if` block followed by another `if` block -- but would be just as accurate if the 2nd `if` was `elseif`, right? I am asking because when I suggest a refactor, I don't want to be fuzzy on the details. Also, are the `array_key_exists()` calls actually necessary? Is your incoming data inconsistently/unpredictably structured?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:54:56.650",
"Id": "425735",
"Score": "0",
"body": "@mickmackusa There is a benefit if you believe it is, I can modify and set my data as I please, basically free to do anything. As for the call, yup, it is necessary, even if heavily documented on how the data should look, I just want to play defensively."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T17:20:30.983",
"Id": "220246",
"Score": "1",
"Tags": [
"php",
"array"
],
"Title": "Check for key in two arrays in order to control flow of the program"
} | 220246 |
<p><em>Edit: Licensed source can be found <a href="https://github.com/RabidGuy/ticker" rel="nofollow noreferrer">here</a>.</em></p>
<p>The intent behind this class is to allow different game systems to run at their own clock rate. The physics integration rate should not be connected to the screen refresh rate, for instance. Instancing this class should allow for accurate, independent timing of separate systems.</p>
<p>Does this code meet that requirement?</p>
<p>An additional feature added while writing was access to the object's <code>tps</code> property, allowing for changes to operating rate during use.</p>
<pre><code>from datetime import datetime
class Ticker:
# 1,000,000; a one followed by six zeroes
microseconds_per_second = 1000000
def __init__(self, tps=1):
self.tps = tps
self._last_mark = 0
self._accumulator = 0
@property
def tps(self):
return self._tps
@tps.setter
def tps(self, ticks_per_second):
assert int(ticks_per_second) == ticks_per_second
assert 0 < ticks_per_second
self._tps = ticks_per_second
@property
def last_mark(self):
return self._last_mark
@property
def _microseconds_per_tick(self):
return Ticker.microseconds_per_second / self.tps
def tick(self):
"""Returns the number of unprocessed ticks.
First call will initialize clock by setting first mark.
This first call will return -1. All other calls will
return an integer greater than or equal to zero.
"""
if not self.last_mark:
# Set firt time mark and exit.
self._last_mark = datetime.now()
return -1
# Get dt, the change in time, and update mark.
next_mark = datetime.now()
dt = next_mark - self._last_mark
self._last_mark = next_mark
# Increment accumulator by change in time:
# 1) the seconds, which are converted to microseconds.
# 2) the microseconds, which total less than one second.
self._accumulator += (dt.seconds * Ticker.microseconds_per_second)
self._accumulator += dt.microseconds
# Drain full ticks from accumulator and return count.
ticks_elapsed = 0
while self._accumulator >= self._microseconds_per_tick:
self._accumulator -= self._microseconds_per_tick
ticks_elapsed += 1
return ticks_elapsed
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T19:27:44.163",
"Id": "220250",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"game",
"datetime",
"timer"
],
"Title": "Game clock with configurable rate"
} | 220250 |
<p>I am trying to solve the <a href="https://www.hackerrank.com/challenges/new-year-chaos/problem" rel="nofollow noreferrer">HackerRank New Year Chaos problem</a> where the aim is as follows:</p>
<p>A vector of size <code>n</code> is having values <code>[1,2,3,...,(n-1),n]</code> with no repetition. A <code>k</code>th element can switch only with the <code>(k-1)</code>th element. An element can maximum switch 2 times with its predecessor.</p>
<p><em>Thus we can say that any <code>k</code>th element should find its place at minimum <code>(k-2)</code>th index</em></p>
<p>Now, The vector given to the below given function <code>minimumBribes()</code> is the unordered / unsorted one, and I need to find the minimum switched occurred to the sorted vector.</p>
<p>NOTE: If the any element makes more than 2 switches, only print "Too chaotic"</p>
<pre><code>void minimumBribes(vector<int> q) {
int count = 0;
for (int p_number = 0; p_number < q.size() - 1; p_number++) {
if ((p_number+1) != q[p_number]) {
vector<int>::iterator it = find(q.begin(), q.end(), (p_number+1));
int index = distance(q.begin(), it);
for (; index > p_number; index--) {
if (q[index - 1] - index > 2) {
cout << "Too chaotic" << endl;
return;
} else {
q[index] = q[index - 1];
count++;
}
}
q[p_number] = (p_number+1);
}
}
cout << count << endl;
}
</code></pre>
<p>The above solution works. but fails for 2 testcases with timeout error.</p>
<p>How to bring down the run time here?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:57:36.453",
"Id": "425554",
"Score": "2",
"body": "Can you please show us the rest of the program? There is not enough code here to review or to offer suggestions for performance improvements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T08:09:51.977",
"Id": "425948",
"Score": "0",
"body": "@pacmaninbw The code running the tests is not up for review, since it's written by HackerRank, not the OP. The rest can be found with the challenge, but I'm not sure including it would be appropriate."
}
] | [
{
"body": "<p>Good attempt, but unfortunately the nested loop brings the time complexity to O(n<sup>2</sup>). Keep in mind that <code>.find</code> performs a linear search on the vector, inspecting up to the entire array to find an element. We can arrive at a O(n) solution by exploiting the fact that no more than 2 swaps can be performed by any given element, which is a red flag in the problem statement that your solution ignores. In other words, we can transform the linear operation inside the array to constant time.</p>\n\n<p>Here's the approach I used:</p>\n\n<p>Start at the back of the array and move forward. For each element <code>q[i]</code> not in its original location, check only <code>q[i-1]</code> and <code>q[i-2]</code> to see if it moved to one of those locations. If the element is in <code>q[i-1]</code>, then it must have used only one bribe. If at <code>q[i-2]</code>, it must have taken two bribes to get there. Either way, perform an un-swap to return it to its original location. If it's not at either element, the array is \"Too chaotic\".</p>\n\n<p>Let's try this algorithm on the input examples:</p>\n\n<h3>Example 1</h3>\n\n<pre class=\"lang-none prettyprint-override\"><code>initial state: \n[2, 1, 5, 3, 4]\n\n[2, 1, 5, 3, 4]\n ^-- This element should be a 5. Let's look for 5 at index 3 or 2.\n[2, 1, 5, 3, 4]\n ^-------- Found 5 at index 2. It must have swapped twice; set `bribes = 2`.\n[2, 1, 3, 4, 5]\n ^-- Put 5 where it belongs by undoing the swaps it made.\n\n[2, 1, 3, 4, 5]\n ^-- Moving to the next element, we see 4 is OK.\n\n[2, 1, 3, 4, 5]\n ^-- Moving to the next element, we see 3 is OK.\n\n[2, 1, 3, 4, 5]\n ^-- Moving to the next element, this element should be 2.\n[2, 1, 3, 4, 5]\n ^----- Found 2. It must have swapped once; set `bribes = 3`.\n[1, 2, 3, 4, 5]\n ^-- Put 2 where it belongs by undoing the swap it made.\n\nOutcome: 3 bribes in total must have happened.\n</code></pre>\n\n<h3>Example 2</h3>\n\n<pre class=\"lang-none prettyprint-override\"><code>initial state:\n[2, 5, 1, 3, 4]\n\n[2, 5, 1, 3, 4]\n ^-- This element should be 5. Let's find 5.\n[2, 5, 1, 3, 4]\n ^----- This element, q[i-1], is not 5.\n[2, 5, 1, 3, 4]\n ^-------- This element, q[i-2], is not 5, either.\n\nOutcome: Too chaotic! 5 must have used more than 2 \n bribes to get any further than index 2.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T01:47:33.253",
"Id": "220263",
"ParentId": "220253",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220263",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T20:37:21.243",
"Id": "220253",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "HackerRank New Year Chaos: arriving at a given list using neighbor swaps"
} | 220253 |
<p>I've come with a solution super tricky for a simple requirement. I think I could solve the problem using LinQ, but I'm not seeing it so clearly at all.
What's sure, I'm not comfortable with my code.</p>
<p>The requirement is the following:</p>
<p>Given a list of lists of string (IEnumerable>), take the first N elements from each but one by one.
So given this list of list and N=10:</p>
<pre><code>{aaa, bb, ccc, ddd}
{eee, fff}
{ggg, hhhhh, iii, jjj, kkk}
{lll}
{1111, 22, 333, 444, 55555, 66666}
</code></pre>
<p>This is the output:</p>
<pre><code>{aaa, eee, ggg, lll, 111, bb, fff, hhhhh, 22, ccc}
</code></pre>
<p>And here is the code:</p>
<pre><code>private IEnumerable<string> Extract(
IEnumerable<IEnumerable<string>> listOfList,
int N
)
{
var result = new List<string>();
for (int i = 0; i < N; i++)
{
foreach (IEnumerable<string> list in listOfList)
{
if (list.Count() > i)
{
result.Add(list.ElementAt(i));
if (result.Count >= N)
return result;
}
}
}
return result;
}
</code></pre>
<p>The code works, but I don't think this is maintainable nor easy to read.
Thanks.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T18:09:49.720",
"Id": "425793",
"Score": "1",
"body": "Would you mind clarifying the spec a little? Are you meant to take the first `N` elements of each list, but taking the first of each, then the second of each, etc. or are you meant to take the first `N` of the sequences defined by taking the first, then the second, etc. Your code (and the example and all the answers) currently do the second, but the spec sounds like it wants the first."
}
] | [
{
"body": "<p>Calling <code>ElementAt()</code> inside a loop will cause the <code>IEnumerable</code> to be called multiple times. This code isn't deferring execution either. </p>\n\n<p>Now if you think the previous code wasn't readable then hold on to your hats. I'm going to post some code in hopes someone can build on it and maybe come up with something better. </p>\n\n<pre><code>public static class IEnumerableExtensions\n{\n public static IEnumerable<TSource> Interweave<TSource>(this IEnumerable<TSource> source, params IEnumerable<TSource>[] weavers)\n {\n // Create a list of Enumerators but need to reverse it as will be removing from list and don't want o mess up indexer\n var enumerators = new[] { source }.Concat(weavers).Select(x => x.GetEnumerator()).Reverse().ToList();\n try\n {\n while (enumerators.Count > 0)\n {\n // index backwards so we can remove from list and not mess up index\n for (var i = enumerators.Count - 1; i >= 0; i--)\n {\n var currentEnumerator = enumerators[i];\n if (currentEnumerator.MoveNext())\n {\n yield return currentEnumerator.Current;\n }\n else\n {\n currentEnumerator.Dispose();\n enumerators.Remove(currentEnumerator);\n }\n }\n }\n }\n finally\n {\n // finally block as we can't use \"using\" as have multiple disposables and don't know count ahead of time\n if (enumerators != null)\n {\n enumerators.ForEach(x => x.Dispose());\n }\n }\n }\n}\n</code></pre>\n\n<p>This doesn't do Take, but you can just chain on the Take method. </p>\n\n<p>Example of it in use:</p>\n\n<pre><code>static void Main(string[] args)\n{\n var one = new[] { \"aaa\", \"bb\", \"ccc\", \"ddd\" };\n var two = new[] { \"eee\", \"fff\" };\n var threee = new[] { \"ggg\", \"hhhhh\", \"iii\", \"jjj\", \"kkk\" };\n var four = new[] { \"lll\" };\n var five = new[] { \"1111\", \"22\", \"333\", \"444\", \"55555\", \"66666\" };\n\n foreach (var item in one.Interweave(two, threee, four, five).Take(6))\n {\n Console.WriteLine(item);\n }\n Console.ReadLine();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:10:35.693",
"Id": "425584",
"Score": "1",
"body": "You can avoid the fiddly stuff with the list indices by using a queue instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T09:14:11.957",
"Id": "425591",
"Score": "0",
"body": "This code isn't just more efficient, it will handle infinite and non-resuable `IEnumerables`, which the OP's code won't. I like the lists personally (though not-so-much the reverse order, and it would probably be tidier with a `Queue`); you might consider using `RemoteAt(i)` rather than `Remove(currentEnumerator)` to avoid a linear scan. There is also no utility in the `null` check in the `finally`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T13:21:36.197",
"Id": "425606",
"Score": "0",
"body": "@VisualMelon RemoveAt would be better. The null check was from https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement where they have code of what using boils down to. I was wondering about it as well but put it in based on their example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T23:20:33.090",
"Id": "425676",
"Score": "1",
"body": "I think this is a great approach. Here's a fiddle of what it might look like with `Dequeue` + maybe re-`Enque` in place of `Remove` or `RemoveAt`. https://dotnetfiddle.net/sOYUn4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:18:24.247",
"Id": "425690",
"Score": "0",
"body": "If you're trying to copy the example of what `using` is equivalent to then the null check should be on `x`. But since you're guaranteed that neither `enumerators` nor `x` is null, the check can be optimised away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:55:36.423",
"Id": "425777",
"Score": "1",
"body": "@benj2240 the queue's constructor is eager and will enumerate the main collection entirely."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T02:35:47.950",
"Id": "220264",
"ParentId": "220254",
"Score": "8"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/220264/59161\">CharlesNRice</a>'s solution has still one flaw. It eagerly enumerates the main collection and since we don't know its length, we better avoid it. Since the other answer already mentions flaws in your code, let me just add this lazy alternative.</p>\n\n<hr>\n\n<p>It's a little bit tricky to make it deferred because you first need to enumerate the main collection and create enumerators for each sub-collection, this is what I use the <code>isQueuePopulated</code> flag for. Then you need to collect them in the <code>queue</code> for as long as you're enumerating the main collection. When this is done, you need to switch to the <code>queue</code>, then you <code>Dequeue</code> the first enumerator, try to <code>MoveNext</code> and if it succeeded, you return <code>Current</code> and <code>Enqueue</code> the enumerator for later.</p>\n\n<pre><code>public static IEnumerable<T> TakeEach<T>(this IEnumerable<IEnumerable<T>> source, int count)\n{\n var counter = 0;\n var queue = new Queue<IEnumerator<T>>();\n var mainEnumerator = source.GetEnumerator();\n var isQueuePopulated = false;\n try\n {\n var e = default(IEnumerator<T>);\n while (!isQueuePopulated || queue.Any())\n {\n if (!isQueuePopulated && mainEnumerator.MoveNext())\n {\n e = mainEnumerator.Current.GetEnumerator();\n }\n else\n {\n isQueuePopulated = true;\n }\n\n e = isQueuePopulated ? queue.Dequeue() : e;\n\n if (e.MoveNext())\n {\n queue.Enqueue(e);\n yield return e.Current;\n\n if (++counter == count)\n {\n yield break;\n }\n }\n else\n {\n e.Dispose();\n }\n }\n }\n finally\n {\n mainEnumerator.Dispose();\n foreach (var e in queue)\n {\n e.Dispose();\n }\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T15:32:30.183",
"Id": "220354",
"ParentId": "220254",
"Score": "4"
}
},
{
"body": "<p>A few comments about the API which completely ignore the spec:</p>\n\n<ul>\n<li><p>I would rename <code>N</code> to <code>count</code>, which is descriptive and follows typical naming conventions. Your method would benefit from inline documentation (<code>///</code>), which could clarify the behaviour (what does <code>Extract</code> mean?!?) and describe the parameters precisely.</p></li>\n<li><p>It's good that you've used the general-purpose <code>IEnumerable</code> as the return type (gives you freedom to use lazy implementations like those provided by the other answers). I would consider removing the count parameter: the consumer can use LINQ's <code>Take</code> if they want. Currently the API means you can't just keep consuming stuff until you get bored (e.g. with <code>TakeWhile</code> or something), and lacks a specification as to what the method should do if it runs out of stuff to return, what to do with invalid inputs (e.g. <code>-1</code>) ,and all that fun stuff that comes with providing a nontrivial API.</p></li>\n<li><p>Note that t3chb0t has provided a generic implementation, so it works with lists of anything, and not just strings. There is basically no reason not to do this, and it means you will have a nice reusable piece of code that works with any type.</p></li>\n<li><p>Again, t3chb0t has made the method a <code>static</code> extension method: there is no need for your method to be an instance method unless it is swappable behaviour, which is not implied by the spec. An extension method means it will fit in nicely with the other LINQ methods that most of us use daily.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T18:18:33.373",
"Id": "220368",
"ParentId": "220254",
"Score": "5"
}
},
{
"body": "<p>Another opportunity to solve this problem is to use <code>Transpose()</code> in <a href=\"https://github.com/morelinq/MoreLINQ\" rel=\"nofollow noreferrer\">MoreLinq</a> with Linq itself:</p>\n\n<pre><code>var listoflists = new List<List<string>>() { one, two, three, four, five };\nvar res = listoflists.Transpose()\n .SelectMany(x => x)\n .Take(10);\n</code></pre>\n\n<p><strong>Result:</strong> <code>{ \"aaa\", \"eee\", \"ggg\", \"lll\", \"1111\", \"bb\", \"fff\", \"hhhhh\", \"22\", \"ccc\" }</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T09:28:00.357",
"Id": "425870",
"Score": "0",
"body": "The [`Transpose`](https://github.com/morelinq/MoreLINQ/blob/a112cea587aa4ce4d7ef8753b0cc04775787270b/MoreLinq/Transpose.cs#L55) extension is implemented virtually exactly as we did it here ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T09:30:00.613",
"Id": "425873",
"Score": "0",
"body": "yep ;) As opportunity to not implement it by yourself"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T09:30:40.573",
"Id": "425874",
"Score": "0",
"body": "And I find their `_()` hillarious. This should have never been accepted LOL"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T09:32:42.547",
"Id": "425875",
"Score": "1",
"body": "Although, now I think my solution is better because it's deferred on every collection. Theirs is using [`Acquire`](https://github.com/morelinq/MoreLINQ/blob/a112cea587aa4ce4d7ef8753b0cc04775787270b/MoreLinq/Acquire.cs#L41) which is eager and enumerates the main collection completely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T09:37:55.863",
"Id": "425876",
"Score": "2",
"body": "@t3chb0t it doesn't have much choice, since it yields columns at a time ;) (good point non-the-less) (I also don't like that transpose method's API... transpose ought to be reversible in my book)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T09:24:21.533",
"Id": "220406",
"ParentId": "220254",
"Score": "4"
}
},
{
"body": "<p>Here is another generic and deferred extension method version that seems to work for me. We iterate through all sequences one by one at once and only stop when there is nowhere to go within any sequence or the number of items requested have already been yielded.</p>\n\n<pre><code> public static IEnumerable<TIn> FecthFromEach<TIn>(\n this IEnumerable<IEnumerable<TIn>> sequences,\n int maxLimit)\n {\n var enumerators = sequences.Select(_ => _.GetEnumerator()).ToList();\n var length = enumerators.Count;\n var breakEnumerators = new bool[length]; \n var count = 0;\n\n try\n {\n while (count < maxLimit && breakEnumerators.Any(_ => !_))\n {\n foreach (var i in Enumerable.Range(0, length))\n {\n if (count >= maxLimit) break;\n\n if (!enumerators[i].MoveNext()) breakEnumerators[i] = true;\n else\n {\n yield return enumerators[i].Current;\n ++count;\n }\n }\n } \n }\n finally\n {\n enumerators.ForEach(_ => _.Dispose());\n }\n }\n</code></pre>\n\n<p>Here are the test cases that I use to confirm it's working as expected:</p>\n\n<pre><code>[TestFixture]\npublic class CollectionExtentionsTests\n{ \n [TestCaseSource(nameof(CountResultPairs))]\n public void TestFetchFromEach(Tuple<int, int[]> pair)\n {\n var l1 = new[] { 1, 11, 111, 1111, 11111 };\n var l2 = new[] { 2, 22 };\n var l3 = new[] { 3 };\n var l4 = new[] { 4, 44, 444, 4444 };\n var l5 = new[] { 5, 55, 555 };\n\n var input = new[] { l1, l2, l3, l4, l5 };\n\n var result = input.FecthFromEach(pair.Item1);\n\n CollectionAssert.AreEqual(pair.Item2, result);\n }\n\n private static IEnumerable<Tuple<int, int[]>> CountResultPairs\n {\n get\n {\n yield return Tuple.Create(10, new[] { 1, 2, 3, 4, 5, 11, 22, 44, 55, 111 });\n yield return Tuple.Create(11, new[] { 1, 2, 3, 4, 5, 11, 22, 44, 55, 111, 444 });\n yield return Tuple.Create(12, new[] { 1, 2, 3, 4, 5, 11, 22, 44, 55, 111, 444, 555 });\n yield return Tuple.Create(13, new[] { 1, 2, 3, 4, 5, 11, 22, 44, 55, 111, 444, 555, 1111 });\n yield return Tuple.Create(14, new[] { 1, 2, 3, 4, 5, 11, 22, 44, 55, 111, 444, 555, 1111, 4444 });\n yield return Tuple.Create(15, new[] { 1, 2, 3, 4, 5, 11, 22, 44, 55, 111, 444, 555, 1111, 4444, 11111 });\n yield return Tuple.Create(115, new[] { 1, 2, 3, 4, 5, 11, 22, 44, 55, 111, 444, 555, 1111, 4444, 11111 });\n }\n }\n}\n</code></pre>\n\n<p>Note that I used int instead of string in the tests but it should affect anything anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T11:55:54.513",
"Id": "449201",
"Score": "1",
"body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T08:39:03.657",
"Id": "230529",
"ParentId": "220254",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220264",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T21:31:40.183",
"Id": "220254",
"Score": "6",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Take N elements from List of Lists"
} | 220254 |
<p>I'm implementing a basic array data structure with basic functionalities. </p>
<pre><code>#include <iostream>
#include "barray.h"
BArray::BArray(int init_size)
{
b_array = new int[init_size]();
array_size = init_size;
}
BArray::BArray(int init_size, int init_val)
{
b_array = new int[init_size];
array_size = init_size;
for(int i = 0; i < init_size; ++i)
b_array[i] = init_val;
}
BArray::BArray(const BArray & rhs)
{
array_size = rhs.array_size;
b_array = new int[array_size];
for(int i = 0; i < array_size; ++i)
b_array[i] = rhs[i];
}
BArray::~BArray()
{
delete [] b_array;
}
int BArray::getSize() const
{
return array_size;
}
int BArray::operator[](int index) const
{
return *(b_array + index);
}
int& BArray::operator[](int index)
{
return *(b_array + index);
}
BArray& BArray::operator=(const BArray& rhs)
{
if(this == &rhs)
return *this;
array_size = rhs.array_size;
delete [] b_array;
b_array = new int[array_size];
for(int i = 0; i < array_size; ++i)
b_array[i] = rhs[i];
return *this;
}
std::ostream& operator<< (std::ostream& out, const BArray& arr)
{
for(int i = 0; i < arr.array_size; ++i)
out << arr[i] << " ";
return out;
}
</code></pre>
<p>And the header file</p>
<pre><code>#ifndef BARRAY_H
#define BARRAY_H
class BArray
{
public:
BArray() = delete; //Declare the default constructor as deleted to avoid
//declaring an array without specifying its size.
BArray(const int init_size);
BArray(int init_size, int init_val); //Constructor that initializes the array with init_val.
BArray(const BArray & rhs); //Copy constructor.
~BArray(); //Destructor.
int operator[](int index) const; //[] operator overloading for "reading" index value.
int& operator[](int index); //[] operator overloading for "setting" index value.
BArray& operator=(const BArray& rhs); //Copy assignment operator.
//Utility functions.
int getSize() const;
//Friend functions.
friend std::ostream& operator<< (std::ostream& out, const BArray& arr);
private:
int* b_array;
int array_size;
};
#endif // BARRAY_H
</code></pre>
<p>Can you please give me a feedback on what is missing, what is wrong and what is good?
I mean in terms of memory allocation, operators overloading, etc...</p>
<p>Is this is the best way this class can be implemented?</p>
<p>Edit:
This is how I tested the code</p>
<pre><code>#include <iostream>
#include "barray.h"
int main()
{
//BArray invalid_instance; //Default constructor is deleted.
BArray barr(5); //Declaring an array of size 5, this initializes all values to zeros.
std::cout << barr[2] << std::endl;
barr[2] = 15; //Setting index 2 to 15.
std::cout << barr[2] << std::endl; //Reading out value of index 2.
BArray anotherArray(barr); //Copy constructor.
std::cout << anotherArray[2] << std::endl;
anotherArray[3] = 8;
BArray assignArray = anotherArray; //Copy assignment operator.
std::cout << assignArray[2] << std::endl;
std::cout << assignArray; //Printing out array values.
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T23:00:46.553",
"Id": "425555",
"Score": "1",
"body": "Do you have some test code that you add to the question to show us how the class is used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T23:02:38.870",
"Id": "425556",
"Score": "1",
"body": "Yes sure. I will add it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T09:46:03.187",
"Id": "425593",
"Score": "0",
"body": "How's that a \"static\" array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:34:36.243",
"Id": "425662",
"Score": "0",
"body": "@L.F. By static I mean not dynamic/resizeable."
}
] | [
{
"body": "<p>I would allow the default constructor and make it default to a 0 size array. with the optimization that b_array is a <code>nullptr</code>.</p>\n\n<p>Then you can also add move constructors/assignment. Where the moved-from object gets a <code>b_array = nullptr;</code></p>\n\n<p>On of the basic functionalities of a container is iteration. So you should add a <code>begin()</code> and <code>end()</code> that return the <code>b_array</code> and <code>b_array+array_size</code> resp. Don't forget the const versions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T08:20:13.327",
"Id": "220271",
"ParentId": "220258",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>The default-ctor won't be implicitly declared as there are user-declared ctors.</p></li>\n<li><p>When you can define a default-ctor with reasonable behavior, consider doing so.<br>\nIf you use in-class initializers to <code>0</code> resp. <code>nullptr</code> for the members, it can even be explicitly defaulted, making the class trivially default-constructible.</p></li>\n<li><p>Top-level <code>const</code> on arguments in a function declaration is just useless clutter.</p></li>\n<li><p>Consider investing in move-semantics to avoid costly copies.</p></li>\n<li><p>If the allocation in one of the ctors throws, your dtor will be called on indeterminate members, which is <strong>undefined behavior</strong>.<br>\nUse mem-initialisers or pre-init <code>b_array</code> to <code>nullptr</code> to fix it.</p></li>\n<li><p>Your copy-assignment also has pathological behavior in the face of exceptions. That aside, it pessimises the common case in favor of self-assignment. Read up on the copy-and-swap idiom. As a bonus, you get an efficient <code>swap()</code> out of it.</p></li>\n<li><p>Using a <code>std::unique_ptr</code> for the member would allow you to significantly simplify the memory-handling.</p></li>\n<li><p>Keep to the common interface-conventions. Failure to follow it makes generic code nigh impossible. Specifically, <code>.getSize()</code> should be <code>.size()</code>.</p></li>\n<li><p>You are missing most of the expected interface, specifically iterators (normal, constant, reverse, related typedefs, <code>.data()</code>).</p></li>\n<li><p>Better names for the private members would be <code>array</code> and <code>count</code>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T10:03:49.610",
"Id": "220277",
"ParentId": "220258",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220277",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:35:56.443",
"Id": "220258",
"Score": "5",
"Tags": [
"c++",
"array",
"memory-management"
],
"Title": "A static array implementation in C++"
} | 220258 |
<h1>What I want to know</h1>
<p>I am writing a ML model called U-Net with Python (and TensorFlow). My question is not about the machine learning or Tensorflow, I want to know the best structure of the code.</p>
<p>I write some code as my hobby and I've never written code as work, so I do not know what is the "good" code.</p>
<h1>My code</h1>
<p>I made two files</p>
<ul>
<li>main.py</li>
<li>model.py</li>
</ul>
<p>The main.py has functions that load data and pass them to the model in model.py. The model.py has a class that represent the ML model and it contains not only the model structure but also a method to train.</p>
<p>The main process of these code is the training method in the model.py, so in main.py, I call this method from the model.py. I feel that this code structure is not correct, that is, I think the main process (training method) should be contained in the main.py, not in the model.py.</p>
<p>I want some advice how I should (or not) change my code.</p>
<p>main.py</p>
<pre class="lang-py prettyprint-override"><code>import argparse
import os
import glob
import random
import math
import numpy as np
from PIL import Image
import model
def get_parser():
"""
Set hyper parameters for training UNet.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--epoch', type=int, default=100)
parser.add_argument('-lr', '--learning_rate', type=float, default=0.0001)
parser.add_argument('-tr', '--train_rate', type=float, default=0.8, help='ratio of training data')
parser.add_argument('-b', '--batch_size', type=int, default=20)
parser.add_argument('-l2', '--l2', type=float, default=0.05, help='L2 regularization')
return parser
def load_data(image_dir, seg_dir, n_class, train_val_rate, onehot=True):
"""
load images and segmented images.
Parameters
==========
image_dir: string
the directory of the raw images.
seg_dir: string
the directory of the segmented images.
n_class: int
the number of classes
train_val_rate: float
the ratio of training data to the validation data
onehot: bool
Returns
=======
the tuple.((training image, training segmented image), (validation image, validation segmented image))
training/validation (segmented) images are the list of np.ndarray whose shape is (128, 128, 3) (row image)
and (128, 128, n_class) (segmented image)
"""
row_img = []
segmented_img = []
images = os.listdir(image_dir)
random.shuffle(images)
for idx, img in enumerate(images):
if img.endswith('.png') or img.endswith('.jpg'):
split_name = os.path.splitext(img)
img = Image.open(os.path.join(image_dir, img))
if seg_dir != '':
seg = Image.open(os.path.join(seg_dir, split_name[0] + '-seg' + split_name[1]))
seg = seg.resize((128, 128))
seg = np.asarray(seg, dtype=np.int16)
else:
seg = None
img = img.resize((128, 128))
img = np.asarray(img, dtype=np.float32)
img, seg = preprocess(img, seg, n_class, onehot=onehot)
row_img.append(img)
segmented_img.append(seg)
train_data = row_img[:int(len(row_img)*train_val_rate)], segmented_img[:int(len(row_img)*train_val_rate)]
validation_data = row_img[int(len(row_img) * train_val_rate):], segmented_img[int(len(row_img) * train_val_rate):]
return train_data, validation_data
def generate_data(input_images, teacher_images, batch_size):
"""
generate the pair of the raw image and segmented image.
Parameters
==========
inputs_images: list of the np.array
teacher_image: list of the np.array or None
batch_size: int
Returns
=======
"""
batch_num = math.ceil(len(input_images) / batch_size)
input_images = np.array_split(input_images, batch_num)
if np.any(teacher_images == None):
teacher_images = np.zeros(batch_num)
else:
teacher_images = np.array_split(teacher_images, batch_num)
for i in range(batch_num):
yield input_images[i], teacher_images[i]
def preprocess(img, seg, n_class, onehot):
if onehot and seg is not None:
identity = np.identity(n_class, dtype=np.int16)
seg = identity[seg]
return img / 255.0, seg
if __name__ == '__main__':
parser = get_parser().parse_args()
unet = model.UNet(classes=2)
unet.train(parser)
</code></pre>
<p>model.py</p>
<pre class="lang-py prettyprint-override"><code>import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import main
class UNet:
def __init__(self, classes):
self.IMAGE_DIR = './dataset/raw_images'
self.SEGMENTED_DIR = './dataset/segmented_images'
self.VALIDATION_DIR = './dataset/validation'
self.classes = classes
self.X = tf.placeholder(tf.float32, [None, 128, 128, 3])
self.y = tf.placeholder(tf.int16, [None, 128, 128, self.classes])
self.is_training = tf.placeholder(tf.bool)
@staticmethod
def conv2d(
inputs, filters, kernel_size=3, activation=tf.nn.relu, l2_reg=None,
momentum=0.9, epsilon=0.001, is_training=False,
):
"""
convolutional layer. If the l2_reg is a float number, L2 regularization is imposed.
Parameters
----------
inputs: tf.Tensor
filters: Non-zero positive integer
The number of the filter
activation:
The activation function. The default is tf.nn.relu
l2_reg: None or float
The strengthen of the L2 regularization
is_training: tf.bool
The default is False. If True, the batch normalization layer is added.
momentum: float
The hyper parameter of the batch normalization layer
epsilon: float
The hyper parameter of the batch normalization layer
Returns
-------
layer: tf.Tensor
"""
regularizer = tf.contrib.layers.l2_regularizer(scale=l2_reg) if l2_reg is not None else None
layer = tf.layers.conv2d(
inputs=inputs,
filters=filters,
kernel_size=kernel_size,
padding='SAME',
activation=activation,
kernel_regularizer=regularizer
)
if is_training is not None:
layer = tf.layers.batch_normalization(
inputs=layer,
axis=-1,
momentum=momentum,
epsilon=epsilon,
center=True,
scale=True,
training=is_training
)
return layer
@staticmethod
def trans_conv(inputs, filters, activation=tf.nn.relu, kernel_size=2, strides=2, l2_reg=None):
"""
transposed convolution layer.
Parameters
----------
inputs: tf.Tensor
filters: int
the number of the filter
activation:
the activation function. The default function is the ReLu.
kernel_size: int
the kernel size. Default = 2
strides: int
strides. Default = 2
l2_reg: None or float
the strengthen of the L2 regularization.
Returns
-------
layer: tf.Tensor
"""
regularizer = tf.contrib.layers.l2_regularizer(scale=l2_reg) if l2_reg is not None else None
layer = tf.layers.conv2d_transpose(
inputs=inputs,
filters=filters,
kernel_size=kernel_size,
strides=strides,
kernel_regularizer=regularizer
)
return layer
@staticmethod
def pooling(inputs):
return tf.layers.max_pooling2d(inputs=inputs, pool_size=2, strides=2)
def UNet(self, is_training, l2_reg=None):
"""
UNet structure.
Parameters
----------
l2_reg: None or float
The strengthen of the L2 regularization.
is_training: tf.bool
Whether the session is for training or validation.
Returns
-------
outputs: tf.Tensor
"""
conv1_1 = self.conv2d(self.X, filters=64, l2_reg=l2_reg, is_training=is_training)
conv1_2 = self.conv2d(conv1_1, filters=64, l2_reg=l2_reg, is_training=is_training)
pool1 = self.pooling(conv1_2)
conv2_1 = self.conv2d(pool1, filters=128, l2_reg=l2_reg, is_training=is_training)
conv2_2 = self.conv2d(conv2_1, filters=128, l2_reg=l2_reg, is_training=is_training)
pool2 = self.pooling(conv2_2)
conv3_1 = self.conv2d(pool2, filters=256, l2_reg=l2_reg, is_training=is_training)
conv3_2 = self.conv2d(conv3_1, filters=256, l2_reg=l2_reg, is_training=is_training)
pool3 = self.pooling(conv3_2)
conv4_1 = self.conv2d(pool3, filters=512, l2_reg=l2_reg, is_training=is_training)
conv4_2 = self.conv2d(conv4_1, filters=512, l2_reg=l2_reg, is_training=is_training)
pool4 = self.pooling(conv4_2)
conv5_1 = self.conv2d(pool4, filters=1024, l2_reg=l2_reg)
conv5_2 = self.conv2d(conv5_1, filters=1024, l2_reg=l2_reg)
concat1 = tf.concat([conv4_2, self.trans_conv(conv5_2, filters=512, l2_reg=l2_reg)], axis=3)
conv6_1 = self.conv2d(concat1, filters=512, l2_reg=l2_reg)
conv6_2 = self.conv2d(conv6_1, filters=512, l2_reg=l2_reg)
concat2 = tf.concat([conv3_2, self.trans_conv(conv6_2, filters=256, l2_reg=l2_reg)], axis=3)
conv7_1 = self.conv2d(concat2, filters=256, l2_reg=l2_reg)
conv7_2 = self.conv2d(conv7_1, filters=256, l2_reg=l2_reg)
concat3 = tf.concat([conv2_2, self.trans_conv(conv7_2, filters=128, l2_reg=l2_reg)], axis=3)
conv8_1 = self.conv2d(concat3, filters=128, l2_reg=l2_reg)
conv8_2 = self.conv2d(conv8_1, filters=128, l2_reg=l2_reg)
concat4 = tf.concat([conv1_2, self.trans_conv(conv8_2, filters=64, l2_reg=l2_reg)], axis=3)
conv9_1 = self.conv2d(concat4, filters=64, l2_reg=l2_reg)
conv9_2 = self.conv2d(conv9_1, filters=64, l2_reg=l2_reg)
outputs = self.conv2d(conv9_2, filters=self.classes, kernel_size=1, activation=None)
return outputs
def train(self, parser):
"""
training operation
argument of this function are given by functions in main.py
Parameters
----------
parser:
the paser that has some options
"""
epoch = parser.epoch
l2 = parser.l2
batch_size = parser.batch_size
train_val_rate = parser.train_rate
output = self.UNet(l2_reg=l2, is_training=self.is_training)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.y, logits=output))
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
train_ops = tf.train.AdamOptimizer(parser.learning_rate).minimize(loss)
init = tf.global_variables_initializer()
saver = tf.train.Saver(max_to_keep=100)
all_train, all_val = main.load_data(self.IMAGE_DIR, self.SEGMENTED_DIR, n_class=2, train_val_rate=train_val_rate)
with tf.Session() as sess:
init.run()
for e in range(epoch):
data = main.generate_data(*all_train, batch_size)
val_data = main.generate_data(*all_val, len(all_val[0]))
for Input, Teacher in data:
sess.run(train_ops, feed_dict={self.X: Input, self.y: Teacher, self.is_training: True})
ls = loss.eval(feed_dict={self.X: Input, self.y: Teacher, self.is_training: None})
for val_Input, val_Teacher in val_data:
val_loss = loss.eval(feed_dict={self.X: val_Input, self.y: val_Teacher, self.is_training: None})
print(f'epoch #{e + 1}, loss = {ls}, val loss = {val_loss}')
if e % 100 == 0:
saver.save(sess, f"./params/model_{e + 1}epochs.ckpt")
self.validation(sess, output)
def validation(self, sess, output):
val_image = main.load_data(self.VALIDATION_DIR, '', n_class=2, train_val_rate=1)[0]
data = main.generate_data(*val_image, batch_size=1)
for Input, _ in data:
result = sess.run(output, feed_dict={self.X: Input, self.is_training: None})
break
result = np.argmax(result[0], axis=2)
ident = np.identity(3, dtype=np.int8)
result = ident[result]*255
plt.imshow((Input[0]*255).astype(np.int16))
plt.imshow(result, alpha=0.2)
plt.show()
</code></pre>
<p>The entire code are in my GitHub repository (<a href="https://github.com/Hayashi-Yudai/ML_models" rel="nofollow noreferrer">https://github.com/Hayashi-Yudai/ML_models</a>)</p>
| [] | [
{
"body": "<ul>\n<li><p>This is clean code for a hobbyist. ML code in particular can end up being a procedural mess, just carrying out one imported function after another, but this is quite good.</p></li>\n<li><p>It's great that you have docstrings with explanations of the arguments, but the explanations of the functions/methods themselves are a little sparse. The odd comment would help a lot too.</p></li>\n<li><p>Try to follow PEP8. It's the standard style for all Python code and is generally followed by all Python programmers (4 spaces for indent, 2 spaces between functions, etc).</p></li>\n<li><p>Immediately I see that you're importing <code>model</code> in <code>main</code> and <code>main</code> in <code>model</code>. Imports should follow a hierarchy with no cycles. i.e. if A imports from B imports from C, C should never import from A, but it's ok if A imports directly from C.</p></li>\n<li><p>Typically, a file called <code>main</code>, <code>run</code>, <code>execute</code> or whatever will import other worker functions from elsewhere, then handle calling them in the correct way. This often means argument parsing is contained in the <code>main</code> file but not a lot else. Given that you have a lot of logic for generating and sorting data, I would separate this out.</p></li>\n<li><p>When comparing a <code>var</code> to <code>None</code>, use the idioms <code>var is None</code> or <code>var is not None</code>.</p></li>\n<li><p>Try to use proper paths with os.path rather than just strings like <code>'/dataset/segmented_images'</code>. This means you can run the script from anywhere and still find the files/directories you want.</p></li>\n<li><p>You check <code>seg_dir</code> is not an empty string, I would be more explicit and have it either be <code>None</code> or the full path described above. Explicitly assigning something as <code>None</code> removes ambiguity. Let's say for example a path is where you are, does the path being <code>''</code> mean you've found it or not? If the path is <code>None</code> however, obviously you haven't found it.</p></li>\n<li><p>Frequently, your variable names are exactly the same as the keyword arguments. This is fine, except the names are often fairly non-descript: <code>inputs</code>, <code>filters</code> etc. Otherwise, variable names are quite good (concise and clear).</p></li>\n<li><p>You <code>enumerate()</code> over images in <code>load_data()</code> but don't use the index, just loop over it with a <code>for</code> loop.</p></li>\n<li><p>You don't use <code>glob</code> as an import, nor <code>activation</code> as an argument (in <code>trans_conv()</code>).</p></li>\n<li><p><code>UNet()</code> would be a lot nicer with loops to remove the repeated code and unnecessary variable assignments. I would suggest one loop for pre-training and another for post.</p></li>\n<li><p>In <code>load_data()</code>, caching the result of <code>int(len(row_img) * train_val_rate</code> would make for much cleaner code, and would tell you what that index actually represents (with a good variable name).</p></li>\n<li><p>You make quite a few assumptions that the code will work as intended, far too hopeful! As an example, say you generate an empty list; on some condition you fill the list; then you assume the list has been filled and loop over it. This is fine if the condition is fulfilled, but if it's not then the program will break. Take a look at <code>load_data()</code> and consider how easy it would be to find if there was a problem with how <code>row_img</code> is (or isn't) being filled.</p></li>\n</ul>\n\n<p>That's how the code <em>looks</em>; I can't really test how it <em>runs</em> without some sample data and expected in/outputs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T00:08:50.777",
"Id": "425677",
"Score": "1",
"body": "Thank you for your great advice. I'll fix correct the code referring to your suggestions. And I'm sorry for not puting a link of entire code, my codes are in my GitHub repository. https://github.com/Hayashi-Yudai/ML_models"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T13:19:38.063",
"Id": "220286",
"ParentId": "220259",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220286",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-14T22:47:27.820",
"Id": "220259",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"image",
"numpy",
"tensorflow"
],
"Title": "U-Net: A TensorFlow model"
} | 220259 |
<p>I've been asked to improve the modular decomposition of the main by moving as many lines of code out of main as possible, but i have no idea how i should do this</p>
<pre><code># writes the number of lines then each line as a string.
def write_data_to_file(aFile)
aFile.puts('5')
end
# reads in each line.
def read_data_from_file(aFile)
puts aFile.gets
end
# writes data to a file then reads it in and prints each line as it reads
def main
aFile = File.new("mydata.txt", "w") # open for writing
if aFile # if nil this test will be false
write_data_to_file(aFile)
aFile.close
else
puts "Unable to open file to write!"
end
aFile = File.new("mydata.txt", "r") # open for reading
if aFile # if nil this test will be false
read_data_from_file(aFile)
aFile.close
else
puts "Unable to open file to read!"
end
end
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T06:22:40.673",
"Id": "425572",
"Score": "1",
"body": "Welcome to Code Review. Try putting a newline after the closing `\\`\\`\\``. The title should reflect what the code is to achieve, see [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T00:29:09.257",
"Id": "429426",
"Score": "0",
"body": "hmm, I would move both read and write blocks in main to their own methods."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T05:11:50.310",
"Id": "220266",
"Score": "1",
"Tags": [
"ruby",
"file"
],
"Title": "Ruby exercise in writing and reading a file"
} | 220266 |
<p>I'm fairly new to C++, so as a learning exercise for how to use various simple data structures efficiently and what I should and shouldn't avoid, I wrote the following code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <queue>
void primitive_test() {
unsigned long l = 20000000;
std::unordered_map<int, int> map;
std::vector<int> vec1;
std::vector<int> vec2;
std::vector<int> vec3;
std::deque<int> que;
int *array = new int[l];
clock_t begin;
begin = clock();
for (int i = 0; i < l; i++) {
map[i] = i;
}
std::cout << "std::unordered_map: " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
vec1.push_back(i);
}
std::cout << "std::vector (no reserve): " << clock() - begin << '\n';
begin = clock();
vec2.reserve(l);
for (int i = 0; i < l; i++) {
vec2.push_back(i);
}
std::cout << "std::vector (reserve): " << clock() - begin << '\n';
begin = clock();
vec3.resize(l);
for (int i = 0; i < l; i++) {
vec3[i] = i;
}
std::cout << "std::vector (resize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
que.push_back(i);
}
std::cout << "std::deque: " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
que.emplace_back(i);
}
std::cout << "std::deque (emplace): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
array[i] = i;
}
std::cout << "array: " << clock() - begin << '\n';
}
void object_test() {
unsigned long l = 20000000;
std::vector<std::tuple<int>> vec1;
std::vector<std::tuple<int>> vec2;
std::vector<std::tuple<int>> vec3;
std::vector<std::tuple<int>> vec4;
std::vector<std::tuple<int>> vec5;
std::vector<std::tuple<int>> vec6;
std::deque<std::tuple<int>> que;
auto *array = new std::tuple<int>[l];
clock_t begin;
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
vec1.push_back(p);
}
std::cout << "std::vector (no reserve): " << clock() - begin << '\n';
begin = clock();
vec2.reserve(l);
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
vec2.push_back(p);
}
std::cout << "std::vector (reserve): " << clock() - begin << '\n';
begin = clock();
vec3.resize(l);
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
vec3[i] = p;
}
std::cout << "std::vector (resize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
vec4.emplace_back(i);
}
std::cout << "std::vector (emplace, no reserve): " << clock() - begin << '\n';
begin = clock();
vec5.reserve(l);
for (int i = 0; i < l; i++) {
vec5.emplace_back(i);
}
std::cout << "std::vector (emplace, reserve): " << clock() - begin << '\n';
//takes too long - is there a faster way to emplace at a particular position?
// begin = clock();
// vec6.resize(l);
// for(int i = 0; i < l; i++){
// vec6.emplace(vec6.begin()+i,i);
// }
// std::cout << "std::vector (emplace, resize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
que.push_back(p);
}
std::cout << "std::deque: " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
que.emplace_back(i);
}
std::cout << "std::deque (emplace): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
array[i] = p;
}
std::cout << "array: " << clock() - begin << '\n';
}
int main() {
std::cout << "\nTesting primitives.\n";
primitive_test();
std::cout << "\nTesting objects.\n";
object_test();
}
</code></pre>
<p>The results of running the code on my machine are a bit surprising to me, which leads me to believe that I've perhaps made a mistake or am not treating each case fairly somehow (my comments in // below):</p>
<pre><code>Testing primitives.
std::unordered_map: 8231979 //wow!
std::vector (no reserve): 402252
std::vector (reserve): 328177 //why is reserving so much slower than resizing?
std::vector (resize): 132258
std::deque: 320600
std::deque (emplace): 363182 //emplacing is a bit slower?
array: 64457 //should vector be so much slower?
Testing objects.
std::vector (no reserve): 1801645
std::vector (reserve): 551038
std::vector (resize): 1100332 //about twice the time of the above?
std::vector (emplace, no reserve): 1979130 //emplacing is slower than reserving?
std::vector (emplace, reserve): 675151
//is there a way to emplace a particular position in a vector if we've already made room for it?
std::deque: 579424 //faster than array?
std::deque (emplace): 693743 //emplacing is slower?
array: 620844
Process finished with exit code 0
</code></pre>
<p>Also, here is my CMakeLists:</p>
<pre><code>cmake_minimum_required(VERSION 3.12)
project(maptest)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_FLAGS_RELEASE "-O2")
add_executable(maptest main.cpp)
</code></pre>
<p>I am running this code on a Predator Helios 300 laptop. </p>
<p>Is there any way that I can improve this benchmark? Have I done something incorrectly/inefficiently or used a function that I shouldn't have used? Is it just that the methodology/approach that I'm using for testing is flawed?</p>
<p><strong>Edit:</strong><br>
I added tests for initializing the vector length in the constructor. After JVApen's comment below, I realized I was doing a debug build. I also realized, upon further looking, that I was being a bit unfair to the vectors since I was timing their resize + reserve functions. I put those before the start of the clock and changed it to a release build and got the following code and results (the vector emplace+resize case still takes a really long time to run):</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <queue>
void primitive_test() {
unsigned long l = 20000000;
std::unordered_map<int, int> map;
std::vector<int> vec1;
std::vector<int> vec2;
std::vector<int> vec3;
std::vector<int> vec4(l);
std::deque<int> que;
int *array = new int[l];
clock_t begin;
begin = clock();
for (int i = 0; i < l; i++) {
map[i] = i;
}
std::cout << "std::unordered_map: " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
vec1.push_back(i);
}
std::cout << "std::vector (no reserve): " << clock() - begin << '\n';
vec2.reserve(l);
begin = clock();
for (int i = 0; i < l; i++) {
vec2.push_back(i);
}
std::cout << "std::vector (reserve): " << clock() - begin << '\n';
vec3.resize(l);
begin = clock();
for (int i = 0; i < l; i++) {
vec3[i] = i;
}
std::cout << "std::vector (resize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
vec4[i] = i;
}
std::cout << "std::vector (initialize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
que.push_back(i);
}
std::cout << "std::deque: " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
que.emplace_back(i);
}
std::cout << "std::deque (emplace): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
array[i] = i;
}
std::cout << "array: " << clock() - begin << '\n';
}
void object_test() {
unsigned long l = 20000000;
std::vector<std::tuple<int>> vec1;
std::vector<std::tuple<int>> vec2;
std::vector<std::tuple<int>> vec3;
std::vector<std::tuple<int>> vec4(l);
std::vector<std::tuple<int>> vec5;
std::vector<std::tuple<int>> vec6;
std::vector<std::tuple<int>> vec7;
std::vector<std::tuple<int>> vec8(l);
std::deque<std::tuple<int>> que;
auto *array = new std::tuple<int>[l];
clock_t begin;
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
vec1.push_back(p);
}
std::cout << "std::vector (no reserve): " << clock() - begin << '\n';
vec2.reserve(l);
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
vec2.push_back(p);
}
std::cout << "std::vector (reserve): " << clock() - begin << '\n';
vec3.resize(l);
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
vec3[i] = p;
}
std::cout << "std::vector (resize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
vec4.push_back(p);
}
std::cout << "std::vector (initialize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
vec5.emplace_back(i);
}
std::cout << "std::vector (emplace, no reserve): " << clock() - begin << '\n';
vec6.reserve(l);
begin = clock();
for (int i = 0; i < l; i++) {
vec6.emplace_back(i);
}
std::cout << "std::vector (emplace, reserve): " << clock() - begin << '\n';
//takes too long - is there a faster way to emplace at a particular position?
// vec7.resize(l);
// begin = clock();
// for(int i = 0; i < l; i++){
// vec7.emplace(vec6.begin()+i,i);
// }
// std::cout << "std::vector (emplace, resize): " << clock() - begin << '\n';
begin = clock();
for(int i = 0; i < l; i++){
vec8.emplace_back(i);
}
std::cout << "std::vector (emplace, initialize): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
que.push_back(p);
}
std::cout << "std::deque: " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
que.emplace_back(i);
}
std::cout << "std::deque (emplace): " << clock() - begin << '\n';
begin = clock();
for (int i = 0; i < l; i++) {
std::tuple<int> p(i);
array[i] = p;
}
std::cout << "array: " << clock() - begin << '\n';
}
int main() {
std::cout << "\nTesting primitives.\n";
primitive_test();
std::cout << "\nTesting objects.\n";
object_test();
}
</code></pre>
<pre><code>Testing primitives.
std::unordered_map: 1690288
std::vector (no reserve): 134839
std::vector (reserve): 64447
std::vector (resize): 11793
std::vector (initialize): 9261
std::deque: 61789
std::deque (emplace): 71425
array: 101057
Testing objects.
std::vector (no reserve): 68414
std::vector (reserve): 42209
std::vector (resize): 9928
std::vector (initialize): 112300
std::vector (emplace, no reserve): 101546
std::vector (emplace, reserve): 49651
std::vector (emplace, initialize): 112602
std::deque: 47545
std::deque (emplace): 47611
array: 9000
Process finished with exit code 0
</code></pre>
<p>It's pretty surprising to see vectors beat out arrays when resizing, especially when using primitives! Also, it also seems a bit odd that using a tuple with one int makes it run faster than just using an int directly. I guess emplace must also add some overhead too, since all the emplace cases are slower than the non-emplace cases. Also seems kind of strange that passing in a length to the constructor is actually slower than just telling the vector nothing at all and resizing later when using objects, while the reverse is true if I use primitives instead.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T06:18:08.040",
"Id": "425569",
"Score": "1",
"body": "Saying you're running on a *Predator Helios 300 laptop* is like saying you're running it on a *HAL 9000*. I.e. it doesn't tell people anything about the actual performance of your computer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T06:18:38.877",
"Id": "425571",
"Score": "0",
"body": "Welcome to Code Review! You could tag your question [tag:beginner] and [tag:stl], an make the title reflect that you are doing an STL micro-benchmark. There is no need to repeat the C++ tag in the title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T06:57:41.557",
"Id": "425577",
"Score": "0",
"body": "Double checking: Did you build as release build?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T11:21:47.903",
"Id": "425595",
"Score": "0",
"body": "@yuri Sorry, I didn't know that it wouldn't be helpful. I thought it would be best to provide as much relevant information as I could think of up front."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T11:23:51.357",
"Id": "425596",
"Score": "0",
"body": "@greybeard I added the tags."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T11:30:26.640",
"Id": "425597",
"Score": "1",
"body": "@JVApen I checked and it turns out I was doing a debug build. That solves a few of my problems! Thank you. There are still a few things that seem odd; I'll edit the question accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T12:32:28.483",
"Id": "425602",
"Score": "0",
"body": "As @yuri pointed out Predator Helios 300 doesn't tell us much. Could you tell us the processor type and speed, the amount of memory in the system and what operating system."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:16:59.540",
"Id": "425630",
"Score": "0",
"body": "I'm fairly certain that something about the measurements is off. Was the laptop running at its limit? If so, other processes might have siphoned some of the CPU power in some places.\nI say this because the vector initialize and vector resize cases should have the same performance. In both cases, when you start the timer, you have an initialized vector with the necessary memory. Also, the raw array should always be the quickest, since vector uses that internally and queue has even more overhead.\nDid you repeat these tests multiple times with comparable results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T19:34:56.050",
"Id": "425658",
"Score": "0",
"body": "`std::cout << \"std::vector (reserve): \" << clock() - begin << '\\n';` Putting the call to `clock()` here means you are probably timing the cost of the print statement as well. Put `auto end = clock();` on its own line before you start printing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T02:37:03.287",
"Id": "425682",
"Score": "0",
"body": "@pacmaninbw \nProcessor type: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz, \nMemory: 16 GB,\nOS: Ubuntu 18.04.2 LTS x86_64"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T04:52:57.147",
"Id": "425684",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T05:05:10.367",
"Id": "425686",
"Score": "0",
"body": "@Heslacher Ok, sorry. There are still some concerns I have regarding the quality of the running times I got from my code even though the quality of the code is improved. I'd also still like to ask about how to efficiently emplace at a particular position in a vector, since that's something that, in my current way of doing it, seems to take an extremely long time relative to the other operations I tested. If this is something I can ask about on Code Review, should I just make a new question for that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T05:33:26.817",
"Id": "425687",
"Score": "0",
"body": "I would suggest to wait at least one more day for more answers to your question. Afterwards asking a new question would be the way to go."
}
] | [
{
"body": "<p>Side note: this is a code review site, so I'm going to at least start by reviewing your actual code. I might try to add a few points about what you tried to investigate later, but for now this is mostly just about the code itself.</p>\n\n<h1>Don't Repeat Yourself</h1>\n\n<p>Right now, your code contains main repetitions of nearly identical code:</p>\n\n<pre><code>begin = clock();\nfor (int i = 0; i < l; i++) {\n map[i] = i;\n}\nstd::cout << \"std::unordered_map: \" << clock() - begin << '\\n';\n\nbegin = clock();\nfor (int i = 0; i < l; i++) {\n vec1.push_back(i);\n}\nstd::cout << \"std::vector (no reserve): \" << clock() - begin << '\\n';\n\nvec2.reserve(l);\nbegin = clock();\nfor (int i = 0; i < l; i++) {\n vec2.push_back(i);\n}\nstd::cout << \"std::vector (reserve): \" << clock() - begin << '\\n';\n</code></pre>\n\n<p>As a starting point, I'd try to refactor that to eliminate at least some of the repetition. I'd start with a little \"timer\" template, something on this general order:</p>\n\n<pre><code>template <class F>\nvoid timer(std::string const &label, F f) {\n auto begin = clock();\n f();\n std::cout << label << clock() - begin() << '\\n';\n}\n</code></pre>\n\n<p>Then I'd use that for each of the individual tests:</p>\n\n<pre><code>void primitive_test() {\n // ...\n\n timer(\"std::unordered_map:\", [&]{ for (int i=0; i<l; i++) map[i] = i; } );\n\n timer(\"std::vector (no reserve): \", [&]{ for (int i=0; i<l; i++) vec1.push_back(i); }); \n\n vec2.reserve(l);\n timer(\"std::vector (reserve): \", [&]{ for (int i=0; i<l; i++) vec2.push_back(i); });\n</code></pre>\n\n<h1>Improve Readability</h1>\n\n<p>Right now, the output isn't very readable. First of all, all the numbers immediately follow the labels, so they're not aligned with each other. When you have a different number of digits, it's not always easy to be sure whether one might be 10 times larger than another. So I'd change the code to display the output so the numbers are aligned with each other:</p>\n\n<pre><code>std::cout << std::setw(30) << label << std::setw(10) << clock() - begin << \"\\n\";\n</code></pre>\n\n<p>Note that by consolidating the code as we did above, we now only have to make this change in one place.</p>\n\n<p>Second, I'd try to format the numbers as the user would normally expect them to look based on the configured locale. We can do that by adding code like this at the beginning of <code>main</code>:</p>\n\n<pre><code>std::cout.imbue(std::locale(\"\"));\n</code></pre>\n\n<p>With those changes, we get output that I find much more readable and easier to compare, like this:</p>\n\n<pre><code>Testing primitives.\n std::unordered_map: 2,240,000\n std::vector (no reserve): 130,000\n std::vector (reserve): 60,000\n std::vector (resize): 10,000\n std::vector (initialize): 10,000\n std::deque: 50,000\n std::queue (emplace): 50,000\n array: 50,000\n</code></pre>\n\n<h1>Improve Timing</h1>\n\n<p><code>clock()</code> isn't really a great way of timing things. The precision varies (widely) and getting results in a meaningful (real-world) unit is somewhat painful. I'd prefer to use something like <code>std::chrono::high_resolution_clock</code>. Again, having consolidated all the timing in one place makes it much easier to institute this change:</p>\n\n<pre><code>template <class F>\nvoid timer(std::string const &label, F f) {\n using namespace std::chrono;\n auto begin = high_resolution_clock::now();\n f();\n auto end = high_resolution_clock::now();\n std::cout << std::setw(30) << label \n << std::setw(10) << duration_cast<milliseconds>(end-begin).count() << \"ms\\n\";\n}\n</code></pre>\n\n<p>Now we get output like this:</p>\n\n<pre><code>Testing primitives.\n std::unordered_map: 2,266ms\n std::vector (no reserve): 126ms\n std::vector (reserve): 60ms\n std::vector (resize): 13ms\n std::vector (initialize): 10ms\n std::deque: 45ms\n std::queue (emplace): 50ms\n array: 41ms\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T18:59:07.200",
"Id": "425654",
"Score": "2",
"body": "All the `clock() - begin` timing calculations need to be done _before_ any output is started or generated, otherwise the time spent doing the output can effect the results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T22:32:03.053",
"Id": "425673",
"Score": "0",
"body": "@1201ProgramAlarm: You certainly don't want to time *while* you're producing output.As long as the I/O is separated from the computation, though, I haven't seen interleaving the I/O between the timed sections making a significant difference in timing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T23:06:08.947",
"Id": "425675",
"Score": "0",
"body": "That's what I meant - each timing section needs to have the time computed before you start the output for that section. I see I wasn't clear on that. Since the elapsed time is computed in the middle of a cout chain, some of the output time can be included in the elapsed time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:02:05.807",
"Id": "425688",
"Score": "0",
"body": "@1201ProgramAlarm: If you can actually show that happening, I'll be happy to submit a bug report against the library that's doing it. But I've used all the major implementations of `std::chrono::high_resolution_clock` many times, and never seen any hint of it misbehaving as you've suggested it could. When/if I see it actually happen, I'll submit a bug report (but I doubt that'll arise)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T07:01:38.267",
"Id": "425699",
"Score": "0",
"body": "@JerryCoffin Is that a bug though? we effectively have `operator<<(operator<<(std::cout, \"std::unordered_map: \"), clock() - begin)`. Isn't the order of evaluation of arguments unspecified? So the first call to `operator<<` could be evaluated before or after `clock() - begin`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:36:08.333",
"Id": "425746",
"Score": "0",
"body": "@user673679: If you continue to use the original code, then yes, you write `clock()-begin` to `cout` (and yes, that's probably a poor idea). But if you use the code I suggested in the `Improve Timing` section, it does `auto end = high_resolution_clock::now();` after the code to be timed, and only after that completes is anything written to `cout`. This leaves no room for ambiguity about the recorded time including the I/O."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T18:47:35.127",
"Id": "220303",
"ParentId": "220269",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220303",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T05:35:44.513",
"Id": "220269",
"Score": "4",
"Tags": [
"c++",
"performance",
"beginner",
"c++11"
],
"Title": "STL Performance micro-benchmark"
} | 220269 |
<p>This is an exercise in a book which ask me to implement</p>
<blockquote>
<p>Write an in-place function to eliminate adjacent duplicates in a []string slice.</p>
</blockquote>
<p>I am relatively new to golang and I am not sure if my implementation is correct and effective or not.</p>
<pre><code>func removeAdj(strings []string) []string {
for i := 0; i < len(strings); i++ {
dup := false
lastJ := i
for j := (i + 1); j < len(strings); j++ {
if strings[i] == strings[j] {
dup = true
lastJ = j
} else {
break
}
}
if dup {
strings[i] = ""
first := strings[:i]
second := strings[lastJ+1:]
strings = append(first, second...)
i = -1
}
}
return strings
}
</code></pre>
<p><strong>Tests:</strong></p>
<pre><code>Input: [a z x x z y]
Output: [a y]
Input: [g e e k s f o r g e e g]
Output: [g k s f o r]
Input: [c a a a b b b a a c d d d d]
Output: []
Input: [a c a a a b b b a c d d d d]
Output: [a c a c]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T09:39:54.317",
"Id": "425592",
"Score": "1",
"body": "Are these the only instructions you got? It is not clear where the recursive suppression from your tests come from. It is also not clear why the last test does not simply return `[a]` since, after removing all `b`s, you can remove `a`s and then `c`s. Can you clarify the problem statement and what hypothesis you took?"
}
] | [
{
"body": "<p>Your implementation, to me at least, doesn't seem correct. You need to remove adjacent duplicates, but looking at your last example, the sequence <code>acaaabbacdddd</code> completely removes the <code>b</code> and <code>d</code> characters from the slice. You're also using an awful lot of code to do a simple thing. What I'd do is quite simply this:</p>\n\n<ul>\n<li>Iterate over the slice from index 0 to the next to last character</li>\n<li>For each character, iterate over the remainder of the slice (nested loop) until you find a character that doesn't equal the current index</li>\n<li>For each character at the current position + 1 that matches the current one, remove it, as it's an adjacent duplicate.</li>\n</ul>\n\n<p>The code itself is quite simple:</p>\n\n<pre><code>func dedup(s []string) []string {\n // iterate over all characters in slice except the last one\n for i := 0; i < len(s)-1;i++ {\n // iterate over all the remaining characeters\n for j := i+1; j < len(s); j++ {\n if s[i] != s[j] {\n break // this wasn't a duplicate, move on to the next char\n }\n // we found a duplicate!\n s = append(s[:i], s[j:]...)\n }\n }\n return s\n}\n</code></pre>\n\n<p>Given an input like <code>[g e e k s f o r g e e g]</code>, the output of this is <code>[g e k s f o r g e g]</code></p>\n\n<h2><a href=\"https://play.golang.org/p/7zTrb_nxnoQ\" rel=\"nofollow noreferrer\">Demo</a></h2>\n\n<p>The only trickery here is this line: <code>s = append(s[:i], s[j:]...)</code>. What this effectively does is reassign the slice <code>s</code> to contain <code>i</code> values starting at 0 (so if <code>i</code> is 2, the slice will be <code>[g, e]</code>). The second part is creating a slice starting at <code>j</code>, until the end of <code>s</code>. Again, if <code>j</code> is 2, this slice will be all values starting at offset 2 until the end (<code>[e k s f o r g e e g]</code>).</p>\n\n<p>So let's look at an actual example:</p>\n\n<ul>\n<li><code>i</code> == 1</li>\n<li><code>j</code> == <code>i+1</code> (2)</li>\n<li><code>s[i]</code> == <code>e</code>, <code>s[j] ==</code>e`</li>\n</ul>\n\n<p>We have a duplicate, so we'll reassign <code>s</code> like so:</p>\n\n<pre><code> s = append(s[:1], s[2:]...)`\n</code></pre>\n\n<p>This means we're appending <code>[e k s f o r g e e g]</code> to <code>[g]</code>, removing the duplicate <code>e</code>. Job done.</p>\n\n<hr>\n\n<h3>Note:</h3>\n\n<p>I've used <code>[]string</code> here, but it should go without saying that a slice of characters is probably best represented as <em>either</em> <code>[]byte</code> or <code>[]rune</code> (for full UTF-8 support). Regardless of the type you end up using, the code above will work with with any type that can be compared with the <code>==</code> operator</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:09:09.403",
"Id": "456383",
"Score": "0",
"body": "Actually your solution doesn't work when there are 3 adjacent occurrences, just try with [g e e e k]. For a fast fix on the line after append I added a j-- (not too elegant, there should be a better solution)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T10:07:18.997",
"Id": "220333",
"ParentId": "220273",
"Score": "3"
}
},
{
"body": "<p>I am also new to Go, and I guess, we have the same Book :)\nI did it like this:</p>\n\n<pre><code>func RemoveAdjacentDuplicates(strings []string) []string {\n if len(strings) < 2 {\n return strings\n }\n current, nextDifferent := 0, 1\n for nextDifferent < len(strings) {\n for nextDifferent < len(strings) && strings[current] == strings[nextDifferent] {\n nextDifferent++\n }\n if nextDifferent < len(strings) {\n if current+1 != nextDifferent {\n strings[current+1] = strings[nextDifferent]\n }\n strings[current+1] = strings[nextDifferent]\n current++\n }\n }\n return strings[:current+1]\n}\n</code></pre>\n\n<p>The advantage is, that you will not copy the whole tail of the slice several times when there are several ranges of duplicates. I am aware, that this also is not the best solution. One could copy whole ranges of unique strings at once instead of copy them one by one, which may be even more efficient.</p>\n\n<p>And here a maybe more efficient one with comments, which copies in chunks with <code>copy</code> A lot of code for a simple task. I don't know if it is really more performant as simpler solutions (regarding code) and I am sure that it can be done easier.</p>\n\n<pre><code>func RemoveAdjacentDuplicates(strings []string) []string {\n // at least two elements need to be in the slice to have adjacent duplicates\n if len(strings) < 2 {\n return strings\n }\n current, nextDifferent, nextDifferentEnd := 0, 1, 0\n for nextDifferentEnd+1 < len(strings) {\n // search for next different element\n for nextDifferent < len(strings) && strings[current] == strings[nextDifferent] {\n nextDifferent++\n }\n // look for the largest subslice from the next different up to the next duplicate\n nextDifferentEnd = nextDifferent + 1\n for nextDifferentEnd < len(strings) && strings[nextDifferentEnd-1] != strings[nextDifferentEnd] {\n nextDifferentEnd++\n }\n // if we did not reach the and of the slice,\n // replace the duplicate(s) with the next subslice with different elements\n if nextDifferent < len(strings) {\n if current+1 != nextDifferent {\n copy(strings[current+1:], strings[nextDifferent:nextDifferentEnd])\n }\n current += nextDifferentEnd - nextDifferent\n nextDifferent = nextDifferentEnd\n }\n }\n // finally, current will index the last element of the result slice\n return strings[:current+1]\n}\n</code></pre>\n\n<p>Or, how about this one?</p>\n\n<pre><code>func FirstSubsliceWithoutAdjacentDuplicates(strings []string) ([]string, int) {\n if len(strings) < 2 {\n return strings, 0\n }\n for i := 1; i < len(strings); i++ {\n if strings[i-1] == strings[i] {\n repeats := 1\n for i+repeats < len(strings) && strings[i] == strings[i+repeats] {\n repeats++\n }\n return strings[:i], repeats\n }\n }\n return strings, 0\n}\n\nfunc RemoveAdjacentDuplicates(toBeProcessed []string) []string {\n unique, repeats := FirstSubsliceWithoutAdjacentDuplicates(toBeProcessed)\n if len(unique) == len(toBeProcessed) {\n return unique\n }\n result := toBeProcessed\n copyTarget := toBeProcessed\n finalLength := 0\n for len(unique) > 0 {\n finalLength += len(unique)\n copy(copyTarget, unique)\n toBeProcessed = toBeProcessed[len(unique)+repeats:]\n copyTarget = copyTarget[len(unique):]\n unique, repeats = FirstSubsliceWithoutAdjacentDuplicates(toBeProcessed)\n }\n return result[0:finalLength]\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T11:58:53.327",
"Id": "225027",
"ParentId": "220273",
"Score": "3"
}
},
{
"body": "<p>You can do this in a single loop, only moving forward through the slice when there are no more duplicates at the current position:</p>\n\n<pre><code>func removeAdjacentDups(strings []string) []string {\n // Iterate over all characters in the slice except the last one\n for i := 0; i < len(strings)-1; {\n // Check whether the character next to it is a duplicate\n if strings[i] == strings[i+1] {\n // If it is, remove the CURRENT character from the slice\n strings = append(strings[:i], strings[i+1:]...)\n } else {\n // If it's not, move to the next item in the slice\n i++\n }\n }\n return strings\n}\n</code></pre>\n\n<p>Input:</p>\n\n<pre><code>[]string{\"hello\", \"hello\", \"hello\", \"hi\", \"hi\", \"hello\", \"howdy\", \"hello\", \"hello\",}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[hello hi hello howdy hello]\n</code></pre>\n\n<p>Explanation:</p>\n\n<p>At each position, i, you check whether the element next to it, i + 1, is a duplicate. If it is, you replace the current slice by appending everything up to but not including i to everything after i. That is, <strong>you remove the current item</strong>, not the one that duplicates it.</p>\n\n<p>Importantly, this solution handles the case when there are three duplicates in a row, e.g. [ \"b\", \"a\", \"a\", \"a\", \"c\"]. It does this by only incrementing the loop counter, i, when no duplicate is found at i + 1. If a duplicate is found and removed, the loop stays in the same position to check for additional copies.</p>\n\n<p>Apologies for resurrecting an old question, but this will likely be useful for others with the same book.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T05:55:39.877",
"Id": "241735",
"ParentId": "220273",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T09:05:10.330",
"Id": "220273",
"Score": "1",
"Tags": [
"performance",
"algorithm",
"go"
],
"Title": "Remove adjacent duplicates in golang"
} | 220273 |
<p><strong>The task</strong>
is taken from <a href="https://leetcode.com/problems/reverse-integer/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Given a 32-bit signed integer, reverse digits of an integer.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: 123
Output: 321
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: -123
Output: -321
</code></pre>
<p><strong>Example 3:</strong></p>
<pre><code>Input: 120
Output: 21
</code></pre>
<p><strong>Note:</strong></p>
<p>Assume we are dealing with an environment which could only store
integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For
the purpose of this problem, assume that your function returns 0 when
the reversed integer overflows.</p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>/**
* @param {number} x
* @return {number}
*/
const reverse = x => {
if (x === undefined || x === null) { return; }
if (x < 10 && x >= 0) { return x; }
const num = [];
const dissectNum = n => {
if (n <= 0) { return; }
const y = n % 10;
num.push(y);
return dissectNum(Math.floor(n / 10));
};
dissectNum(Math.abs(x));
let tmp = 0;
const maxPow = num.length - 1;
for (let i = 0; i < num.length; i++) {
tmp += num[i] * Math.pow(10, maxPow - i);
}
const result = (x < 0 ? -1 : 1 ) * tmp;
return result > Math.pow(-2, 31) && result < (Math.pow(2, 31) - 1)
? result
: 0;
};
</code></pre>
| [] | [
{
"body": "<ul>\n<li>The question states that the input is a number 32 signed int so checking for <code>undefined</code> or <code>null</code> is a waste of time.</li>\n</ul>\n\n<p>The solution is a little long. Some of it due to not being familiar with some old school short cuts.</p>\n\n<ul>\n<li>To get the sign of a number use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign\" rel=\"noreferrer\"><code>Math.sign</code></a></li>\n</ul>\n\n<p>-JavaScript numbers are doubles but when you use bitwise operations on them they are converted to 32 bit signed integers. This gives you a very easy way to check if the result has overflowed.</p>\n\n<pre><code>const signedInt = value => (value | 0) === value; // returns true if int32\n</code></pre>\n\n<ul>\n<li><p>A 32 bit int can store 9 full decimal digits, with an extra digit <code>1</code> or <code>2</code>, and a sign. you dont need to use an array to hold the reversed digits you can store them in the reversed number as you go.</p></li>\n<li><p>JavaScript can handle hex <code>0x10 === 16</code>, decimal <code>10 === 10</code>, octal <code>010 === 8</code> and binary <code>0b10 === 2</code> (oh and BIG ints <code>10n === 10</code>) Hex makes realy easy to remember the lowest and highest int for a given size. </p>\n\n<p>Not that you need them to solve the problem, just some handy info.</p></li>\n</ul>\n\n<p>Some common ways of writing min max 32Ints</p>\n\n<pre><code> const MIN = Math.pow(-2, 31), MAX = Math.pow(2, 31) - 1;\n\n\n// negative\n-0x80000000 === MIN; // true\n(0x80000000 | 0) === MIN; // true. Coerce from double to int32 \n1 << 31 === MIN; // true. Shift 1 to the highest (MSB) bit for negative\n\n//positive\n0x7FFFFFFF === MAX; // true\n~(1 << 31) === MAX; // true Flips bits of min int32\n</code></pre>\n\n<h2>Rewrite</h2>\n\n<p>With that info you can rewrite the solution as</p>\n\n<pre><code>function reverseDigits(int) {\n var res = 0, val = Math.abs(int);\n while (val > 0) {\n res = res * 10 + (val % 10);\n val = val / 10 | 0;\n }\n res *= Math.sign(int);\n return (res | 0) === res ? res : 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T12:46:32.763",
"Id": "220282",
"ParentId": "220274",
"Score": "7"
}
},
{
"body": "<p>I'd just use string manipulation on this, with a simple conditional for the edge cases.</p>\n\n<pre><code>var reverse = n => {\n const s = parseInt([...\"\" + n].reverse().join(\"\"));\n return s >= 2 ** 31 ? 0 : Math.sign(n) * s;\n};\n</code></pre>\n\n<p>The approach is to stringify the number, arrayify the string, reverse it, re-join the array into a string and finally parse the reversed string to an integer. <code>parseInt</code> called on a string such as <code>\"546-\"</code> will strip the trailing <code>-</code>. Then, handle overflow and positive/negative conditions and return the result.</p>\n\n<p>In short, avoid overcomplication and take advantage of high-level language features when possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:56:03.790",
"Id": "220380",
"ParentId": "220274",
"Score": "5"
}
},
{
"body": "<p>Both answers require you to use <code>Math.sign</code>. To avoid compatibility issues with some browsers, you could add the following script in your solution.</p>\n\n<pre><code>if (Math.sign === undefined) {\n Math.sign = function ( x ) {\n return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : +x;\n };\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T05:19:26.930",
"Id": "429444",
"Score": "1",
"body": "\"some browsers\" in this case means [only the Internet Explorer](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Math/sign)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-03T06:57:59.647",
"Id": "221574",
"ParentId": "220274",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220282",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T09:08:50.047",
"Id": "220274",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"ecmascript-6"
],
"Title": "Reverse Integer"
} | 220274 |
<p>I have this simple function that just reads a file, replaces all occurances of a string, and write it back to the file:</p>
<pre><code>def fileSearchReplace(targetFile, search, replace):
with open(targetFile, 'r') as openFile:
filedata = openFile.read()
newData = filedata.replace(search, replace)
with open(targetFile, 'w') as openFile:
openFile.write(newData)
</code></pre>
<p>I was wondering if there are any better implementation? </p>
| [] | [
{
"body": "<p>Personally, I would do this kind of thing line by line. I don't like the idea of putting my entire file into memory, then overwriting it. What if something goes wrong in between? Basically I don't trust myself to write good code!</p>\n\n<p>So, looping through line by line, I would write to a new file with any changes. In Python, you can open two files at once, which is perfect for reading from one and writing to another. </p>\n\n<p>Applying PEP8 for naming, you'd end up with something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def file_search_replace(open_file, search, replacement):\n\n with open(open_file, 'r') as read_file, open('new_file.txt', 'w+') as write_file:\n\n for line in read_file:\n write_file.write(line.replace(search, replacement))\n\n</code></pre>\n\n<p>I've changed a few of the names, notably <code>replace</code> to <code>replacement</code> so it's clear it's not the same as <code>replace()</code>.</p>\n\n<p>Finally, if you're happy with the result, you can easily rename the file to something else. Personally I'd keep the old one just in case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T15:49:59.497",
"Id": "425622",
"Score": "0",
"body": "This doesn't work without backup (when open_file == 'new_file.txt')"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T13:31:57.073",
"Id": "220287",
"ParentId": "220283",
"Score": "6"
}
},
{
"body": "<p>You could consider using the <a href=\"https://docs.python.org/3.7/library/fileinput.html#fileinput.FileInput\" rel=\"nofollow noreferrer\"><code>fileinput.FileInput</code></a> to perform in-place substitutions in a file. The accepted answer in <a href=\"https://stackoverflow.com/a/20593644/466070\">this Stack Overflow answer</a> illustrates a simple solution.</p>\n\n<p>If you need to perform replacements across multiple lines, you will likely want to read all of the data into a variable (if possible, depending on file size), then use the <a href=\"https://docs.python.org/3.7/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><code>re.sub</code></a> function with the <code>re.DOTALL</code> option specified to treat newlines as inclusive in your regular expression.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:48:01.330",
"Id": "425664",
"Score": "0",
"body": "Thank you for your edit :) This is an example of what the second would look like: `out.write(re.sub(re.escape(search), replace, in_.read()))`. Changing `in_` to an [`mmap`](https://docs.python.org/3.7/library/mmap.html) will also mean the entire file isn't read into memory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T17:58:16.917",
"Id": "220299",
"ParentId": "220283",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T12:52:41.123",
"Id": "220283",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"strings",
"file"
],
"Title": "Search string in file, replace it, and write back to file"
} | 220283 |
<p>I started learning Python a month ago (used to write programs in Delphi before). Can you please take a look at my code and give me some tips what is good and what is bad in it?</p>
<p>The aim is to find duplicate files on a disk and saves this information. I'm using md5 hash. Is it right to use global variable like I did?</p>
<pre><code>import os
import time
import hashlib
def md5_sum(path, block_size=256*128, hr=False):
md5 = hashlib.md5()
with open(path, 'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
md5.update(chunk)
if hr:
return md5.hexdigest()
return md5.digest()
def md5_simple(path, chunk):
if chunk:
return md5_sum(path, 8192)
else:
return hashlib.md5(open(path, 'rb').read()).digest()
def walking(path, chunk=False):
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
global dupl_string
try:
if len(found_files) % 500 == 0:
print(len(found_files))
fname = os.path.join(dirpath, filename)
file_size = os.path.getsize(fname)
found_files[fname] = file_size
if chunk:
file_hash = md5_sum(fname, 8192)
else:
file_hash = md5_simple(fname, file_size > 1000 * 1024 * 1024)
if file_hash in hash_files:
dupl_string += 'Src: ' + hash_files[file_hash] + ', dupl: ' + fname + '\n'
else:
hash_files[file_hash] = fname
except OSError:
print('OSError: ' + fname)
my_dir = "C:"
dupl_string = ''
found_files = dict()
hash_files = dict()
time1 = time.time()
try:
walking(my_dir)
finally:
if dupl_string:
with open('dupl.txt', 'w') as f3:
f3.write(dupl_string)
with open('files.csv', 'w') as f:
for key, value in sorted(found_files.items(), key=lambda item: item[1], reverse=True):
f.write("%s, %s\n" % (key, value))
print("Elapsed: " + str(time.time() - time1) + ' sec')
</code></pre>
| [] | [
{
"body": "<h1>Formatting</h1>\n\n<p>The code formatting is good. The only major gripe I have is that there are some long lines (117 chars). Part of this is due to the high level of indenation, which we'll solve in another way, but even with heavily indented code, lines can be shorter. I use the <a href=\"https://github.com/python/black\" rel=\"noreferrer\">black</a> code formatter (with a linelength of 79) to format my code, so I don't have to worry about spacing, long lines or inconsistent quote characters any more</p>\n\n<h1>Try-except</h1>\n\n<p>You should surround the part that can fail (reading the filesize and file_hash) as closely as possible with the <code>try-except</code> clause. If you want to print a debug message and prevent the rest of that iteration to be executed, you can do that by adding a <code>continue</code> after the print</p>\n\n<h1>globals</h1>\n\n<p>as you question it, globals are not the correct way to pass information here. A different approach would be to have parts that</p>\n\n<ol>\n<li>generate the paths to the files to check</li>\n<li>return the hash</li>\n<li>look for duplicates in the hashes</li>\n<li>report the duplicates</li>\n</ol>\n\n<p>Each part can receive the result of the previous step as input</p>\n\n<h1>generate the paths</h1>\n\n<p>Since python 3.4 there is a more convenient way to handle file paths: <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib.Path</code></a></p>\n\n<pre><code>from pathlib import Path\ndef walking(path):\n return Path(path).glob(\"**/*\")\n</code></pre>\n\n<p>This returns a generator that yields <code>Path</code>s to all of the files under <code>path</code>. Since it is so simple, it can be inlined.</p>\n\n<h1>hashing</h1>\n\n<pre><code>def hashing(paths, chunk=False):\n for path in paths:\n filesize = path.stat().st_size\n if chunk:\n file_hash = md5_sum(fname, 8192)\n else:\n file_hash = md5_simple(fname, file_size > 1000 * 1024 * 1024)\n yield path, file_hash\n</code></pre>\n\n<h1>magic numbers</h1>\n\n<p>This previous function has some magic numbers <code>8192</code> and <code>1000 * 1024 * 1024</code>.\nBetter would be to define those a module level constants:</p>\n\n<pre><code>CHUNKSIZE_DEFAULT = 8192\nMAX_SIZE_BEFORE_CHUNK = 1000 * 1024 * 1024 # files larger than this need to be hashed in chuncks\n\ndef hashing(paths, chunk=False):\n for path in paths:\n filesize = path.stat().st_size\n if chunk or file_size > MAX_SIZE_BEFORE_CHUNK:\n file_hash = md5_sum(fname, CHUNKSIZE_DEFAULT )\n else:\n file_hash = md5_simple(fname)\n yield path, file_hash\n</code></pre>\n\n<p>I'm not 100% happy with <code>MAX_SIZE_BEFORE_CHUNK</code> as variable name, but can't immediately think of a better on</p>\n\n<h1>hoist the OI</h1>\n\n<p>If you look at <a href=\"https://rhodesmill.org/brandon/talks/#clean-architecture-python\" rel=\"noreferrer\">this</a> talk by Brandon Rhodes, it makes sense not to open the file in the method that calculates the hash, but have it accept a filehandle. This is also the approach taken in this <a href=\"https://codereview.stackexchange.com/a/108362/123200\">code review answer</a>\nSo to reuse the slightly adapted code from this answer</p>\n\n<pre><code>def read_chunks(file_handle, chunk_size=CHUNKSIZE_DEFAULT):\n while True:\n data = file_handle.read(chunk_size)\n if not data:\n break\n yield data\n\n\ndef md5(file_handle, chunk_size=None, hex_representation=False):\n if chunk_size is None:\n hasher = hashlib.md5(file_handle.read())\n else:\n hasher = hashlib.md5()\n for chunk in read_chunks(file_handle, chunk_size):\n hasher.update(chunk)\n\n return hasher.digest() if not hex_representation else hasher.hexdigest()\n</code></pre>\n\n<p>This gets called like this:</p>\n\n<pre><code>def hashing(paths, chunk=False, hex_representation=False):\n for path in paths:\n file_size = path.stat().st_size\n with path.open(\"rb\") as file_handle:\n chunk_size = (\n CHUNKSIZE_DEFAULT\n if chunk or file_size > MAX_SIZE_BEFORE_CHUNK\n else None\n )\n file_hash = md5(\n file_handle,\n chunk_size=chunk_size,\n hex_representation=hex_representation,\n )\n yield path, file_hash\n</code></pre>\n\n<h1>looking for duplicates</h1>\n\n<p>Instead of keeping a long string with all the duplicates, you can keep a set of the <code>Path</code>s for each <code>file_hash</code>. A <code>collections.defaultdict(set)</code> is the suited container for this. You add each path to the set at the in the dict. At the end of the function, you filter the keys that have more than 1 entry:</p>\n\n<pre><code>def duplicates(hashings):\n duplicates = defaultdict(set)\n for path, file_hash in hashings:\n duplicates[file_hash].add(path)\n\n return {\n filehash: paths\n for filehash, paths in duplicates.items()\n if len(paths) > 1\n }\n</code></pre>\n\n<h1>report the filesizes</h1>\n\n<p>instead of formating the csv-file yourself, you can use the <code>csv</code> module. It even has a <a href=\"https://docs.python.org/3/library/csv.html#csv.csvwriter.writerows\" rel=\"noreferrer\"><code>writerows</code></a>. Instead of defining the lambda function to srt by value, you can use <code>operator.itemgetter</code></p>\n\n<pre><code>import csv\nfrom operator import itemgetter\n\n\ndef report_results(file_handle, filesizes):\n writer = csv.writer(file_handle, delimiter=\",\", lineterminator=\"\\n\")\n sorted_sizes = sorted(filesizes.items(), key=itemgetter(1))\n writer.writerows(sorted_sizes)\n</code></pre>\n\n<p>This method can also be used to save the <code>file_hashes</code></p>\n\n<h1>reporting the duplicates</h1>\n\n<pre><code>def report_duplicates(file_handle, duplicates):\n writer = csv.writer(file_handle, delimiter=\",\", lineterminator=\"\\n\")\n for file_hash, duplicate_files in duplicates.items():\n for file_name in duplicate_files:\n writer.writerow((file_hash, str(file)))\n</code></pre>\n\n<p>Here I exported a <code>csv</code> file with the hash and filenames of the duplicates. If you want it in another format, you can easily change this method</p>\n\n<h1>bringing it together</h1>\n\n<pre><code>def main(path, chunk=False):\n files = [file for file in Path(path).glob(\"**/*\") if file.is_file()]\n\n filesizes = {str(path): path.stat().st_size for path in files}\n with open(\"test_filesizes.csv\", \"w\") as file_handle:\n report_results(file_handle, filesizes)\n filehashes = dict(hashing(files, chunk=chunk))\n\n with open(\"test_hashes.csv\", \"w\") as file_handle:\n report_results(file_handle, filehashes)\n\n duplicates = find_duplicates(filehashes.items())\n with open(\"test_duplicates.csv\", \"w\") as file_handle:\n report_duplicates(file_handle, duplicates)\n</code></pre>\n\n<p>And then we put everything behind a <code>__main__</code> guard:</p>\n\n<pre><code>if __name__ == \"__main__\":\n main(<path>)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:15:59.743",
"Id": "425629",
"Score": "0",
"body": "Thank you sir! It helped me a lot"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:06:37.837",
"Id": "220290",
"ParentId": "220284",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220290",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T13:17:22.400",
"Id": "220284",
"Score": "7",
"Tags": [
"python",
"file-system",
"checksum"
],
"Title": "Finding duplicate files on a disk using MD5"
} | 220284 |
<p>I programmed a generic queue in pure C and I'd love to receive some feedback from other programmers.</p>
<p>You may use the following questions to guide your review.</p>
<ul>
<li>Is the API well thought and idiomatic?</li>
<li>Does the code look "modern" (i.e. uses modern conventions etc)?</li>
<li>Is the code efficient in terms of memory usage?</li>
<li>Are the tests well thought?</li>
<li>Is the code free of undefined behavior, memory leaks etc?</li>
</ul>
<p>My program is divided in 3 files:</p>
<p><strong>queue.h</strong></p>
<pre class="lang-c prettyprint-override"><code>#pragma once
#include <stddef.h>
typedef enum queue_ret
{
QUEUE_RET_Success,
QUEUE_RET_FailedMemoryAlloc,
QUEUE_RET_QueueIsEmpty,
} queue_ret_t;
typedef struct node
{
void* data;
struct node* next;
} node_t;
typedef struct queue
{
node_t* front;
node_t* back;
size_t size;
} queue_t;
queue_ret_t QUEUE_initialize(queue_t** queue);
size_t QUEUE_size(queue_t* queue);
queue_ret_t QUEUE_enqueue(queue_t* queue, void* data);
queue_ret_t QUEUE_peek(queue_t* queue, void* data, size_t size);
queue_ret_t QUEUE_dequeue(queue_t* queue, void* data, size_t size);
void QUEUE_free(queue_t* queue);
</code></pre>
<p><strong>queue.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
#include <string.h>
#include "queue.h"
queue_ret_t QUEUE_initialize(queue_t** queue)
{
*queue = (queue_t*)calloc(1, sizeof(queue_t));
if ((*queue) == NULL)
{
return QUEUE_RET_FailedMemoryAlloc;
}
(*queue)->front = NULL;
(*queue)->back = NULL;
(*queue)->size = 0;
return QUEUE_RET_Success;
}
size_t QUEUE_size(queue_t* queue)
{
return queue->size;
}
queue_ret_t QUEUE_enqueue(queue_t* queue, void* data)
{
node_t* node = (node_t*)calloc(1, sizeof(node_t));
if (node == NULL)
{
return QUEUE_RET_FailedMemoryAlloc;
}
node->data = data;
node->next = NULL;
if (queue->size == 0)
{
queue->front = node;
queue->back = node;
}
else
{
queue->back->next = node;
queue->back = node;
}
(queue->size)++;
return QUEUE_RET_Success;
}
queue_ret_t QUEUE_peek(queue_t* queue, void* data, size_t size)
{
if (queue->size == 0)
{
return QUEUE_RET_QueueIsEmpty;
}
memcpy(data, queue->front->data, size);
return QUEUE_RET_Success;
}
queue_ret_t QUEUE_dequeue(queue_t* queue, void* data, size_t size)
{
queue_ret_t ret = QUEUE_peek(queue, data, size);
if (ret != QUEUE_RET_Success)
{
return ret;
}
if (queue->front == queue->back)
{
free(queue->front);
queue->front = NULL;
queue->back = NULL;
}
else
{
node_t* temp = queue->front;
queue->front = temp->next;
free(temp);
}
(queue->size)--;
return QUEUE_RET_Success;
}
void QUEUE_free(queue_t* queue)
{
node_t* current = queue->front;
while (current != NULL)
{
node_t* next = current->next;
free(current);
current = next;
}
free(queue);
}
</code></pre>
<p><strong>queue_test.c</strong></p>
<pre class="lang-c prettyprint-override"><code>#include "greatest.h"
#include "queue.h"
TEST dequeue_empty_queue_should_return_QueueIsEmpty()
{
queue_t* queue;
queue_ret_t ret;
ret = QUEUE_initialize(&queue);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_dequeue(queue, NULL, 0);
ASSERT_EQ(QUEUE_RET_QueueIsEmpty, ret);
QUEUE_free(queue);
PASS();
}
TEST peek_empty_queue_should_return_QueueIsEmpty()
{
queue_t* queue;
queue_ret_t ret;
ret = QUEUE_initialize(&queue);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_peek(queue, NULL, 0);
ASSERT_EQ(QUEUE_RET_QueueIsEmpty, ret);
QUEUE_free(queue);
PASS();
}
TEST size_of_empty_queue_should_be_0()
{
queue_t* queue;
queue_ret_t ret;
size_t actual;
ret = QUEUE_initialize(&queue);
ASSERT_EQ(QUEUE_RET_Success, ret);
actual = QUEUE_size(queue);
ASSERT_EQ(0, actual);
QUEUE_free(queue);
PASS();
}
TEST enqueue_should_make_size_grow()
{
queue_t* queue;
queue_ret_t ret;
int dummy = 0;
size_t actual;
ret = QUEUE_initialize(&queue);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &dummy);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &dummy);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &dummy);
ASSERT_EQ(QUEUE_RET_Success, ret);
actual = QUEUE_size(queue);
ASSERT_EQ(3, actual);
QUEUE_free(queue);
PASS();
}
TEST peek_should_return_next_dequeue_item()
{
queue_t* queue;
queue_ret_t ret;
int expected = 1;
int dummy = 2;
int actual = 0;
ret = QUEUE_initialize(&queue);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &expected);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_peek(queue, &actual, sizeof(actual));
ASSERT_EQ(QUEUE_RET_Success, ret);
ASSERT_EQ(expected, actual);
ret = QUEUE_enqueue(queue, &dummy);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_peek(queue, &actual, sizeof(actual));
ASSERT_EQ(QUEUE_RET_Success, ret);
ASSERT_EQ(expected, actual);
QUEUE_free(queue);
PASS();
}
TEST dequeue_all_items_should_left_queue_empty()
{
queue_t* queue;
queue_ret_t ret;
int dummy = 0;
size_t actual;
ret = QUEUE_initialize(&queue);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &dummy);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &dummy);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_dequeue(queue, &dummy, sizeof(dummy));
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_dequeue(queue, &dummy, sizeof(dummy));
ASSERT_EQ(QUEUE_RET_Success, ret);
actual = QUEUE_size(queue);
ASSERT_EQ(0, actual);
QUEUE_free(queue);
PASS();
}
TEST first_item_in_should_be_first_item_out()
{
queue_t* queue;
int expected_1 = 1;
int expected_2 = 2;
int actual;
queue_ret_t ret;
ret = QUEUE_initialize(&queue);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &expected_1);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_enqueue(queue, &expected_2);
ASSERT_EQ(QUEUE_RET_Success, ret);
ret = QUEUE_dequeue(queue, &actual, sizeof(actual));
ASSERT_EQ(QUEUE_RET_Success, ret);
ASSERT_EQ(expected_1, actual);
ret = QUEUE_dequeue(queue, &actual, sizeof(actual));
ASSERT_EQ(QUEUE_RET_Success, ret);
ASSERT_EQ(expected_2, actual);
QUEUE_free(queue);
PASS();
}
GREATEST_MAIN_DEFS();
int main(int argc, char **argv) {
GREATEST_MAIN_BEGIN();
RUN_TEST(dequeue_empty_queue_should_return_QueueIsEmpty);
RUN_TEST(peek_empty_queue_should_return_QueueIsEmpty);
RUN_TEST(size_of_empty_queue_should_be_0);
RUN_TEST(enqueue_should_make_size_grow);
RUN_TEST(peek_should_return_next_dequeue_item);
RUN_TEST(dequeue_all_items_should_left_queue_empty);
RUN_TEST(first_item_in_should_be_first_item_out);
GREATEST_MAIN_END();
}
</code></pre>
<h2>How to run</h2>
<p>Put all the files shown above in the same folder. Then, you need to copy the <a href="https://raw.githubusercontent.com/silentbicycle/greatest/master/greatest.h" rel="noreferrer">testing library</a> to the this folder, which is just a single header file called greatest.h.</p>
<p>So, assuming your folder looks like this:</p>
<pre class="lang-none prettyprint-override"><code>> ls
> greatest.h queue.c queue.h queue_test.c
</code></pre>
<p>You run the tests with:</p>
<pre class="lang-none prettyprint-override"><code>gcc queue.c queue_test.c -o queue_test && queue_test
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T15:53:23.990",
"Id": "425623",
"Score": "0",
"body": "the posted code is missing the header file contents for `greatest.h` Please edit the question to include that missing header file"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:01:27.910",
"Id": "425624",
"Score": "0",
"body": "@user3629249 I included a link to it, which is: https://raw.githubusercontent.com/silentbicycle/greatest/master/greatest.h"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:07:13.100",
"Id": "425626",
"Score": "0",
"body": "@user3629249 It looks like you didn't copy [the content of greatest.h](https://raw.githubusercontent.com/silentbicycle/greatest/master/greatest.h). All I have to do is to create a `greatest.h` file with the content found in the previous link, so I presume this is all you have to do too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:12:35.947",
"Id": "425628",
"Score": "0",
"body": "After copying the linked file: `greatest.h` it cleanly compiles. DO NOT reference links to external files. The posted code should stand on its' own"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:36:20.177",
"Id": "425635",
"Score": "0",
"body": "@user3629249 I thought about posting that code into the question, but it's an external library, not my actual code, so I just left a link to it. Anyway, I'm glad it's now working for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T15:28:30.850",
"Id": "425973",
"Score": "1",
"body": "This looks like a linked list trying to get out! I would extract out the linked list code (which could then be used directly, or as part of a stack or other data structure), and then wrap it to create the queue and expose only those operations which are legal for queues."
}
] | [
{
"body": "<p>When you have queued a pointer you can never get that pointer again. It is also very difficult to know when that pointer has been dequeued. This is a recipe for leaks. </p>\n\n<p>Instead returning the pointer itself instead of the data contained is a better idea. Or store the entire object wholesale.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:53:03.150",
"Id": "425637",
"Score": "1",
"body": "Sorry, I don't get what you mean... Can you explain this further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T04:53:30.140",
"Id": "425685",
"Score": "7",
"body": "@Gabriel: In your API, `enqueue()` stores the data by reference, forcing the caller not to free the memory containing it until it's removed from the queue. But `peek()` and `dequeue()` return a copy of the data rather than a pointer to it, which not only feels inconsistent, but also prevents the caller from getting the original pointer back from the queue so that it can be freed. Either have `enqueue()` allocate its own memory and make a copy of the data and have `dequeue()` free it, or just have both `peek()` and `dequeue()` return the original pointer and let the caller manage data memory."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:36:39.723",
"Id": "220291",
"ParentId": "220288",
"Score": "9"
}
},
{
"body": "<p>Overall good job!</p>\n\n<blockquote>\n <p>Does the code looks \"modern\" (i.e. uses modern conventions etc)?</p>\n</blockquote>\n\n<p>One of the things I see regularly here on Code Review is the advice to allocate memory based on the size of what an object points to rather than the object type itself:</p>\n\n<pre><code> *queue = calloc(1, sizeof(*queue));\n</code></pre>\n\n<p>and</p>\n\n<pre><code> node_t* node = calloc(1, sizeof(*node));\n</code></pre>\n\n<p>This eases maintainability by removing necessary changes, only the type of <code>queue</code> or <code>node</code> needs to be changed in these cases.</p>\n\n<p>While the code is technically correct, I personally would use <code>malloc()</code> in these cases and only use <code>calloc()</code> when creating an array. If the goal is to zero out the memory allocated <code>memset()</code> can be used for that. There won't be any change in performance, <code>calloc()</code> takes longer than <code>malloc()</code> because it does clear the memory. It's not clear that <code>calloc()</code> is necessary for <code>node</code> because all the necessary assignments are performed.</p>\n\n<blockquote>\n <p>Is the code efficient in terms of memory usage?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>Are the tests well thought?</p>\n</blockquote>\n\n<p>As far as I can tell everything is covered. The test library doesn't seem to provide any information about code coverage and that would be interesting and helpful as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:49:20.430",
"Id": "425636",
"Score": "3",
"body": "`sizeof(*data)` has no relation to actual size of pointed data. It is `sizeof(void)`, which is a compilation error, unless a GCC extension is used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:53:05.260",
"Id": "425638",
"Score": "1",
"body": "@vnp Thank you, I've removed that section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T17:52:53.630",
"Id": "425644",
"Score": "6",
"body": "I can put function pointers in `queue_t` but I don't know how to implement a `queue->size()` that doesn't require the queue as parameter (i.e. `queue->size(queue)`). Function pointers don't provide a `this` (like in Java for example), and C has no closures afaik."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:15:56.433",
"Id": "425660",
"Score": "4",
"body": "Putting function pointers into the structure would also inflate the size of the queue object itself. If the API has N functions, then each instance of the queue would be increased by `N*sizeof(void*)` bytes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T03:10:34.843",
"Id": "425683",
"Score": "7",
"body": "Downvoted because object oriented is a really bad API idea for C. C isn't an object oriented language. Don't try to make it one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T10:25:52.273",
"Id": "425718",
"Score": "1",
"body": "@Gabriel: you're correct, `queue->size(queue)` would be the only practical way to make this suggestion work. (If you want `queue->size()` to work, you need a separate definition of the function for every size that exists in your program, because the caller won't pass a pointer to the `queue` object that contained the function pointer). As others commented, it's not a good suggestion in the first place for efficiency and style reasons. It's highly likely to defeat the compiler's ability to inline it as a simple access to a variable inside the struct, as well as being non-idiomatic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T11:42:15.230",
"Id": "425720",
"Score": "0",
"body": "@OscarSmith You are correct that C is not an object oriented language, however C++ started as \"C with Objects\" in the 1980's. The first C++ compilers were written as pre-processors to the C compiler in C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T11:44:17.117",
"Id": "425721",
"Score": "0",
"body": "@Gabriel You are correct without macros I can't figure out how to do it as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T12:03:21.060",
"Id": "425722",
"Score": "0",
"body": "@OscarSmith Bowing to community pressure the section on the API has been removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:38:54.717",
"Id": "425750",
"Score": "0",
"body": "Force-fitting object orientation (especially in languages without built-in OO) generally leads to software bloat and a steady stream of bugs. If the library *needs* to be object-oriented, then just use C++."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T16:38:45.370",
"Id": "220292",
"ParentId": "220288",
"Score": "4"
}
},
{
"body": "<p>This looks really nice! Here we go:</p>\n\n<blockquote>\n <p>Is the API well thought and idiomatic?</p>\n</blockquote>\n\n<p>Mostly. For a library as simplistic as this, you probably want to avoid creating a special enum when returning <code>NULL</code> on error will suffice.</p>\n\n<ul>\n<li>For this you could make the <code>QUEUE_initialize()</code> function return a pointer to the <code>queue_t</code> instead of having a <code>queue_t**</code> passed as an argument. If the allocation fails, it can simply return <code>NULL</code> (you may even consider having the end-user allocate the struct and make the function only initialize it). For example:</li>\n</ul>\n\n<pre><code>queue_t *QUEUE_initialize()\n{\n queue_t *queue = (queue_t*)calloc(1, sizeof(queue_t));\n\n if (queue == NULL) return NULL;\n\n queue->front = NULL;\n queue->back = NULL;\n queue->size = 0;\n\n return queue;\n}\n</code></pre>\n\n<p>Alternatively, to provide \"mechanism not policy\" with respect to how memory is allocated:</p>\n\n<pre><code>void QUEUE_initialize(queue_t *queue)\n{\n queue->front = NULL;\n queue->back = NULL;\n queue->size = 0;\n}\n</code></pre>\n\n<p>As you can see, this greatly simplifies the implementation in addition to providing the user with more flexibility.</p>\n\n<ul>\n<li>If <code>QUEUE_peek()</code> returns the pointer argument on success and <code>NULL</code> on failure, you could get rid of the enum and have fewer lines of code:</li>\n</ul>\n\n<pre><code>void *QUEUE_peek(queue_t* queue, void* data, size_t size)\n{\n if (queue->size == 0) return NULL;\n\n memcpy(data, queue->front->data, size);\n return data;\n}\n</code></pre>\n\n<p>In general, you want to have as few lines of codes as possible, as each line is a potential for bugs.</p>\n\n<blockquote>\n <p>Does the code look \"modern\" (i.e. uses modern conventions etc)?</p>\n</blockquote>\n\n<p>Yes, except for the non-standard <code>#pragma once</code> in <code>queue.h</code>. Personally, I would use lowercase function names (<code>queue_size()</code> and not <code>QUEUE_size()</code>, etc.), but this is just personal preference.</p>\n\n<blockquote>\n <p>Is the code efficient in terms of memory usage?\n Are the tests well thought?</p>\n</blockquote>\n\n<p>Yes</p>\n\n<blockquote>\n <p>Is the code free of undefined behavior, memory leaks etc?</p>\n</blockquote>\n\n<p>Some of the functions (<code>QUEUE_peek()</code>, <code>QUEUE_dequeue</code>) have a potential for the user to make mistakes by having the user specify the size separate from the data. You should probably treat the user's pointers as opaque data or add a <code>size_t</code> to the <code>node_t</code> structure. At the same time, I do not believe your library should be responsible for checking for null pointers within e.g. the initialization function. If the user tried to <code>malloc()</code> a struct but didn't check if it was successful, they may have already passed the pointer around to other parts of their program, making this check redundant. However, as @bta mentions, your implementation is vulnerable to a nosy user and shouldn't be using the <code>_t</code> suffix for structs.</p>\n\n<p>Depending on how old your compiler is, you may want to mark the <code>QUEUE_size()</code> function as <code>inline</code> or define it as a macro. While some may argue that <code>QUEUE_size()</code> is redundant and should be removed, the library user should not have to know about the internals of the struct. If you wanted to stay true to C, I would go as far as to remove the typedefs and only reference the structs as <code>struct foo</code>. I would also refrain from adding any function pointers to the struct, as this leads to some unnecessary complexity (read: bloat). If the API needs to be object oriented, then just use C++.</p>\n\n<p>To have a more memory-allocation agnostic <code>free()</code> function, you might want to use a callback function. In addition, your library does not need to know about what kinds of things the user is using the pointers for (what if they just wanted to post message ids instead of actual pointers), nor does the user need to know about how the queue is implemented. To avoid polluting the user's namespace, you might want to place some of the header definitions in the c file to prevent it from being visible outside that translation unit.</p>\n\n<p>Overall, the improved library might look like this(header guards omitted because they are considered bad style by some):</p>\n\n<p><strong>queue.h</strong></p>\n\n<pre><code>#include <stdbool.h>\n\nstruct queue;\n\n/* Required behavior: node_alloc returns NULL on failure */\ntypedef void *(*node_alloc_fn)(size_t size);\ntypedef void (*node_free_fn)(void *node);\n\nvoid queue_initialize(struct queue *queue);\ninline size_t queue_size(struct queue *queue);\nbool queue_enqueue(struct queue *queue, void *data, node_alloc_fn node_alloc);\nvoid *queue_peek(struct queue *queue);\nvoid *queue_dequeue(struct queue *queue, node_free_fn node_free);\nvoid queue_free_nodes(struct queue *queue, node_free_fn node_free);\n</code></pre>\n\n<p><strong>queue.c</strong></p>\n\n<pre><code>#include \"queue.h\"\n\nstruct node\n{\n void *data;\n struct node *next;\n};\n\nstruct queue\n{\n struct node *front;\n struct node *back;\n size_t numitems;\n};\n\n\nvoid queue_initialize(struct queue *queue)\n{\n queue->front = NULL;\n queue->back = NULL;\n queue->numitems = 0;\n}\n\ninline size_t queue_size(struct queue *queue)\n{\n return queue->numitems;\n}\n\nbool queue_enqueue(struct queue *queue, void *data, node_alloc_fn node_alloc)\n{\n /* Not including a default value for node_alloc since malloc() might not exist */\n\n struct node *node = (struct node*)node_alloc(sizeof(struct node));\n if (!node) return false;\n\n node->data = data;\n node->next = NULL;\n\n if (queue->size == 0)\n {\n queue->front = node;\n queue->back = node;\n }\n else\n {\n queue->back->next = node;\n queue->back = node;\n }\n\n (queue->numitems)++;\n return true;\n}\n\n/* Just get the first value in the queue, the user chooses if it gets copied */\nvoid *queue_peek(struct queue *queue)\n{\n if (queue->numitems == 0) return NULL;\n return queue->front->data;\n}\n\n/* Instead of a data parameter, just return the value */\nvoid *queue_dequeue(struct queue *queue, node_free_fn node_free)\n{\n /* Not including a default value for node_free since free() might not exist */\n if (!queue_peek(queue)) return NULL;\n\n /* All this function needs to do is unlink the first member.\n Leave it up to the user to decide if it needs to be freed */\n struct node *front = queue->front;\n if (front == queue->back)\n {\n queue->front = NULL;\n queue->back = NULL;\n }\n else\n {\n queue->front = front->next;\n }\n\n (queue->numitems)--;\n return front;\n}\n\nvoid queue_free_nodes(struct queue *queue, node_free_fn node_free)\n{\n /* Not including a default value for node_free since free() might not exist */\n struct node *current = queue->front;\n\n while (current)\n {\n struct node *next = current->next;\n node_free(current);\n current = next;\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T10:27:57.030",
"Id": "425719",
"Score": "3",
"body": "+1 for passing an already-allocated `queue` to the init function. That lets the caller use automatic or static storage for the queue's control block, not forcing dynamic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T12:17:17.520",
"Id": "425724",
"Score": "0",
"body": "If I remove the queue allocation from `QUEUE_initialize` I would still have to provide a `QUEUE_free` function in order to free the nodes. Wouldn't a `QUEUE_free` function that doesn't `free` the queue look a bit awkard? Your point does make sense and I like it, I'm just trying to figure out a non-misleading, self explanatory API."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:37:19.220",
"Id": "425748",
"Score": "0",
"body": "@Gabriel You could just require the user to manually call `free()`. If the user `malloc()`ed the struct initially, it's not any harder to `free()` it. It also allows you to use the library for e.g. embedded systems which might not have a heap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:44:22.743",
"Id": "425754",
"Score": "0",
"body": "@hsdfhsdal Yes, the user would be responsible for freeing the queue, but I would still need to provide a `QUEUE_free` function for freeing the nodes I allocated inside `QUEUE_enqueue`. So the user would need to place a `QUEUE_free(queue)` before every call to `free(queue)`, otherwise the nodes would leak, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:46:05.597",
"Id": "425755",
"Score": "0",
"body": "@Gabriel Depending on the what the user stores in the queue, you might want to just have a callback function."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T19:28:01.487",
"Id": "220309",
"ParentId": "220288",
"Score": "13"
}
},
{
"body": "<p>None of your <code>QUEUE_*</code> functions validate their input arguments before using them. <code>NULL</code> pointers will be a problem, particularly for the pointer-to-pointer arguments.</p>\n\n<p>C's memory-allocation functions return a <code>void*</code>, which implicitly converts to any other pointer type. This means that you don't need to typecast the result of <code>calloc</code>. Doing so can actually mask certain errors that the compiler would otherwise catch.</p>\n\n<p>Your <code>node_t</code> structure is missing a vital piece of information: the size of the target object. This would be okay if your queue dealt purely with pointers. In several places, though, you access the actual data behind that pointer. Without knowing the size of that data, you're opening up yourself to tons of buffer overrun problems. For example, if I queue a char and then call <code>QUEUE_peek()</code> with a size of 1 MB, bad things happen. Trusting the caller to keep track of this is problematic. First and foremost, you shouldn't trust the user to do the right thing. More importantly, requiring a second queue to keep track of object sizes in the first queue makes your implementation difficult to use. You have two options for resolving this. If the queue will only hold objects of the same type, replace <code>void* data</code> with a pointer to a specific type (clever macros can even make this type user-configurable like a C++ template). The other option is to add a <code>size_t size</code> member to <code>struct node</code>. If you go with the latter, you'll need to either re-design <code>peek</code>/<code>dequeue</code> to allocate the output buffer internally, or add a function that returns the size of the object at the head of the queue.</p>\n\n<p>Your code is very vulnerable to what I sometimes call the \"nosy user\". That is, a user that pokes around at the internals of your implementation. If a user decides to alter the value of a queue's <code>size</code> member (either through malice or incompetence), your code will break in a number of places. I recommend hiding the implementation details from the user. The easiest way to do this would be to move the definitions of <code>struct queue</code> and <code>struct node</code> into the .c file. Then, add the line <code>struct queue;</code> to the top of the header (a forward declaration). This allows the user to create pointers to queue objects - which is all they need in order to use your API - but doesn't let them poke about at the internals. This is similar to how <code>stdio.h</code> implements the <code>FILE</code> type. Side note: nice work on the clean API that only requires the user to know about a single pointer type. Most first passes leak a lot more implementation details than that.</p>\n\n<p>Expanding on what ratchet freak mentioned above, your API is asymmetrical. You enqueue a <em>pointer</em> to an object, but you dequeue a <em>copy</em> of the <em>content</em> of the object. This can cause problems when you queue objects that have been dynamically allocated. Once you dequeue that object and want to free it, you have no real way of figuring out the original pointer so that you can pass it to <code>free()</code>. If the dequeue function returned the pointer instead, the caller would have all of the information they'd need.</p>\n\n<p>Having enqueue/dequeue only deal in pointers would avoid another problem as well. The current dequeue implementation makes a complete copy of the queued object, which can have <em>severe</em> performance penalties. Using large objects with your queue would lead to a lot of memory churn plus a lot of time wasted copying bits unnecessarily. Users could always queue pointers to these objects instead of the objects themselves, but that's more of a workaround than a solution.</p>\n\n<p>Portability issues:</p>\n\n<p>The POSIX standard reserves typenames that end in <code>_t</code>. For the sake of portability, it's best if you avoid using that suffix on your custom types. The risk of name collisions is particularly high when you have basic, generic names like <code>queue_t</code> and <code>node_t</code>.</p>\n\n<p><code>#pragma once</code> is not standard C. It's a relatively common extension but if you want to ensure that your code works with any compiler/platform, use a traditional <code>#define</code>-based include guard instead.</p>\n\n<p>Minor things:</p>\n\n<p>In general, I usually advise to avoid typedef-ing struct types. It hides the fact that what you're dealing with are actually structures. Plus, you now have two names for the same type (<code>struct node</code> and <code>node_t</code>), which can cause confusion and make refactoring more difficult. There are even some contexts (like forward declarations) where you can use the <code>struct</code> name but the <code>typedef</code>-ed name won't work.</p>\n\n<p>I can see where the name for <code>queue->size</code> could be confusing. \"Size\" generally refers to how much storage space something takes. A name like \"count\" or \"length\" could make it more obvious what this field measures.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:03:20.823",
"Id": "425738",
"Score": "1",
"body": "What do you think about removing `enum queue_ret`? My original intent was to provide a mechanism similar to exceptions, but... looking at the code now, it seems to me it adds unnecessary complexity. I could make `QUEUE_initialize`, `QUEUE_peek` and `QUEUE_dequeue` return the actual pointer (or `NULL` on failure) and `QUEUE_enqueue` return a `bool`. It simplifies the tests a lot, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:41:36.213",
"Id": "425752",
"Score": "3",
"body": "@Gabriel I think it's best to remove the enum, as a null pointer can be returned if one of the functions fail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:39:14.997",
"Id": "425774",
"Score": "0",
"body": "@Gabriel You really only need custom error codes if a function can fail for multiple reasons and the caller needs to know the precise failure reason in order to recover. I don't think that's the case for your API as it currently stands."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:49:33.967",
"Id": "425775",
"Score": "0",
"body": "@Gabriel Even if there were multiple failure reasons, you could still use errno or similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T11:53:11.800",
"Id": "426159",
"Score": "0",
"body": "I'm accepting this answer because I think it provides the most insightful feedback, but all other answers were very much appreciated, and I hope other members don't refrain from submiting new reviews in the future if they want to."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T02:32:12.253",
"Id": "220325",
"ParentId": "220288",
"Score": "24"
}
}
] | {
"AcceptedAnswerId": "220325",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T14:40:13.537",
"Id": "220288",
"Score": "28",
"Tags": [
"c",
"unit-testing",
"queue"
],
"Title": "FIFO data structure in pure C"
} | 220288 |
<p>I'm new to multi-threading and concurrency. I've got 2 lists that I want to process concurrently. Processing both lists requires a lot of time.sleep() and waiting for other servers to finish, so I figured rather than do one at a time I could process them simultaneously.</p>
<p>The first list is un-validated items and I try to validate them and if successful add them to the second list for processing. I want to start validating items in the first list and then while that is going start on the processing of the 2nd list. I've since found out I wanted a Queue for the 2nd list and that has helped but I can't help but feel that even though this works I'm missing something.</p>
<pre><code>def process_sr(jira, tuple, args, log):
... # does some pretty straight forward stuff but lots of waiting
return "done"
def waiting_for_build(tuple, validqueue, log):
sr, pr = tuple
iter = 0
log.info("Waiting for {} to re-build".format(pr))
while iter < 30: # don't add. It's been more than 10 minutes and we need to finish
log.debug("%s still waiting for Jenkins", pr)
sleep(20)
status = pr.build_status()
if status is None:
break # don't add. Build finished "FAILURE" or didn't build in 10 min
elif status == "Wait":
iter += 1
elif status == "Done":
validqueue.put((sr,pr))
def build_lists(jira, log):
validqueue = Queue()
waiting_for_jenkins = []
... # this builds the two lists
return validqueue, waiting_for_jenkins
def main():
args, log = cli_args()
jira = JiraWrapper()
validqueue, waiting_for_jenkins = build_lists(jira, log)
workers = len(waiting_for_jenkins) + validqueue.qsize()
threads = []
for item in waiting_for_jenkins:
name = str(item[1])
threads.append(threading.Thread(target=waiting_for_build, name=name, args=(item, validqueue, log)))
threads[-1].start()
def worker(i):
log.debug("started")
results = []
while True:
log.debug("blocking on queue")
item = validqueue.get()
if item is None:
log.debug("done")
return results
log.debug("got item %s", item)
result = process_sr(jira, item, args, log)
results.append({result:item})
log.debug("task %s done", item)
validqueue.task_done()
log.debug("%d workers will be spawned", workers)
if not workers:
log.info("Nothing to do here")
else:
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor: # can't use thread_name_prefix until python 3.6
futures = executor.map(worker, range(workers))
for thread in threads:
thread.join()
validqueue.join()
for i in range(workers):
validqueue.put(None)
for future in futures:
log.debug(future)
exit(0)
if __name__ == '__main__':
main()
</code></pre>
<p>I've included as much as I think is needed. The main() method and specifically the two multi-threaded bits are where I'm looking for feedback.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T17:11:47.337",
"Id": "220296",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"multithreading",
"concurrency"
],
"Title": "Process 2 lists concurrently with the first list adding to the second"
} | 220296 |
<p>Hi I am trying to get into Rust by implementing a small library for vector calculations. </p>
<p>I am mainly asking to point out whether I chose a valid approach. I also am interested in comments on the overall details I might have missed or got the wrong way.</p>
<p>So for my <code>Vec3</code> implementation I basically declared a custom type which is an array of length 3. Afterwards I am simply implementing <code>Traits</code> for this type. For now I only implemented it for <code>f32</code>.</p>
<pre><code>pub type Vec3<T = f32> = [T; 3];
pub trait Vector3<T> {
/// Creates a new Vec3 with its values initialized to `[0.0, 0.0, 0.0]`.
fn new() -> Self;
/// Creates a new `Vec3` based on the given `x`, `y` and `z` values.
fn from_values(x: f32, y: f32, z: f32) -> Vec3<T>;
/// Calculates the scalar dot product of two `Vec3`'s.
fn dot(a: Vec3<T>, b: Vec3<T>) -> f32;
/// Performs multiplication between two `Vec3`.
fn multiply(self, a: Vec3) -> Vec3;
/// Calculates the sum of two `Vec3` components.Vec3
fn add(self, a: Vec3) -> Vec3;
/// Scales a `Vec3` by a scalar value.
fn scale(self, x: f32) -> Vec3;
}
impl Vector3<f32> for Vec3<f32> {
/// Creates a new Vec3 with its values initialized to `[0.0, 0.0, 0.0]`.
///
/// ```
/// use glMatrix_rs::vec3::*;
///
/// let result = Vec3::new();
/// assert_eq!([0.0, 0.0, 0.0], result);
/// ```
fn new() -> Vec3<f32> {
[0.0, 0.0, 0.0]
}
/// Creates a new `Vec3` based on the given `x`, `y` and `z` values.
///
/// ### Arguments
///
/// * `x` - The first vector component.
/// * `y` - The second vector component.
/// * `z` - The third vector component.
///
/// ```
/// use glMatrix_rs::vec3::*;
///
/// let result = Vec3::from_values(0.0, 1.0, 2.0);
/// assert_eq!([0.0, 1.0, 2.0], result);
/// ```
fn from_values(x: f32, y: f32, z: f32) -> Vec3 {
[x, y, z]
}
/// Calculates the scalar dot product of two `Vec3`'s.
///
/// ### Arguments
///
/// * `a` - The first vector for `dot` calculation.
/// * `b` - The second vector for `dot` calculation.
///
/// ```
/// use glMatrix_rs::vec3::*;
/// let a = Vec3::from_values(2.0, 2.0, 2.0);
/// let b = Vec3::from_values(2.0, 2.0, 2.0);
/// assert_eq!(12.0, Vec3::dot(a, b));
/// ```
fn dot(a: Vec3, b: Vec3) -> f32 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
/// Performs multiplication between two `Vec3`.
///
/// ### Arguments
///
/// * `a` - Vector by which `self` will be multiplied.
///
/// ```
/// use glMatrix_rs::vec3::*;
/// let mut out = Vec3::new();
/// let a = Vec3::from_values(1.0, 2.0, 3.0);
/// let b = Vec3::from_values(2.0, 2.0, 2.0);
/// assert_eq!([2.0, 4.0, 6.0], a.multiply(b));
/// ```
fn multiply(self, a: Vec3) -> Vec3 {
[self[0] * a[0], self[1] * a[1], self[2] * a[2]]
}
/// Calculates the sum of two `Vec3` components.Vec3
///
/// ### Arguments
///
/// * `a` - Vector which will be added to `self`.
///
/// ```
/// use glMatrix_rs::vec3::*;
/// let x = Vec3::from_values(1.0, 2.0, 3.0);
/// let a = Vec3::from_values(3.0, 2.0, 1.0);
/// assert_eq!([4.0, 4.0, 4.0], x.add(a));
/// ```
fn add(self, a: Vec3) -> Vec3 {
[self[0] + a[0], self[1] + a[1], self[2] + a[2]]
}
/// Scales a `Vec3` by a scalar value.
///
/// ### Arguments
///
/// * `x` - Scalar value by which the vector will be scaled.
///
/// ```
/// use glMatrix_rs::vec3::*;
/// let a = Vec3::from_values(1.0, 2.0, 3.0);
/// assert_eq!([2.0, 4.0, 6.0], a.scale(2.0));
/// ```
fn scale(self, x: f32) -> Vec3 {
[self[0] * x, self[1] * x, self[2] * x]
}
}
</code></pre>
<p>You can clone, <code>build</code> and <code>test</code> it any time from my <a href="https://github.com/Kaesebrot84/glMatrix-rs" rel="nofollow noreferrer">GitHub repository</a>.</p>
| [] | [
{
"body": "<p>My first recommendation is to use <code>std::ops</code>. Try writing implementations of <code>ops::Add</code> for addition, <code>ops::Mul<Vec3<T>></code> for cross product, and <code>ops::Mul<T></code> for scaler-vector multiplication. Not only does implementing these standard traits make your code more interoperable with other Rust code, but it also gives you operator overloading, so you can use <code>+</code> and <code>*</code> on your vectors.</p>\n\n<p>Second, I would question the user of the trait <code>Vector3<f32></code>. Why do you need a trait? I would just put your operations in the implementation of <code>Vec3<T></code> itself</p>\n\n<pre><code>impl <T> Vec3<T> {\n\n// ... methods ...\n\n}\n</code></pre>\n\n<p>Looking forward to seeing your completed code. This will even more interesting once you get generics working.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:14:35.650",
"Id": "425893",
"Score": "0",
"body": "Thanks for your answer. I think I need the traits, as my type alias [does not create a new type](https://stackoverflow.com/a/35569079/681705). If I try your approach I get `impl requires a base type`. Also see this [Github issue](https://github.com/rust-lang/rust/issues/9767)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:26:36.697",
"Id": "425895",
"Score": "0",
"body": "Oh, I missed that. If you can't have a really struct, that is very limiting. Do you have objections to using a struct with an array member instead of a type alias?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:37:55.313",
"Id": "425896",
"Score": "0",
"body": "It depends on which advantages and disadvantages the two approaches have :) Not sure about this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:43:33.257",
"Id": "220315",
"ParentId": "220297",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T17:19:13.567",
"Id": "220297",
"Score": "0",
"Tags": [
"rust",
"library",
"vectors"
],
"Title": "Vector calculation in Rust"
} | 220297 |
<p>So I have the following models:</p>
<pre class="lang-rb prettyprint-override"><code>class Poll < ApplicationRecord
validates :title, presence: true, allow_blank: false
validates :options, presence: true
has_many :options, dependent: :destroy
end
class Option < ApplicationRecord
validates :title, presence: true, allow_blank: false
belongs_to :poll
end
</code></pre>
<p>And given the following data:</p>
<pre><code>{
title: "My poll",
options: [
{title: "Option 1"},
{title: "Option 2"},
{title: "Option 3"},
]
}
</code></pre>
<p>I would like to create a poll with 3 options.</p>
<p>This is my solution:</p>
<pre><code> # POST /polls
def create
@poll = Poll.new(poll_params)
params[:options].each do |option|
@poll.options.new option.permit(:title)
end
if @poll.save
render json: @poll, status: :created, location: @poll
else
render json: @poll.errors.full_messages, status: :unprocessable_entity
end
end
</code></pre>
| [] | [
{
"body": "<p>You should be able to do this with <code>accepts_nested_attributes_for</code>.\n see <a href=\"https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for\" rel=\"nofollow noreferrer\">https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for</a></p>\n\n<pre><code>class Poll < ApplicationRecord\n validates :title, presence: true, allow_blank: false\n validates :options, presence: true\n\n has_many :options, dependent: :destroy\n accepts_nested_attributes_for :options \nend\n\ndef poll_params\n params.require(:poll).permit(:title,\n options: :title)\nend \n\ndef create\n @poll = Poll.new(poll_params)\n\n if @poll.save\n render json: @poll, status: :created, location: @poll\n else\n render json: @poll.errors.full_messages, status: :unprocessable_entity\n end\nend \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:01:17.283",
"Id": "425810",
"Score": "0",
"body": "It works, with a small catch. The parameter must be called `options_attributes`, instead of `options`\n\nThe strong params must be:\n`params.require(:poll).permit(:title, options_attributes: :title)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T19:39:05.013",
"Id": "220372",
"ParentId": "220298",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220372",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T17:47:21.863",
"Id": "220298",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Ruby on Rails - Creating many models associated with another one"
} | 220298 |
<p>As a continuation to my question <a href="https://codereview.stackexchange.com/questions/220179/design-for-a-very-simple-e-shop">Design for a very simple e-shop</a></p>
<p>I made some of the changes proposed but not all of the proposed for example I was not able to make a factory for the setAttributes. And if anyone could give me a hint how to get rid of the if statements in the factory for the production of the IProducts i would appreciate it. And of course any other advice's would be welcome especially if I am using the shared_ptr correctly. </p>
<p>User.h</p>
<pre><code>#pragma once
#include"Products.h"
class IUser
{
public:
IUser(const std::string myName, const double myPassword) { name = myName, password = myPassword; }
const std::string getName() const
{
return name;
}
const double getPassword() const
{
return password;
}
protected:
std::string name;
double password;
};
class Client : public IUser
{
public:
Client(const std::string myName, double passWord) :IUser(myName, passWord) {};
void buyProduct(std::shared_ptr<IProducts> currentProduct) { boughtProducts.push_back(currentProduct); }
void checkOut() {
for (size_t i = 0; i < boughtProducts.size(); ++i)
{
std::cout << "Your " << i + 1 << " bought product is " << boughtProducts[i]->getProductName() << " with the above charecteristics " << std::endl;
boughtProducts[i]->Display();
}
}
private:
std::vector<std::shared_ptr<IProducts>> boughtProducts;
};
</code></pre>
<p>Products.h</p>
<pre><code>#pragma once
#include <iostream>
#include <string>
#include <vector>
// Create an Interface for Product Objects
class IProducts
{
public:
// Virtual Function to get the name of the product implementing the interface
virtual const std::string getProductName() const = 0;
// Virtual Function to Display the names of all components of a class implementing the interface
virtual void DisplayComponents() = 0;
// Virtual Function to display the values of the components of a class implementing the interface
virtual void Display() = 0;
// Virtual Function to set the components to desired values
virtual void setAttributes() = 0;
};
// Concretion of Product Interface
class PC_Towers final : public IProducts
{
public:
// Function to set the member variables of the class
void setAttributes ()
{
std::cout << "Please enter Memory size for PC_Tower in GB : ";
// MAke sure that the input in numeric
while(!(std::cin >> this->Memory))
{
std::cout << "All input's must be numeric " << std::endl;
break;
}
std::cout << "Please enter CPU size for PC_Tower in GHz : ";
while (!(std::cin >> this->CPU))
{
std::cout << "All input's must be numeric " << std::endl;
break;
};
}
// Function to get the Name of the product
const std::string getProductName() const { return this->productName; }
// Function to display the names of the components of the class
void DisplayComponents() { std::cout<<"The Tower is composed from : 1) Memory 2) CPU " << std::endl; }
// Function to display the values of the member variables
void Display()
{
std::cout << "Your Tower has a Memory of " << this->Memory << " GB and a CPU of " << this->CPU << " GHZ" << std::endl;
}
private:
double Memory;
double CPU;
const std::string productName = "PC_Tower";
};
// Another concrition on the IProduct interface the same as the one before
class PC_Screen : public IProducts
{
public:
void setAttributes ()
{
std::cout << "Please enter size of your Screen in inches: " ;
while (!(std::cin >> this->Size_inch))
{
std::cout << "All input's must be numeric " << std::endl;
break;
}
}
const std::string getProductName() const { return this->productName; }
void DisplayComponents() { std::cout << "The screen is composed from a screen measured in inches " << std::endl; }
void Display()
{
std::cout << "Your screen is " << this->Size_inch << " inches " << std::endl;
}
private:
double Size_inch;
const std::string productName = "PC_Screen";
};
// Concrition of IProducts
class Personal_Computer : public IProducts
{
public:
// Function to set the attributes of the member variable. In this case the function works as a decorator
// arround the setAttributes of the IProduct adding functionalities to it
void setAttributes()
{
Tower.setAttributes();
Screen.setAttributes();
std::cout << " Please enter size of your HardDics in GB : " ;
while (!(std::cin >> this->HardDisc))
{
std::cout << "All input's must be numeric " << std::endl;
break;
}
}
const std::string getProductName() const { return this->productName; }
// Decorate the DisplayComponents() and add functionalities
void DisplayComponents()
{
std::cout << "Personal Computer is composed from: 1) Tower 2) PC Screen 3) Hard Disc" << std::endl;
Tower.DisplayComponents();
Screen.DisplayComponents();
}
// Decorate the Display() and add functionalities
void Display()
{
Tower.Display();
Screen.Display();
std::cout << "Your Hard Disc has size : " << this->HardDisc << " GB " << std::endl;
}
private:
PC_Towers Tower;
PC_Screen Screen;
double HardDisc;
const std::string productName = "Personal_Computer";
};
// Concretion of Iproduct
class Work_Station : public IProducts
{
public:
void setAttributes()
{
Computer.setAttributes();
std::cout << "Please Enter your Operating System " ;
while (!(std::cin >> this->OperatingSystem))
{
std::cout << "Operating system must be string " << std::endl;
break;
}
}
const std::string getProductName() const { return this->productName; }
void DisplayComponents()
{
std::cout << "Work station is composed from : 1) Personal computer 2) Operating System (Linux or Windows) " << std::endl;
Computer.DisplayComponents();
}
void Display()
{
Computer.Display();
std::cout << "Your Operating System is :" << this->OperatingSystem << std::endl;
}
private:
Personal_Computer Computer;
std::string OperatingSystem;
std::string productName = "WorkStation";
};
</code></pre>
<p>ProductsFactory.h</p>
<pre><code>#pragma once
#include"Products.h"
class IProductFactory
{
public:
virtual std::shared_ptr<IProducts> createProduct(std::string) = 0;
};
// Concretion of Interface for IProduct creation. This Factory produces IProducts based on the an string input
// to the function ( like a user input)
class UserInputFactoryProduct : public IProductFactory
{
public:
std::shared_ptr<IProducts> createProduct(std::string myProduct)
{
std::shared_ptr<IProducts> product;
if (myProduct == "PC_Tower")
product = std::make_shared<PC_Towers>();
else if (myProduct == "PC_Screen")
product = std::make_shared<PC_Screen>();
else if (myProduct == "Personal_Computer")
product = std::make_shared<Personal_Computer>();
else if (myProduct == "WorkStation")
product = std::make_shared<Work_Station>();
else
product = nullptr;
return product;
}
};
</code></pre>
<p>e_shop.h</p>
<pre><code>#pragma once
#include"Products.h"
// Class e-shop to add and display all the products of the shop
class e_shop
{
public:
// Function to add products to the shop
void addProduct(std::shared_ptr<IProducts>newProduct) { this->allProducts.push_back(newProduct); }
// Function to display all the products of the shop
void desplayAllProducts()
{
for (auto e:allProducts)
std::cout << e->getProductName() << std::endl;
}
private:
// vector to keep all the products of the shop
std::vector< std::shared_ptr<IProducts> > allProducts;
};
</code></pre>
<p>main.cpp</p>
<pre><code>#include "Products.h"
#include "e_shop.h"
#include"ProductsFactory.h"
#include "User.h"
int main()
{
Client first("Aris", 12345);
// create some products
std::shared_ptr< IProducts > Product1 = std::make_shared<PC_Towers>();
std::shared_ptr< IProducts > Product2 = std::make_shared<PC_Screen>();
std::shared_ptr< IProducts > Product3 = std::make_shared<Personal_Computer>();
std::shared_ptr< IProducts > Product4 = std::make_shared<Work_Station>();
// create an e-shop and add the products created
e_shop myEshop;
myEshop.addProduct(Product1);
myEshop.addProduct(Product2);
myEshop.addProduct(Product3);
myEshop.addProduct(Product4);
myEshop.desplayAllProducts();
std::string finish;
while(finish != "N")
{
std::string choosedProduct;
std::cout << std::endl;
std::shared_ptr<IProducts> myProduct = nullptr;
UserInputFactoryProduct ProductFactory;
// choose a product and use factory to create the object based on the user input
while (myProduct == nullptr)
{
std::cout << "Chose one of the above products : ";
std::cin >> choosedProduct;
myProduct = ProductFactory.createProduct(choosedProduct);
} ;
// display all the attributes of the product
myProduct->DisplayComponents();
// let the user to add values to components
myProduct->setAttributes();
// display the product ith the values of the user
first.buyProduct(myProduct);
std::cout << "Do you want to continue: Y or N :" ;
std::cin >> finish;
}
std::cout << first.getName() << " bought :" << std::endl;
first.checkOut();
system("pause");
}
</code></pre>
| [] | [
{
"body": "<p>There are some things that seem unclear or can be improved.</p>\n\n<ul>\n<li>Lots of typos and lots of inconsistent formatting make this harder to read than it should be</li>\n<li>Not a fan of the \"I\" prefix for interface classes but that is purely subjective</li>\n<li>Why is there an interface for everything? Do you plan to extend this heavily in the future?</li>\n<li>Why initialize <code>IUser</code> in the ctor but other classes via ctor init list?</li>\n<li>You could possibly pass and return more arguments by reference</li>\n<li>As previously suggested you can use a for each loop</li>\n<li>Possibly change to actual include guards</li>\n<li>As previously suggested mark classes you don't intend to derive from any more as <code>final</code></li>\n<li>Mark virtual functions you override with <code>override</code> and possibly <code>final</code></li>\n<li>Why are you using <code>this</code>?</li>\n<li>Missing initialization for some members</li>\n<li>Not sure about your use of factory. AFAIK they excel at defered creation of complex objects and are not really used to their full potential here</li>\n<li>Don't compare to <code>nullptr</code></li>\n<li>Don't use <code>std::endl</code> unless you need to flush </li>\n<li><code>system(\"pause\");</code> is Windows only</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T19:21:38.867",
"Id": "220306",
"ParentId": "220300",
"Score": "2"
}
},
{
"body": "<p>As noted in another answer for this question and previously in an answer to your earlier question:</p>\n\n<p>It might be better to use a ranged for loop using iterators rather than an index for loop:</p>\n\n<pre><code> for (auto i : allProducts) {\n std::cout << i->getProductName() << std::endl;\n }\n</code></pre>\n\n<p>This may improve performance as well. It is equivalent to <code>for each</code> in other languages.</p>\n\n<p>Unlike some other languages such as PHP, the <code>this</code> keyword is not generally required in C++ and is generally not used. There may be certain special cases where it is required.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T12:35:11.857",
"Id": "220341",
"ParentId": "220300",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220306",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T17:59:06.307",
"Id": "220300",
"Score": "2",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Design for a simple a shop"
} | 220300 |
<p>I need to cut the time it takes to print a large string by ~50%. </p>
<p>I went from using <code>s1 + s2</code> to using <code>StringBuilder</code>, and instead of making several calls to <code>System.out.print</code> for each line, I create one large string by appending newlines to the <code>StringBuilder</code>, and then print that large string just once with <code>System.out</code>. </p>
<p>But my code is still way too slow (this is for a homework assignment and the code is not accepted by the automated hand-in system because it takes too long).</p>
<p>When the <code>StringBuilder</code> is printed, the string has ~100k lines</p>
<p>The relevant part of my code looks like this:</p>
<pre><code>public class Main {
public static void main (String[] args){
MyClass builder = new MyClass();
new ClassThatBuildsOnBuilder(builder);
System.out.println(builder.str.toString());
}
}
</code></pre>
<pre><code>public class MyClass {
private double[] coordinates = new double[]{0, 0, 0, 0};
public StringBuilder str = new StringBuilder();
private DecimalFormat formatter = new DecimalFormat("#0.0000");
public MyClass(){
}
public void changeValues(double[] coordinates){
this.coordinates = coordinates;
updateRow();
}
private void updateRow(){
for (double d : coordinates){
str.append(formatter.format(d));
str.append(" ");
}
str.append("\n");
}
</code></pre>
<p>Can this even be optimized further? I feel like this should be very close to a lower bound.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T18:27:29.987",
"Id": "425650",
"Score": "0",
"body": "add language tags?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T18:52:20.077",
"Id": "425652",
"Score": "0",
"body": "`new ClassThatBuildsOnBuilder(builder);` Does this line do anything?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:36:44.830",
"Id": "425697",
"Score": "0",
"body": "If you know the number of rows and the lenght of each row, you can calculate the final size of StringBuilder and specify it in the constructor to avoid unnecessary reallocations and array copies. Or at least you can estimate it to avoid most of them."
}
] | [
{
"body": "<ul>\n<li>Are you sure the bottleneck is the printing, as opposed to whatever <code>new ClassThatBuildsOnBuilder(builder);</code> is doing? </li>\n<li>Is <code>coordinates</code> always going to have a width of four?</li>\n<li>It appears you're building the whole string in memory, and then printing all your output at once at the end. While printing each line to standard-out individually may be slower, it also <em>may</em> take better advantages of the built-in output buffering. (Printing each word individually as you describe having originally done probably isn't a great idea.</li>\n</ul>\n\n<p>Would something like this work?</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> private void printRow(){\n System.out.format(\"#%.3f #%.3f #%.3f #%.3f%n\",\n coordinates[0],\n coordinates[1],\n coordinates[2],\n coordinates[3]);\n</code></pre>\n\n<p>You could also try a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#Formatter(java.lang.Appendable)\" rel=\"nofollow noreferrer\">Formatter</a>, which would let you use a StringBuilder as you already are, but also use printf syntax. </p>\n\n<p>Finally, I don't know how to take manual control of System.out's buffering behavior, but it's probably possible and may help. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T18:54:49.150",
"Id": "220304",
"ParentId": "220302",
"Score": "4"
}
},
{
"body": "<p>I don't think buffering is the problem or solution. Creating a gigantic buffer probably hurts if the recipient has, say, a 4k buffer for reading the results. That would mean the recipient can't start working before your code has finished completely, making the process completely serial instead of parallel. Instead you should try creating a smaller buffer (with the initial size defined in the constructor, so it doesn't do unnecessary reallocations) and flush it regularly. </p>\n\n<p>This is a bit of shooting in the dark as we don't know how the evaluator works.</p>\n\n<p>In Java creating temporary Strings in tight loops is often a performance killer. Find the APIs that let you format numbers straight into a stream or with minimal temporary strings. DecimalFormat can write directly to a StringBuffer. Try using that method instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:48:32.547",
"Id": "220330",
"ParentId": "220302",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T18:23:14.997",
"Id": "220302",
"Score": "1",
"Tags": [
"java",
"performance",
"strings",
"homework"
],
"Title": "Optimize printing massive strings to System.out with respect to time"
} | 220302 |
<p><strong>The goal of the code below is limited to the creation of the initial map only and not to the whole game mechanics itself.</strong></p>
<p>The rules are that there are 4 ships of length {2,3,4,5} and no ship may be placed adjacent or diagonally adjacent to another ship.</p>
<p>For now I plan to stay with the 10x10 grid with 4 ships. In my implementation, a <code>1</code> means that there is ship in that cell, and <code>0</code> otherwise. </p>
<p>I am not a Python developer, but since I am interested in learning it I decided to program this project using this language. <strong>Please</strong> scrutinize, nitpick my code. I want to get into the so called pythonic way.</p>
<p>This is the code for now (According to my tests, I think it is working as intended):</p>
<pre><code>import numpy as np
import random
grid_x = 10
grid_y = 10
number_of_ships = 4
class Ship:
def __init__(self, x, y, direction, length):
self.x = x
self.y = y
self.direction = direction
self.length = length
def generate_random_ship(self, rows, columns, length):
self.x = random.randrange(rows)
self.y = random.randrange(columns)
self.direction = random.randrange(4)
self.length = length
def print_ship(self):
print('x: %d, y: %d, direction: %d, length: %d' %(self.x,self.y,self.direction,self.length))
class Grid:
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
self.grid = np.zeros((rows, columns))
#Assume ship is already valid
def place_ship(self,ship):
for i in range(ship.length):
if ship.direction == 0: #up
self.grid[ship.x - i][ship.y] = 1
elif ship.direction == 1: #right
self.grid[ship.x][ship.y + i] = 1
elif ship.direction == 2: #down
self.grid[ship.x + i][ship.y] = 1
elif ship.direction == 3: #left
self.grid[ship.x][ship.y - i] = 1
def check_for_ship(self, x, y):
if x >= self.rows or x < 0 or y >= self.columns or y < 0:
return False
elif self.grid[x][y] == 1:
return True
else:
return False
def is_ship_valid(self, ship):
#up
if ship.direction == 0:
#if the ship won't fit
if ship.length > (ship.x + 1):
return False
else:
#Check for ships in the neighborhood
for i in range(ship.x, ship.x-ship.length, -1):
if (self.check_for_ship(i+1, ship.y-1) or self.check_for_ship(i+1, ship.y)
or self.check_for_ship(i+1, ship.y+1) or self.check_for_ship(i, ship.y-1)
or self.check_for_ship(i, ship.y) or self.check_for_ship(i, ship.y+1)
or self.check_for_ship(i-1, ship.y-1) or self.check_for_ship(i-1, ship.y)
or self.check_for_ship(i-1, ship.y+1)):
return False
#right
elif ship.direction == 1:
#if the ship won't fit
if ship.length > (self.columns - ship.y):
return False
else:
#Check for ships in the neighborhood
for i in range(ship.y, ship.y+ship.length):
if (self.check_for_ship(ship.x-1, i-1) or self.check_for_ship(ship.x, i-1)
or self.check_for_ship(ship.x+1, i-1) or self.check_for_ship(ship.x-1, i)
or self.check_for_ship(ship.x, i) or self.check_for_ship(ship.x+1, i)
or self.check_for_ship(ship.x-1, i+1) or self.check_for_ship(ship.x, i+1)
or self.check_for_ship(ship.x+1, i+1)):
return False
#down
elif ship.direction == 2:
if ship.length > (self.rows - ship.x):
return False
else:
#Check for ships in the neighborhood
for i in range(ship.x, ship.length+ship.x):
if (self.check_for_ship(i+1, ship.y-1) or self.check_for_ship(i+1, ship.y)
or self.check_for_ship(i+1, ship.y+1) or self.check_for_ship(i, ship.y-1)
or self.check_for_ship(i, ship.y) or self.check_for_ship(i, ship.y+1)
or self.check_for_ship(i-1, ship.y-1) or self.check_for_ship(i-1, ship.y)
or self.check_for_ship(i-1, ship.y+1)):
return False
#left
elif ship.direction == 3:
if ship.length > (ship.y+1):
return False
else:
#Check for ships in the neighborhood
for i in range(ship.y, ship.y-ship.length, -1):
if (self.check_for_ship(ship.x-1, i-1) or self.check_for_ship(ship.x, i-1)
or self.check_for_ship(ship.x+1, i-1) or self.check_for_ship(ship.x-1, i)
or self.check_for_ship(ship.x, i) or self.check_for_ship(ship.x+1, i)
or self.check_for_ship(ship.x-1, i+1) or self.check_for_ship(ship.x, i+1)
or self.check_for_ship(ship.x+1, i+1)):
return False
return True
battlefield = Grid(grid_x, grid_y)
ships = []
ship_length = 2
for _ in range(number_of_ships):
ship = Ship(random.randrange(grid_x), random.randrange(grid_y),
random.randrange(4), ship_length)
ships.append(ship)
ship_length += 1
for ship in ships:
valid_ship = battlefield.is_ship_valid(ship)
if valid_ship:
battlefield.place_ship(ship)
else:
while valid_ship == False:
ship.generate_random_ship(grid_x, grid_y, ship.length)
valid_ship = battlefield.is_ship_valid(ship)
battlefield.place_ship(ship)
print(battlefield.grid)
print()
for ship in ships:
ship.print_ship()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T21:03:18.350",
"Id": "425666",
"Score": "2",
"body": "@close-voter stating future plans doesn't make something 'not working as intended'. Given that they've tested the code too, it's harder to make a case that this is broken, as you've likely found an edgecase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T21:07:59.350",
"Id": "425667",
"Score": "0",
"body": "Edited the post a little bit to explicit my intentions with the given code."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T19:13:52.337",
"Id": "220305",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"battleship"
],
"Title": "Initial map modelling for Battleship game"
} | 220305 |
<p>My goal is to determine, of all of the currently visible cells in a collection view, which section has the most visible cells.</p>
<p>Start by getting the index paths for the visible cells:</p>
<pre><code>let visible = collectionView.indexPathsForVisibleItems // [IndexPath]
</code></pre>
<p>Originally I used an <code>NSCountedSet</code> followed by mapping and sorting.</p>
<pre><code>let counted = NSCountedSet(array: visible.map { $0.section })
let section = counted.allObjects.map { ($0, counted.count(for: $0)) }.sorted { $0.1 > $1.1 }.first?.0 as? Int
</code></pre>
<p>This works but I don't like <code>NSCountedSet</code> because it deals with <code>Any</code>.</p>
<p>I then replaced the use of <code>NSCountedSet</code> with <code>reduce</code> by reducing the visible array into a dictionary and then using a similar map and sort.</p>
<pre><code>let counted = visible.reduce([Int: Int]()) { (result, path) -> [Int: Int] in
var updated = result
updated[path.section, default: 0] += 1
return updated
}
let section = counted.keys.map { ($0, counted[$0]!) }.sorted { $0.1 > $1.1 }.first?.0
</code></pre>
<p>This works as well but I'm hoping there are ways to improve this.</p>
<p>Two main questions:</p>
<ol>
<li><p>Can the <code>reduce</code> closure be improved? Is there a better way to return the updated dictionary where the keys are section and the values are the count?</p></li>
<li><p>Once I have the dictionary of sections and counts, is there a better way to find the section with the highest count? Is there something better than mapping to a tuple, sorting those tuples, and finally grabbing the first one?</p></li>
</ol>
<p>BTW - If there is a tie for highest count, I don't care which of those sections is returned.</p>
| [] | [
{
"body": "<p><strong>Re 1:</strong> You can take advantage of <a href=\"https://developer.apple.com/documentation/swift/array/3126956-reduce\" rel=\"nofollow noreferrer\"><code>reduce(into:_:)</code></a> which was introduced in Swift 4 precisely for this purpose:</p>\n<blockquote>\n<p>This method is preferred over <a href=\"https://developer.apple.com/documentation/swift/array/2298686-reduce\" rel=\"nofollow noreferrer\"><code>reduce(_:_:)</code></a> for efficiency when the result is a copy-on-write type, for example an Array or a Dictionary.</p>\n</blockquote>\n<p>See also <a href=\"https://github.com/apple/swift-evolution/blob/master/proposals/0171-reduce-with-inout.md\" rel=\"nofollow noreferrer\">SE-0171 Reduce with inout</a>:</p>\n<blockquote>\n<p><strong>Motivation</strong></p>\n<p>The current version of reduce needs to make copies of the result type for each element in the sequence. The proposed version can eliminate the need to make copies (when the inout is optimized away).</p>\n</blockquote>\n<p>In your case:</p>\n<pre><code> let counted = visible.reduce(into: [Int: Int]()) { (result, path) in\n result[path.section, default: 0] += 1\n}\n</code></pre>\n<p>The compiler can also infer the type of the initial accumulator automatically if the closure consists only of a single statement:</p>\n<pre><code>let counted = visible.reduce(into: [:]) { (result, path) in\n result[path.section, default: 0] += 1\n}\n</code></pre>\n<p><strong>Re 2:</strong> A dictionary <em>is</em> a collection of key/value pairs, therefore it can be sorted directly, without mapping each key to a tuple first:</p>\n<pre><code>let section = counted.sorted(by: { $0.value > $1.value }).first?.key\n</code></pre>\n<p>Even better, use <a href=\"https://developer.apple.com/documentation/swift/sequence/2906531-max\" rel=\"nofollow noreferrer\"><code>max(by:)</code></a> to find the dictionary entry with the maximal value:</p>\n<pre><code>let section = counted.max(by: { $0.value < $1.value })?.key\n</code></pre>\n<p>This is shorter and eliminates the intermediate arrays and the dictionary lookup. It is more efficient than sorting an array because only a single traversal of the collection is done. And even if the forced unwrapping is safe in your case, it is nice not to have it.</p>\n<hr />\n<p>One could also make this a generic method for sequences</p>\n<pre><code>extension Sequence {\n func mostFrequent<T: Hashable>(by map: (Element) -> T) -> T? {\n let counted = reduce(into: [:]) { (result, elem) in\n result[map(elem), default: 0] += 1\n }\n return counted.max(by: { $0.value < $1.value })?.key\n }\n}\n</code></pre>\n<p>which is then used as</p>\n<pre><code>let section = collectionView.indexPathsForVisibleItems.mostFrequent(by: { $0.section })\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T21:37:53.050",
"Id": "425668",
"Score": "0",
"body": "Excellent. That `reduce(into:)` was just what I needed to make that part cleaner. And I had been thinking about how to use `max` but I forgot about being able to use it like this with a dictionary. Great info. The extension is a great touch too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T19:40:52.283",
"Id": "220310",
"ParentId": "220308",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220310",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T19:25:30.183",
"Id": "220308",
"Score": "2",
"Tags": [
"functional-programming",
"swift"
],
"Title": "Finding the most common section from the visible cells in a collection view"
} | 220308 |
<p>I implemented an algorithm to find the modular multiplicative inverse of an integer. The code works, but it is too slow and I don't know why. I compared it with an <a href="https://rosettacode.org/wiki/Modular_inverse#Ruby" rel="nofollow noreferrer">algorithm I found in Rosetta Code</a>, which is longer but way faster.</p>
<p>My implementation:</p>
<pre class="lang-rb prettyprint-override"><code>def modinv1(a, c)
raise "#{a} and #{c} are not coprime" unless a.gcd(c) == 1
0.upto(c - 1).map { |b| (a * b) % c }.index(1)
end
</code></pre>
<p>Rosetta Code's implementation:</p>
<blockquote>
<pre class="lang-rb prettyprint-override"><code>def modinv2(a, m) # compute a^-1 mod m if possible
raise "NO INVERSE - #{a} and #{m} not coprime" unless a.gcd(m) == 1
return m if m == 1
m0, inv, x0 = m, 1, 0
while a > 1
inv -= (a / m) * x0
a, m = m, a % m
inv, x0 = x0, inv
end
inv += m0 if inv < 0
inv
end
</code></pre>
</blockquote>
<p>Benchmark results (used <code>benchmark-ips</code>):</p>
<pre><code>Warming up --------------------------------------
Rosetta Code 141.248k i/100ms
Mine 462.000 i/100ms
Calculating -------------------------------------
Rosetta Code 2.179M (± 6.5%) i/s - 10.876M in 5.022459s
Mine 4.667k (± 3.7%) i/s - 23.562k in 5.055259s
Comparison:
Rosetta Code: 2179237.4 i/s
Mine: 4667.4 i/s - 466.90x slower
</code></pre>
<p>Why is mine so slow? Should I use the one I found in Rosetta Code?</p>
| [] | [
{
"body": "<p>As the comment says on the less-obfuscated version on Rosetta Code, their implementation is based on the <a href=\"http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Iterative_method_2\" rel=\"nofollow noreferrer\">Extended Euclidean Algorithm</a>. Your implementation works by brute force to test every element in the field, so of course it's going to be slow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T21:34:15.770",
"Id": "220317",
"ParentId": "220312",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220317",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:05:44.183",
"Id": "220312",
"Score": "0",
"Tags": [
"performance",
"algorithm",
"ruby",
"mathematics"
],
"Title": "Modular multiplicative inverse in Ruby"
} | 220312 |
<p>This is extension of the <a href="https://rosettacode.org/wiki/Rep-string" rel="nofollow noreferrer">rep-string task from Rosette code</a>. I do not only want to check if the input string is the shortest periodic string (rep-string) or not, but also check if it is preperiodic. </p>
<p>Periodic means, that a part must occur two or more times.</p>
<p><strong>Input</strong> is a binary string (only 1 and 0 chars). It can be for example <a href="http://www.knowledgedoor.com/2/calculators/convert_a_ratio_of_integers.html" rel="nofollow noreferrer">binary expansion of the fraction</a></p>
<p><strong>Output</strong> is a formatted binary string: preperiod(period)</p>
<p><a href="https://en.wikibooks.org/wiki/Fractals/Mathematics/Numbers#Examples_of_binary_expansions" rel="nofollow noreferrer">Examples:</a></p>
<pre><code>10101010 = (10) // periodic
10010101010 = 100(10) // preperiodic
11111111110 // aperiodic
</code></pre>
<p>Below is my C code. I use simple / naive <a href="https://en.wikipedia.org/wiki/String-searching_algorithm" rel="nofollow noreferrer">string-search algorithm</a>, and the code works well.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <string.h>
// array of strings for testing
char *strs[] = {
// aperiodic
"11111111110", // aperiodic
"011111111110",
"11000100000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", // https://en.wikipedia.org/wiki/Liouville_number
"110001000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010", // https://en.wikipedia.org/wiki/Liouville_number + 0
"101", // aperiodic because only one and a half repetition, possibly periodic if longer string
// periodic
"0100100", // (010) preperiod = 0 period = 3, truncated
"00100100100100100100100100100100100100100100100100100100100100100100100100100", // (001) preperiod = 0 period = 3 truncated
"1001110011", // = (10011) preperiod = 0 period = 5
"1110111011", // = (1110) preperiod = 0 period = 4
"0010010010", /* 4 x 001 and truncated, last char can be from 001*/
"001001001", /* 4 x 001 */
"1111111111", // (1)
"11", // (1) periodic
"00", // (0) periodic
// preperiodic
"0100101101",
"00100100101", /* 4 x 001 but last 2 chars are NOT from 001 */
"100100100101", /* */
"01111111111", // 0(1) preperiodic
"001010101010101", // preperiodic = 0(01) = 1/6
"0100101010101010" // preperiodic = 010(01) = 7/24
};
//
// strstr : Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.
// size_t is an unsigned integer typ
// looks for the shortest substring !!!!!
// GivePeriod = repstr_shortest
// https://rosettacode.org/wiki/Rep-string#C
int GivePeriod(char *str)
{
if (!str) return 0; // if empty input
size_t sl = 1;
size_t sl_max = strlen(str)/2+1 ; // more then one repetition of periodic parts
while (sl < sl_max) {
if (strstr(str, str + sl) == str) // How it works ???? It checks the whole string str
return sl;
++sl;
}
return 0;
}
int FormatString(char *str){
int p; // offset or preperiod ( if period is found)
int pMax = strlen(str) ; // length without null character
int period = 0;
int preperiod = 0;
char *substr;
for (p=0; p < pMax; ++p ){
substr = str+p;
period = GivePeriod( substr);
if (period > 0 ) {
preperiod = p;
//printf("substring =\t%*s\t from position =%d has preperiod = %d\tperiod = %d\n", pMax, substr, p, preperiod, period ); // pring part of the string from p position to the end ( without last null character)
printf("%s = %.*s(%.*s) preperiod = %d\tperiod = %d\n", str, p, str, period, str+p, preperiod, period );
return period;
}
// else printf("substring =\t%*s\t from position = %d\t\n", pMax, substr, p); // pring part of the string from p position to the end ( without last null character)
}
printf("%s is aperiodic\n", str);
return 0;
}
int main(){
int iMax = sizeof(strs) / sizeof(strs[0]); // number of test values
int i; // test number = index of the array
for (i = 0; i < iMax; ++i) // check all test values
FormatString(strs[i]);
return 0;
}
</code></pre>
<p>To compile : </p>
<pre><code>gcc p.c -Wall
</code></pre>
<p>to run: </p>
<pre><code>./a.out
</code></pre>
<p>My output is: </p>
<pre><code>11111111110 is aperiodic
011111111110 is aperiodic
11000100000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 is aperiodic
110001000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010 is aperiodic
101 is aperiodic
0100100 = (010) preperiod = 0 period = 3
00100100100100100100100100100100100100100100100100100100100100100100100100100 = (001) preperiod = 0 period = 3
1001110011 = (10011) preperiod = 0 period = 5
1110111011 = (1110) preperiod = 0 period = 4
0010010010 = (001) preperiod = 0 period = 3
001001001 = (001) preperiod = 0 period = 3
1111111111 = (1) preperiod = 0 period = 1
11 = (1) preperiod = 0 period = 1
00 = (0) preperiod = 0 period = 1
0100101101 = 0100(101) preperiod = 4 period = 3
00100100101 = 0010010(01) preperiod = 7 period = 2
100100100101 = 10010010(01) preperiod = 8 period = 2
01111111111 = 0(1) preperiod = 1 period = 1
001010101010101 = 0(01) preperiod = 1 period = 2
0100101010101010 = 010(01) preperiod = 3 period = 2
</code></pre>
<p><strong>Questions:</strong></p>
<ol>
<li>Can I do it better ? </li>
<li>Can you give examples of strings for which my program fail ?</li>
<li>Does this code follow common best practices?</li>
</ol>
<p><strong>Edit 1</strong></p>
<p>notation:</p>
<ul>
<li>period = length of periodic ( repeating) part</li>
<li>preperiod = length of part before periodic part</li>
<li>periodic string : preperiod = 0, period > 0</li>
<li>preperiodic string : preperiod > 0 and period > 0</li>
<li>aperiodic string : perperiod = 0 and period = 0</li>
</ul>
<p>Note the input string is finite ( = finite part of infinite string) so maybe in a longer input string period or preperiod will be > 0</p>
| [] | [
{
"body": "<p>Looking at your code for style</p>\n\n<pre><code>#include <stdio.h>\n#include <string.h>\n\n\n// array of strings for testing\n</code></pre>\n\n<p>These strings should be <code>char const *</code> unless you really want them to be altered</p>\n\n<pre><code>char *strs[] = {\n</code></pre>\n\n<p>You have the 'aperiodic comment twice here, which confuses me somewhat. If this is a section of aperiodic strings, why do you need the 2nd comment at all?</p>\n\n<p>Also I suspect the 1st comment should be a block comment (especially in view of some of the other stuff)</p>\n\n<pre><code> // aperiodic\n \"11111111110\", // aperiodic\n \"011111111110\",\n</code></pre>\n\n<p>With strings this long I'd put the descriptive comment by itself on the line before</p>\n\n<pre><code> \"11000100000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001\", // https://en.wikipedia.org/wiki/Liouville_number \n \"110001000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010\", // https://en.wikipedia.org/wiki/Liouville_number + 0\n \"101\", // aperiodic because only one and a half repetition, possibly periodic if longer string\n</code></pre>\n\n<p>Again, I think this comment should be a block comment</p>\n\n<pre><code> // periodic\n \"0100100\", // (010) preperiod = 0 period = 3, truncated \n \"00100100100100100100100100100100100100100100100100100100100100100100100100100\", // (001) preperiod = 0 period = 3 truncated\n \"1001110011\", // = (10011) preperiod = 0 period = 5\n \"1110111011\", // = (1110) preperiod = 0 period = 4\n \"0010010010\", /* 4 x 001 and truncated, last char can be from 001*/\n \"001001001\", /* 4 x 001 */\n \"1111111111\", // (1)\n \"11\", // (1) periodic\n \"00\", // (0) periodic \n</code></pre>\n\n<p>probably a block comment again. Does preperiodic mean periodic after a prefix, as the word doesn't appear in the referenced web page (in fact, neither do periodic or aperiodic, but I know what both of those mean, but I've never come across preperiodic)</p>\n\n<pre><code> // preperiodic\n \"0100101101\", \n \"00100100101\", /* 4 x 001 but last 2 chars are NOT from 001 */\n</code></pre>\n\n<p>Blank comments are generally unhelpful</p>\n\n<pre><code> \"100100100101\", /* */\n</code></pre>\n\n<p>You've already said preperiodic so why repeat?</p>\n\n<pre><code> \"01111111111\", // 0(1) preperiodic\n \"001010101010101\", // preperiodic = 0(01) = 1/6\n \"0100101010101010\" // preperiodic = 010(01) = 7/24\n};\n\n\n\n// \n</code></pre>\n\n<p>The c standard defines what strstr does, so this doesn't convey any helpful information</p>\n\n<pre><code>// strstr : Returns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1. \n</code></pre>\n\n<p>Ditto for size_t</p>\n\n<pre><code>// size_t is an unsigned integer typ\n</code></pre>\n\n<p>If it looks for the shortest substring, why not call it that, rather than GivePeriod? Or is the comment wrong?</p>\n\n<pre><code>// looks for the shortest substring !!!!!\n// GivePeriod = repstr_shortest\n// https://rosettacode.org/wiki/Rep-string#C\n</code></pre>\n\n<ul>\n<li>I think this is getting the repeat period, not giving it</li>\n<li>you should pass <code>char const *</code> here. You don't alter the string in this and you presumably don't intend do.</li>\n</ul>\n\n<pre><code>int GivePeriod(char *str)\n{\n</code></pre>\n\n<p>This is not 'empty input'. This protects against passing a null pointer. It's not usually worth protecting against that.</p>\n\n<pre><code> if (!str) return 0; // if empty input\n\n size_t sl = 1; \n</code></pre>\n\n<p>I can't relate the comment to the calculation at all.</p>\n\n<pre><code> size_t sl_max = strlen(str)/2+1 ; // more then one repetition of periodic parts\n</code></pre>\n\n<p>You could make this a for loop</p>\n\n<pre><code> while (sl < sl_max) {\n</code></pre>\n\n<p>That doesn't explain how it works at all</p>\n\n<pre><code> if (strstr(str, str + sl) == str) // How it works ???? It checks the whole string str\n</code></pre>\n\n<p>Never omit the braces after if/while/do/for. Read up on '<a href=\"https://gotofail.com/\" rel=\"nofollow noreferrer\">goto fail</a>'. I honestly would be a rich person if I had a penny for every time someone added a line into an if statement during a maintenance and didn't add the braces</p>\n\n<pre><code> return sl; \n ++sl;\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Again, const correctness. You don't (and shouldn't) alter the string. You should pass pointers as pointer to const by default, and only change if you actually need to modify what is pointed to</p>\n\n<pre><code>int FormatString(char *str){\n</code></pre>\n\n<p>Given you have period and preperiod defined shortly after, this comment is confusing. Looking at the code, it isn't either anyway, it's the current offset in the string.</p>\n\n<pre><code> int p; // offset or preperiod ( if period is found)\n</code></pre>\n\n<p>That's what strlen does. Not a helpful comment</p>\n\n<pre><code> int pMax = strlen(str) ; // length without null character\n</code></pre>\n\n<p>You only use period, preperiod and substr inside the loop, so declare them inside the loop. It helps the reader understand the intended scope</p>\n\n<pre><code> int period = 0; \n int preperiod = 0; \n\n char *substr;\n\n for (p=0; p < pMax; ++p ){\n\n substr = str+p;\n period = GivePeriod( substr);\n\n if (period > 0 ) {\n preperiod = p;\n</code></pre>\n\n<ul>\n<li>Don't release commented out code to production</li>\n<li>you don't actually use preperiod apart from this output. There's not much point in having it as it has to be the same as p.</li>\n<li>in general I'd avoid having output to stdout/stderr inside a library function. It should be up to the client to determine what to do with the results of your function - including how and where to output them. Among other things, it is difficult to write a unit test that checks you output what you think you did.</li>\n</ul>\n\n<pre><code> //printf(\"substring =\\t%*s\\t from position =%d has preperiod = %d\\tperiod = %d\\n\", pMax, substr, p, preperiod, period ); // pring part of the string from p position to the end ( without last null character)\n printf(\"%s = %.*s(%.*s) preperiod = %d\\tperiod = %d\\n\", str, p, str, period, str+p, preperiod, period );\n return period;\n }\n // else printf(\"substring =\\t%*s\\t from position = %d\\t\\n\", pMax, substr, p); // pring part of the string from p position to the end ( without last null character)\n }\n printf(\"%s is aperiodic\\n\", str);\n return 0;\n}\n</code></pre>\n\n<pre><code>int main(){\n int iMax = sizeof(strs) / sizeof(strs[0]); // number of test values\n\n int i; // test number = index of the array \n</code></pre>\n\n<p>Again do not omit the braces</p>\n\n<pre><code> for (i = 0; i < iMax; ++i) // check all test values\n FormatString(strs[i]);\n\n\n\n return 0;\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T20:08:09.347",
"Id": "425998",
"Score": "0",
"body": "\"gcc p.c -Wall -Wextra -Wmisleading-indentation\" gives no warnings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T07:17:24.467",
"Id": "426130",
"Score": "0",
"body": "thats not a particularly good reason for not putting in the braces. Especially as you have to add the extra switch to get the warning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T08:25:51.937",
"Id": "426140",
"Score": "0",
"body": "I was looking for a way to automatically find such error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T08:35:33.393",
"Id": "426141",
"Score": "0",
"body": "sadly, i've yet to come across one, although there are formatting programs that can be persuaded to put them back (astyle for one)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T09:37:03.807",
"Id": "426144",
"Score": "0",
"body": "The code was formatted with emacs"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:53:57.553",
"Id": "220351",
"ParentId": "220313",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:11:34.277",
"Id": "220313",
"Score": "4",
"Tags": [
"algorithm",
"c",
"strings",
"search",
"floating-point"
],
"Title": "Preperiodic, periodic or aperiodic binary string"
} | 220313 |
<p><strong>The task</strong>
is taken from <a href="https://leetcode.com/problems/container-with-most-water/" rel="noreferrer">leetcode</a></p>
<blockquote>
<p>Given n non-negative integers a<sub>1</sub>, a<sub>2</sub>, ..., a<sub>n</sub> , where each represents
a point at coordinate (i, a<sub>i</sub>). n vertical lines are drawn such that
the two endpoints of line i is at (i, a<sub>i</sub>) and (i, 0). Find two lines,
which together with x-axis forms a container, such that the container
contains the most water.</p>
<p>Note: You may not slant the container and n is at least 2.</p>
</blockquote>
<p><strong>My first solution:</strong></p>
<pre><code>/**
* @param {number[]} height
* @return {number}
*/
var maxArea = height => {
let max = 0;
height.forEach((hL, i) => {
height.slice(i + 1).forEach((hR, j) => {
max = Math.max(max, Math.min(hL, hR) * (1 + j));
});
});
return max;
};
</code></pre>
<p><strong>My second solution:</strong></p>
<pre><code>/**
* @param {number[]} height
* @return {number}
*/
var maxArea2 = height => {
let l = max = 0;
let r = height.length - 1;
while (l < r) {
const area = Math.min(height[l], height[r]) * (r - l);
if (height[l] > height[r]) {
r--;
} else {
l++;
}
max = Math.max(max, area);
}
return max;
};
</code></pre>
<p>Is it possible to solve it mathematically and make it faster?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:28:06.077",
"Id": "425694",
"Score": "0",
"body": "Strictly speaking your code doesn't solve the task. It only finds the maximum area, but it does not say which of the lines form the container. The task says \"find the lines\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T15:13:03.977",
"Id": "425761",
"Score": "0",
"body": "I solved it consistently with the example they gave (See link in OP) @RolandIllig"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T19:23:33.487",
"Id": "425808",
"Score": "0",
"body": "And I thought the tasks from leetcode had been peer reviewed and checked for accuracy. Apparently they aren't. :)"
}
] | [
{
"body": "<blockquote>\n <p>Is it possible to solve it mathematically and make it faster?</p>\n</blockquote>\n\n<p>Not faster than the second solution,\nwhich is <span class=\"math-container\">\\$O(n)\\$</span>, making a single pass over the input.\nIt's easy to see that it's not possible to find the correct answer without inspecting every element. For example, if two values are not inspected, then one could pick arbitrarily high values for them to make them produce the maximum area.</p>\n\n<p>I have some style comments about the second solution:</p>\n\n<ul>\n<li>I dislike the variable name <code>l</code> because in some fonts it can be confused with <code>|</code> or <code>1</code>.</li>\n<li>I would rename <code>l</code> to <code>left</code> and <code>r</code> to <code>right</code> for natural clarity. Still simple enough.</li>\n<li>For symmetry with the <code>while (l < r)</code>, I would rewrite the <code>if</code> in the loop body to be <code>if (height[l] < height[r])</code>, as I feel it would facilitate understanding of the logic.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T18:02:32.793",
"Id": "220747",
"ParentId": "220314",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220747",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:24:15.143",
"Id": "220314",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"comparative-review",
"ecmascript-6"
],
"Title": "Container with most water"
} | 220314 |
<p><a href="https://leetcode.com/problems/flatten-binary-tree-to-linked-list/" rel="nofollow noreferrer">https://leetcode.com/problems/flatten-binary-tree-to-linked-list/</a></p>
<p>Please comment on performance</p>
<blockquote>
<p>Given a binary tree, flatten it to a linked list in-place.</p>
<p>For example, given the following tree:</p>
<pre><code> 1
/ \
2 5
/ \ \
3 4 6
</code></pre>
<p>The flattened tree should look like:</p>
<pre><code>1
\
2
\
3
\
4
\
5
\
6
</code></pre>
</blockquote>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LinkedListQuestions
{
[TestClass]
public class FlattenBinaryTree2LinkedList
{
[TestMethod]
public void FlattenBinaryTree2LinkedListTest()
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(5);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(4);
root.right.right = new TreeNode(6);
Flatten(root);
Assert.AreEqual(1, root.data);
Assert.AreEqual(2, root.right.data);
Assert.AreEqual(3, root.right.right.data);
Assert.AreEqual(4, root.right.right.right.data);
Assert.AreEqual(5, root.right.right.right.right.data);
Assert.AreEqual(6, root.right.right.right.right.right.data);
}
public void Flatten(TreeNode root)
{
if (root == null || (root.left == null && root.right == null))
{
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
var head = root;
stack.Push(root);
while (stack.Count > 0)
{
var curr = stack.Pop();
if (curr != root) // in the first iteration, we don't want to move the head to the next item
{
head.right = curr;
head = curr;
}
if (curr.right != null)
{
stack.Push(curr.right);
curr.right = null;
}
if (curr.left != null)
{
stack.Push(curr.left);
curr.left = null;
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T21:58:20.507",
"Id": "425669",
"Score": "2",
"body": "I think the moment you do a new Stack(), you violate the restriction to doing it \"in-place\". You have to move the nodes around in the same tree, without using a helper"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T22:18:36.727",
"Id": "425672",
"Score": "0",
"body": "@fernando yes I think you are right. I will try another solution."
}
] | [
{
"body": "<p>Your solution use a single loop to iterate through all elements\nso the complexity is O(N), where N is the number of elements.</p>\n\n<p>The performance can be improved a little by removing the first if statement and inserting left before right in the stack </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T22:17:14.897",
"Id": "425671",
"Score": "0",
"body": "If I put left before right. The result will be wrong"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T23:04:28.183",
"Id": "425674",
"Score": "0",
"body": "Yes, Right before Left is the right order. As left will be processed before Right"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T22:04:15.160",
"Id": "220320",
"ParentId": "220316",
"Score": "1"
}
},
{
"body": "<p>The first condition is a bit conservative:</p>\n\n<blockquote>\n<pre><code>if (root == null || (root.left == null && root.right == null))\n</code></pre>\n</blockquote>\n\n<p>Just <code>if (root == null)</code> would be enough, the rest of the implementation naturally handles the cases of <code>root.left == null && root.right == null</code>.</p>\n\n<hr>\n\n<p>Evaluating <code>curr != root</code> for every node, when it's only useful for the first node is a bit ugly.\nYou could get rid of that by not adding <code>root</code> itself on the stack, but its children. (In the right order, and when not null.)</p>\n\n<hr>\n\n<p><code>head</code> is a misleading name for a variable that traverses all the nodes,\nespecially since the end result is effectively a linked list,\nwhere \"head\" usually means the first element.\nI'd rename this to <code>node</code>.</p>\n\n<hr>\n\n<p>All the <code>curr.right = null;</code> can be safely dropped,\nbecause <code>curr.right</code> will either get overwritten with the intended value,\nor it's <code>null</code> to begin with (in the very last node).</p>\n\n<hr>\n\n<p>An <span class=\"math-container\">\\$O(n)\\$</span> solution exists without using a stack:</p>\n\n<ul>\n<li>When left is null and right is not, advance over right</li>\n<li>When right is null and left is not, move left to right and advance over right</li>\n<li>When both not null of <code>node</code>, then:\n\n<ul>\n<li>traverse through all the right descendants of <code>node.left</code>, and append at the end <code>node.right</code></li>\n<li>move <code>node.left</code> to <code>node.right</code> and advance over it</li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:30:31.937",
"Id": "220375",
"ParentId": "220316",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220375",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T20:56:47.730",
"Id": "220316",
"Score": "2",
"Tags": [
"c#",
"programming-challenge",
"linked-list",
"tree",
"depth-first-search"
],
"Title": "Leetcode: Flatten binary tree to linked list C#"
} | 220316 |
<p>I have a <code>durations</code> as such:</p>
<pre><code>[{'duration': 3600}, {'duration': 3600}]
</code></pre>
<p>And I want the output to be <code>{3600: 2}</code>, where 2 is the number of occurrences of 3600.</p>
<p>My first attempt is use a loop, as such:</p>
<pre><code> var count = {};
for (var d of durations) {
var length = d.duration;
if (length in count) {
count[length] += 1;
}
else {
count[length] = 1;
}
}
console.log(count);
</code></pre>
<p>The second attempt uses <a href="https://lodash.com/docs#reduce" rel="nofollow noreferrer">reduce()</a> in lodash:</p>
<pre><code> function foo(result, value) {
var length = value.duration;
if (length in result) {
result[length] += 1;
}
else {
result[length] = 1;
}
return result;
}
var reduced = _.reduce(durations, foo, {});
console.log(reduced);
</code></pre>
<p>As can be seen, this second attempt is still as verbose as before.</p>
<p>Is there a way to write the iteratee function <code>foo</code> more conform to functional programming?</p>
| [] | [
{
"body": "<p>It's not really clear what you mean by \"functional\".</p>\n\n<p>The use of <code>reduce</code> is nifty, and correctly done, but it seem like <a href=\"https://en.wikipedia.org/wiki/Cargo_cult\" rel=\"nofollow noreferrer\">cargo cult</a> programming. The realization that a lot of loop-like actions can be represented in terms of <code>reduce</code> (fold, aggregate, etc) is <em>important</em> to functional programing, but it should no more be your first choice than a while-loop.</p>\n\n<p>The fact that it's verbose isn't necessarily a problem. It <em>suggests</em> that you might be failing at a general goal:</p>\n\n<blockquote>\n <p>Write what you mean.</p>\n</blockquote>\n\n<p>One of the things that makes functional programming good is that it helps us do that.<br>\nJavascript has limited tools for directly declaring lists. What you <em>mean</em> to do is declare a Dictionary from the Set of <code>duration</code> values to the Count of the source array Filtered by the respective duration. Or even better you could use a grouping function.</p>\n\n<p>You could bring in a library for the task, which may be a good idea, or you could compromise a little.</p>\n\n<pre><code>function getCounts(items, key){\n let c = {};\n for(let item of items){\n c[key(item)] = items.filter(function(i){\n return key(i) === key(item);\n }).length;\n }\n return c;\n};\ncounts = getCounts(durations, function(i){ return i['duration']; })'\n</code></pre>\n\n<p>You'll notice that that's quite inefficient. We could make it less wasteful, but it'd be less terse. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T02:29:05.970",
"Id": "425680",
"Score": "2",
"body": "The introduction of your answer is good, but the code is not since its complexity is \\$\\mathcal O(n^2)\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:33:59.277",
"Id": "425745",
"Score": "0",
"body": "Yeah, don't actually use that code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T01:57:11.853",
"Id": "220323",
"ParentId": "220322",
"Score": "3"
}
},
{
"body": "<p>To reduce the verboseness of the code, you should extract the main idea of that code into a function:</p>\n\n<pre><code>function histogram(data, key) {\n const count = {};\n for (let item of data) {\n const value = data[key];\n count[value] = (count[value] || 0) + 1;\n }\n return count;\n}\n</code></pre>\n\n<p>That way you can write your code as:</p>\n\n<pre><code>console.log(histogram(durations, 'duration'));\n</code></pre>\n\n<p>I first tried a simple <code>count[value]++</code>, but that didn't work since <code>undefined + 1</code> is still <code>undefined</code>. Therefore I had to use the <code>|| 0</code> trick.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T02:55:30.283",
"Id": "220326",
"ParentId": "220322",
"Score": "2"
}
},
{
"body": "<h2>First point</h2>\n\n<p>Don't add quotes around property names when defining JS objects.</p>\n\n<pre><code>[{'duration': 3600}, {'duration': 3600}]\n\n// should be\n\n[{duration: 3600}, {duration: 3600}]\n</code></pre>\n\n<h2>You state</h2>\n\n<blockquote>\n <p><em>\"And I want the output to be {3600: 2}, where 2 is the number of occurrences of 3600.\"</em></p>\n</blockquote>\n\n<p>Which is not that clear. Going by your code I assume you want <code>[{duration: 60}, {duration: 60}, , {duration: 10}]</code> converted to <code>{60:2, 10:1}</code></p>\n\n<p>I will also assume that all array items contain an object with the property named <code>duration</code></p>\n\n<p>Using these assumptions for the rest of the answer. </p>\n\n<h2>Rewrite</h2>\n\n<p>Taking your first snippet and turning it into a function.</p>\n\n<ul>\n<li>You don't need the <code>if (length in count) {</code>, you can just use <code>if (count[d.duration]) {</code></li>\n<li>The object <code>count</code> and <code>d</code> should be constants as you don't change them.</li>\n<li>Using a t<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">ernary</a> you can reduce the 6 lines of the if else to one line.</li>\n</ul>\n\n<p>Code</p>\n\n<pre><code>function countDurations(durations) {\n const counts = {};\n for (const {duration: len} of durations) {\n counts[len] = counts[len] ? counts[len] + 1 : 1;\n }\n return counts;\n}\n</code></pre>\n\n<p>Or a little less verbose as a arrow function</p>\n\n<pre><code>const countDur = dur => dur.reduce((c, {duration: l}) => (c[l] = c[l]? c[l] + 1: 1, c), {});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>const countDurs = durs => \n durs.reduce((counts, {duration: len}) => \n (counts[len] = counts[len] ? counts[len] + 1 : 1, counts)\n , {}\n);\n</code></pre>\n\n<h2>Rewrite 2</h2>\n\n<p>The second snippet is algorithmicly the same, just uses a different iteration method. </p>\n\n<ul>\n<li>JavaScript has <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\">Array.reduce</a> so you don't need to use a external library.</li>\n<li>Separating the iterator inner block into a function <code>count</code></li>\n</ul>\n\n<p>Code</p>\n\n<pre><code>const count= (cnt, {duration: len}) => (cnt[len] = cnt[len] ? cnt[len] + 1 : 1, cnt);\nconst countDurations = durations => durations.reduce(count, {});\n</code></pre>\n\n<p>Or encapsulating the <code>count</code> function via closure</p>\n\n<pre><code>const countDurations = (()=> {\n const count = (cnt, {duration: len}) => (cnt[len] = cnt[len] ? cnt[len] + 1 : 1, cnt);\n return durations => durations.reduce(count, {});\n})();\n</code></pre>\n\n<h2>Functional?</h2>\n\n<blockquote>\n <p><em>\"Is there a way to write the iterate function foo more conform to functional programming?\"</em></p>\n</blockquote>\n\n<p>JavaScript is not designed to be a functional language (it is impossible to create pure functions) so It is best to use functional as a guide rather than a must.</p>\n\n<h2>Almost pure</h2>\n\n<p>The second rewrite is more along the functional approach, but functional purist would complain that the reducer function has side effects by modifying the counter. You can create a copy of the counts each call as follows..</p>\n\n<pre><code>const counter = (c, {duration: len}) => (c = {...c}, (c[len] = c[len] ? c[len] + 1 : 1), c);\nconst countDurations = durations => durations.reduce(counter, {});\n</code></pre>\n\n<p>However this add significant memory and processing overhead with zero benefit (apart from a functional pat on the back).</p>\n\n<h2>Note</h2>\n\n<ul>\n<li>This answer uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Assigning_to_new_variable_names\" rel=\"nofollow noreferrer\">destructuring property name alias</a> so check for browser compatibility.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T09:20:28.057",
"Id": "220332",
"ParentId": "220322",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220332",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-15T23:57:55.990",
"Id": "220322",
"Score": "3",
"Tags": [
"javascript",
"functional-programming",
"comparative-review",
"lodash.js"
],
"Title": "Counting duration values"
} | 220322 |
<p>One of my favorite classic programming exercises is the Subset Sum problem. I'm (trying) to learn Ada and it's the first thing I wanted to implement, even before a Hello World. </p>
<p>The Subset Sum problem aims to find within a set of numbers, if a specified sum can be found by combining any number of elements from the set. For example, <code>{2, 8, 4}</code> has subset sums of <code>2</code>, <code>8</code>, <code>4</code>, <code>10</code> (2+8), <code>6</code> (2+4), <code>12</code> (8+4), and <code>14</code> (2+8+4). The goal of this algorithm is to feed it a set and a sum and determine if the sum is a subset sum or not.</p>
<p>Here's my code:</p>
<pre><code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Command_line; use Ada.Command_Line;
procedure Subset_Sum is
-- a set of numbers to find subset sum on
type Set is array(0..4) of Integer;
Arr : Set;
-- find if subset sum exists in a set
-- @param Arr - the set to check
-- @param S - the sum to check against Arr
-- @param N - for iteration; equals Arr.length
-- @returns - truth value on whether subset sum exists
function Find_Subset (Arr : in Set; S, N : in Integer) return Boolean is
begin
-- a sum of zero is always possible
if S = 0 then
return True;
-- base case, if surpassed all elements of Set
elsif N = 0 then
return False;
end if;
-- if last is bigger than sum, ignore and go deeper
if (Arr(N-1)) > S then
return Find_Subset(Arr, S, N-1);
end if;
-- check including the last
-- and excluding the last
return Find_Subset(Arr, S, N-1)
or else Find_Subset(Arr, S-Arr(N-1), N-1);
end Find_Subset;
-- verifies arguments are correct before continuing
-- @returns - truth value on whether args valid
function Verify_Args return Boolean is
begin
-- only six arguments allowed
-- one for sum, five for set
if Argument_Count /= 6 then
-- instruct user how to use args
Put("Invalid arguments."); New_Line;
Put("Use arguments '<arg1> <args2>'."); New_Line;
Put("<arg1> is the sum to find, <args2> is space delimited list of 5 numbers.");
return False;
end if;
return True;
end Verify_Args;
begin
-- if valid arguments
if Verify_Args then
Put("{");
-- populate Arr with arguments
for i in 0..4 loop
Arr(i) := Integer'value(Argument(i+2));
Put(Integer'Image(Arr(i)));
if i /= 4 then
Put(", ");
end if;
end loop;
Put("} ");
-- determine if a subset sum exists
if Find_Subset(Arr, Integer'Value(Argument(1)), Arr'Length) = False then
Put("does not contain subset sum " & Argument(1));
else
Put("contains subset sum " & Argument(1));
end if;
end if;
end Subset_Sum;
</code></pre>
<p>You can run the code like so:</p>
<pre><code># save as subset_sum.adb
$ gnatmake subset_sum.adb -o sss
$ ./sss <arg1> <args2>
# <arg1> is the sum to find
# <args2> is space delimited list of numbers of size 5
# eg. ./sss 12 2 8 4 1 5
</code></pre>
<p>An example execution and output:</p>
<pre><code>$ ./sss 11 2 8 4 9 1
$ {2, 8, 4, 9, 1} contains subset sum 11
</code></pre>
<p>This is the <em>naive</em> approach. In my experience, Subset Sum Problem is studied as part of a unit on dynamic programming. My next step is to implement that but in the interim I wanted to get the handle of Ada.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:17:04.290",
"Id": "425689",
"Score": "0",
"body": "Could you try to replace the `or` with `or else`? If that still compiles, it will make your code a bit faster. The `or` operator always evaluates both of its operands. The same would apply to `and` being replaced with `and then`, if your code contained it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:18:53.677",
"Id": "425691",
"Score": "0",
"body": "I'm still new to Ada but I figured it would still short circuit if the first operand evaluates to `false`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:21:16.287",
"Id": "425692",
"Score": "0",
"body": "A workaround for the formatting bug is to add a comment to the end of that line, like `Arr'Length) = False then -- ' fix highlighting on Stack Overflow`. I've done that regularly when I wrote Perl code, which also confuses most editors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T06:22:18.633",
"Id": "425693",
"Score": "0",
"body": "I don't get what you mean by \"still\", but yes, that would short-circuit the boolean evaluation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T09:06:46.027",
"Id": "425710",
"Score": "0",
"body": "@RolandIllig, the test the short-circuit form affects here is just A vs B, both of which have already been evaluated, so the saving is minimal (unless the optimiser is able to recognise the situation: but A and B are in an outer scope, so quite possibly not). To achieve the effect required, you’d need to call `SubsetSum` in the condition"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T09:32:09.330",
"Id": "425712",
"Score": "1",
"body": "Your algorithm needs the input to be sorted-ish (try with `(5, 5, 3, 2, 1)`); and even then, doesn’t it only check consecutive subsequences?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:57:51.210",
"Id": "425778",
"Score": "0",
"body": "@SimonWright thanks for the tip. I've altered the code and from my unit testing, I can't find an example where it doesn't work as intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:13:32.703",
"Id": "425882",
"Score": "0",
"body": "I don’t know why my experiments with one of your earlier versions led me to believe that `(5, 5, 3, 2, 1)` wouldn’t work. Sorry for the noise."
}
] | [
{
"body": "<p>Much of this review is about style. Style's important, especially in\njoint projects. It's best if style matches what the community has come\nto expect.</p>\n\n<p>That said, it'd be natural to start off with an unconstrained array\ntype for <code>Set</code>:</p>\n\n<pre><code>type Set is array (Natural range <>) of Integer;\n</code></pre>\n\n<p>Naming is important. The function doesn't <em>find</em> a subset (clue: it\nreturns a <code>Boolean</code>).</p>\n\n<pre><code>function Check_For_Subset\n</code></pre>\n\n<p>Parameter names are important too. They should be written from the\npoint of view of the caller, not from that of the implementer. It's\ngood if they make sense when using named parameter assignment;\n<code>Check_For_Subset (Of_Set => Arr, Summing_To => 0)</code>. Note also, we\ndon't need the <code>N</code> parameter, because the parameter <code>Of_Set</code> carries\nwith it the array bounds, length etc in the form of attributes. Using\nthe attributes adds to the code volume, but improves flexibility, and\nis pretty-much mandatory when using unconstrained parameters.</p>\n\n<pre><code> (Of_Set : Set; Summing_To : Integer) return Boolean is\nbegin\n</code></pre>\n\n<p>I think I have the intent of the algorithm correct in the code\ncomments.</p>\n\n<pre><code> -- Check whether the recursion should terminate.\n if Summing_To = 0 then\n -- If the required sum is zero, it would be possible to meet\n -- it by using an empty set, even if the current set isn't\n -- empty.\n return True;\n</code></pre>\n\n<p>Here we use the attribute <code>'Length</code>.</p>\n\n<pre><code> elsif Of_Set'Length = 0 then\n -- Summing_to is non-zero, but there are no further\n -- elements to contribute to it.\n return False;\n end if;\n</code></pre>\n\n<p>Here we use the attribute <code>'Last</code>, the last index of the actual\nparameter.</p>\n\n<pre><code> if (Of_Set (Of_Set'Last)) > Summing_To then\n</code></pre>\n\n<p><code>Of_Set (Of_Set'First .. Of_Set'Last - 1)</code> is a \"slice\" of the array,\nextending from the first to the last-but-one element. Note, it's\npossible for the last index of the slice to be less than the first,\nwhich corresponds to an empty slice.</p>\n\n<p>I think there's a problem here if <code>Summing_To</code> is negative! Perhaps it\nshould be a <code>Natural</code>?</p>\n\n<pre><code> -- If the last element is already bigger than the requirred\n -- sum, it cannot contribute; so ignore it and check the\n -- remainder.\n return Check_For_Subset (Of_Set (Of_Set'First .. Of_Set'Last - 1),\n Summing_To);\n end if;\n</code></pre>\n\n<p>And then</p>\n\n<pre><code> return\n -- We may be able to find a subset by excluding the last\n -- element ..\n Check_For_Subset (Of_Set (Of_Set'First .. Of_Set'Last - 1),\n Summing_To)\n or else\n -- .. or by taking the last element away from the required\n -- sum, and checking the remainder of the input set (this\n -- effectively *includes* the last element).\n Check_For_Subset (Of_Set (Of_Set'First .. Of_Set'Last - 1),\n Summing_To - Of_Set(Of_Set'Last));\nend Check_For_Subset;\n</code></pre>\n\n<p>Finally. this declares a <code>Set</code> object with the desired range, to be\nused by the main program. I do question whether it might be better to\narrange for indexing by <code>Positive</code>, which would have eliminated the \n<code>N - 1</code>'s in the original code.</p>\n\n<pre><code>Arr : Set (0 .. 4);\n</code></pre>\n\n<hr>\n\n<p>I wrote some notes on style in the mid-1990’s, updated (a bit) <a href=\"https://forward-in-code.blogspot.com/2019/05/coding-guidelines.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T01:08:40.333",
"Id": "425928",
"Score": "1",
"body": "Great answer. I tried (albeit not very hard) to find a conventions guide for comments, naming, etc and couldn't find much. Interestingly, NASA provides an Ada guide, which is not surprising due to Ada's widespread use in critical systems like in the DOD, aeronautics, etc.\n\nThe language I am most familiar with and use the most often is C++, and it seems conventions are project specific. To something like Ada, it's a lot more freedom but I dig there's one specific ruleset to follow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T07:25:09.130",
"Id": "425945",
"Score": "0",
"body": "Thanks! Try the [Ada Quality and Style Guide](https://en.wikibooks.org/wiki/Ada_Style_Guide) - I’ll try to add this to the answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:26:06.120",
"Id": "220414",
"ParentId": "220327",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220414",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T04:35:19.413",
"Id": "220327",
"Score": "4",
"Tags": [
"beginner",
"ada",
"subset-sum-problem"
],
"Title": "Subset Sum in Ada"
} | 220327 |
<p>I'm adding rather extensive xml-doc comments to all Rubberduck inspection classes, like this:</p>
<pre><code>namespace Rubberduck.Inspections.Concrete
{
/// <summary>
/// Warns about a variable that is assigned, and then re-assigned before the first assignment is read.
/// </summary>
/// <why>
/// The first assignment is likely redundant, since it is being overwritten by the second.
/// </why>
/// <examples>
/// <example>
/// <text>This inspection means to flag the following examples:</text>
/// <code>
/// <![CDATA[
/// Public Sub DoSomething()
/// Dim foo As Long
/// foo = 12 ' assignment is redundant
/// foo = 34
/// End Sub]]>
/// </code>
/// </example>
/// <example>
/// <text>The following code should not trip this inspection:</text>
/// <code>
/// <![CDATA[
/// Public Sub DoSomething(ByVal foo As Long)
/// Dim bar As Long
/// bar = 12
/// bar = bar + foo ' variable is re-assigned, but the prior assigned value is read at least once first.
/// End Sub]]>
/// </code>
/// </example>
/// </examples>
public sealed class AssignmentNotUsedInspection : InspectionBase
{
...
</code></pre>
<p>The idea being to get our CI server to build the XML docs for that assembly, and then essentially use the GitHub repository as a CDN to retrieve and parse from the project's website - and that works great: on my local build I generate the <code>/inspections/list</code> page contents off the XML documentation, exactly as intended.</p>
<p>But the <code>/list</code> page doesn't include the <code><examples></code>; I want the <code>/inspections/details/{inspection-name}</code> pages to include them, and I want them not only formatted as code, but also syntax-highlighted - similar to how the site's <a href="http://rubberduckvba.com/Error/PageNotFound" rel="noreferrer">404 error page</a> formats some dummy VBA code, but better: that dummy code's CSS formatting is all hard-coded, and there's no way I'm going to clutter the xml-doc examples with <code><span class="keyword"></code> tags.</p>
<p>Since Rubberduck's VBA parser does a pretty awesome job at parsing VBA code, I figured it shouldn't be too hard to write a class that takes this:</p>
<pre class="lang-none prettyprint-override"><code>Public Sub DoSomething()
Dim foo As Long
foo = 12 ' assignment is redundant
foo = 34
End Sub
</code></pre>
<p>...and outputs this:</p>
<pre class="lang-html prettyprint-override"><code><span class="keyword">Public</span> <span class="keyword">Sub</span> DoSomething()
<span class="keyword">Dim</span> foo <span class="keyword">As</span> <span class="keyword">Long</span>
foo = 12 <span class="comment">' assignment is redundant
</span> foo = 34
<span class="keyword">End Sub</span>
</code></pre>
<p>Here's the class in question:</p>
<pre><code>public class FormattedCodeBlockBuilder
{
private static readonly string KeywordClass = "keyword";
private static readonly string CommentClass = "comment";
private static readonly string StringLiteralClass = "string-literal";
public string Format(string code)
{
var builder = new StringBuilder(code.Length);
var tokens = Tokenize(code);
var parser = new VBAParser(tokens);
var commentsListener = new CommentIntervalsListener();
parser.AddParseListener(commentsListener);
parser.startRule();
for (var i = 0; i < tokens.Size; i++)
{
var token = tokens.Get(i);
if (commentsListener.IsComment(token, out var commentInterval))
{
builder.Append($"<span class=\"{CommentClass}\">{tokens.GetText(commentInterval)}</span>");
i = commentInterval.b;
}
else if (StringLiteralTokens.Contains(token.Type))
{
builder.Append($"<span class=\"{StringLiteralClass}\">{token.Text}</span>");
}
else if (KeywordTokens.Contains(token.Type))
{
builder.Append($"<span class=\"{KeywordClass}\">{token.Text}</span>");
}
else
{
builder.Append(token.Text);
}
}
return builder.ToString();
}
private ITokenStream Tokenize(string code)
{
AntlrInputStream input;
using (var reader = new StringReader(code))
{
input = new AntlrInputStream(reader);
}
var lexer = new VBALexer(input);
return new CommonTokenStream(lexer);
}
#region token classes
private static readonly HashSet<int> StringLiteralTokens = new HashSet<int>
{
VBAParser.STRINGLITERAL,
VBAParser.DATELITERAL,
};
private static readonly HashSet<int> KeywordTokens = new HashSet<int> {
VBAParser.ANY,
VBAParser.CURRENCY,
VBAParser.DEBUG,
VBAParser.DOEVENTS,
VBAParser.EXIT,
VBAParser.FIX,
VBAParser.INPUTB,
VBAParser.LBOUND,
VBAParser.LONGLONG,
VBAParser.LONGPTR,
VBAParser.OPTION,
VBAParser.PSET,
VBAParser.SCALE,
VBAParser.SGN,
VBAParser.UBOUND,
VBAParser.ACCESS,
VBAParser.ADDRESSOF,
VBAParser.ALIAS,
VBAParser.AND,
VBAParser.ATTRIBUTE,
VBAParser.APPEND,
VBAParser.AS,
VBAParser.BEGINPROPERTY,
VBAParser.BEGIN,
VBAParser.BINARY,
VBAParser.BOOLEAN,
VBAParser.BYVAL,
VBAParser.BYREF,
VBAParser.BYTE,
VBAParser.CALL,
VBAParser.CASE,
VBAParser.CDECL,
VBAParser.CLASS,
VBAParser.CLOSE,
VBAParser.CONST,
VBAParser.CONST,
VBAParser.DATABASE,
VBAParser.DATE,
VBAParser.DECLARE,
VBAParser.DEFBOOL,
VBAParser.DEFBYTE,
VBAParser.DEFDATE,
VBAParser.DEFDBL,
VBAParser.DEFCUR,
VBAParser.DEFINT,
VBAParser.DEFLNG,
VBAParser.DEFLNGLNG,
VBAParser.DEFLNGPTR,
VBAParser.DEFOBJ,
VBAParser.DEFSNG,
VBAParser.DEFSTR,
VBAParser.DEFVAR,
VBAParser.DIM,
VBAParser.DO,
VBAParser.DOUBLE,
VBAParser.EACH,
VBAParser.ELSE,
VBAParser.ELSEIF,
VBAParser.EMPTY,
VBAParser.END_ENUM,
VBAParser.END_FUNCTION,
VBAParser.END_IF,
VBAParser.ENDPROPERTY,
VBAParser.END_SELECT,
VBAParser.END_SUB,
VBAParser.END_TYPE,
VBAParser.END_WITH,
VBAParser.END,
VBAParser.ENUM,
VBAParser.EQV,
VBAParser.ERASE,
VBAParser.ERROR,
VBAParser.EVENT,
VBAParser.EXIT_DO,
VBAParser.EXIT_FOR,
VBAParser.EXIT_FUNCTION,
VBAParser.EXIT_PROPERTY,
VBAParser.EXIT_SUB,
VBAParser.FALSE,
VBAParser.FRIEND,
VBAParser.FOR,
VBAParser.FUNCTION,
VBAParser.GET,
VBAParser.GLOBAL,
VBAParser.GOSUB,
VBAParser.GOTO,
VBAParser.IF,
VBAParser.IMP,
VBAParser.IMPLEMENTS,
VBAParser.IN,
VBAParser.INPUT,
VBAParser.IS,
VBAParser.INTEGER,
VBAParser.LOCK,
VBAParser.LONG,
VBAParser.LOOP,
VBAParser.LET,
VBAParser.LIB,
VBAParser.LIKE,
VBAParser.LINE_INPUT,
VBAParser.LOCK_READ,
VBAParser.LOCK_WRITE,
VBAParser.LOCK_READ_WRITE,
VBAParser.LSET,
VBAParser.MOD,
VBAParser.NAME,
VBAParser.NEXT,
VBAParser.NEW,
VBAParser.NOT,
VBAParser.NOTHING,
VBAParser.NULL,
VBAParser.OBJECT,
VBAParser.ON_ERROR,
VBAParser.ON_LOCAL_ERROR,
VBAParser.OPEN,
VBAParser.OPTIONAL,
VBAParser.OPTION_BASE,
VBAParser.OPTION_EXPLICIT,
VBAParser.OPTION_COMPARE,
VBAParser.OPTION_PRIVATE_MODULE,
VBAParser.OR,
VBAParser.OUTPUT,
VBAParser.PARAMARRAY,
VBAParser.PRESERVE,
VBAParser.PRINT,
VBAParser.PRIVATE,
VBAParser.PROPERTY_GET,
VBAParser.PROPERTY_LET,
VBAParser.PROPERTY_SET,
VBAParser.PTRSAFE,
VBAParser.PUBLIC,
VBAParser.PUT,
VBAParser.RANDOM,
VBAParser.RANDOMIZE,
VBAParser.RAISEEVENT,
VBAParser.READ,
VBAParser.READ_WRITE,
VBAParser.REDIM,
VBAParser.REM,
VBAParser.RESET,
VBAParser.RESUME,
VBAParser.RETURN,
VBAParser.RSET,
VBAParser.SEEK,
VBAParser.SELECT,
VBAParser.SET,
VBAParser.SHARED,
VBAParser.SINGLE,
VBAParser.STATIC,
VBAParser.STEP,
VBAParser.STOP,
VBAParser.STRING,
VBAParser.SUB,
VBAParser.TAB,
VBAParser.TEXT,
VBAParser.THEN,
VBAParser.TO,
VBAParser.TRUE,
VBAParser.TYPE,
VBAParser.TYPEOF,
VBAParser.UNLOCK,
VBAParser.UNTIL,
VBAParser.VARIANT,
VBAParser.VERSION,
VBAParser.WEND,
VBAParser.WITH,
VBAParser.WITHEVENTS,
VBAParser.WRITE,
VBAParser.XOR
};
#endregion
private class CommentIntervalsListener : VBAParserBaseListener
{
private readonly IList<Interval> _intervals = new List<Interval>();
public bool IsComment(IToken token, out Interval commentInterval)
{
if (!_intervals.Any())
{
commentInterval = Interval.Invalid;
return false;
}
var tokenInterval = new Interval(token.TokenIndex, token.TokenIndex);
commentInterval = _intervals.SingleOrDefault(e => e.ProperlyContains(tokenInterval));
return !commentInterval.Equals(default(Interval));
}
public override void ExitCommentOrAnnotation(VBAParser.CommentOrAnnotationContext context)
{
_intervals.Add(context.SourceInterval);
}
}
}
</code></pre>
<p>Does anything strike anyone as weird or wrong in that string formatter class? I don't do web stuff very often, so this might very well be a very naive approach to building the formatted HTML. If it's any relevant, the website is ASP.NET MVC (not Core, since it's referencing the <code>Rubberduck.SmartIndender</code> and <code>Rubberduck.Parsing</code> assemblies).</p>
| [] | [
{
"body": "<p>You are basically building a compiler. You have your tokenizer and parser available, but your target language generator is missing. Sure, hardcoding in html can be done for a small use case, but I would prefer to use an existing API. </p>\n\n<p>Suggested API: <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.htmltextwriter?redirectedfrom=MSDN&view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>HtmlTextWriter</code></a> from System.Web.</p>\n\n<p>Alternative API: <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.htmlelement?view=netframework-4.8\" rel=\"nofollow noreferrer\"><code>HtmlElement</code></a> from System.Windows.Forms. </p>\n\n<p>Both API's allow building html elements in code and back- and forward mapping between managed code and html text.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T12:21:51.637",
"Id": "425957",
"Score": "1",
"body": "The `System.Windows.Forms` namespace would be the last place I would ever look for a `HtmlElement` :-o How did they come up with the idea to _hide_ it there? Oh boy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T13:21:27.687",
"Id": "425962",
"Score": "0",
"body": "@t3chb0t good point - but I like the idea of building the HTML with that kind of object rather than concatenating/building a string. Surely `System.Web` has a similar DOM classes somewhere, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T13:23:38.497",
"Id": "425963",
"Score": "0",
"body": "@Mathieu Guindon: check out https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.htmltextwriter?redirectedfrom=MSDN&view=netframework-4.8, I will update my post"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T07:58:28.660",
"Id": "220453",
"ParentId": "220328",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220453",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T05:21:42.603",
"Id": "220328",
"Score": "5",
"Tags": [
"c#",
"html",
"formatting",
"rubberduck",
"antlr"
],
"Title": "Custom lexer/parser-based code prettifier"
} | 220328 |
<p>The code below is working properly but how do I make this code faster and more efficient. How do I perfect this code?</p>
<p>Let's assume I have 1000 country, state and city records in a mongodb collection. I want to retrieve all the city data by matching country id and state id. Please tell me the perfect way to code.</p>
<pre><code>// @route GET citylist/:countryid/:stateid
// @desc get all the city from mongodb for countryid and stateid
router.get("/citylist/:countryid/:stateid", (req, res) => {
const isValidCountryid = mongoose.Types.ObjectId.isValid( req.params.countryid);
const isValidStateid = mongoose.Types.ObjectId.isValid(req.params.stateid);
if (isValidCountryid && isValidStateid) {
CityModel.find({
country_id: req.params.countryid,
state_id: req.params.stateid
})
.then(cities => {
if (!cities || !cities[0]) {
return res.status(404).json({ msg: "City not found" });
} else {
res.json(cities);
}
})
.catch(error => res.status(500).send(error));
} else {
res.json({ msg: "Country or State Id is not valid" });
}
});
</code></pre>
<p>how to make this code highly fast, efficient, great time complexity and perfect way of code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T08:18:05.670",
"Id": "425706",
"Score": "1",
"body": "Please have a look at *Titling your question* in the [Help center](https://codereview.stackexchange.com/help/how-to-ask) and change your title accordingly! Namely, describe what your task is, not what you expect from the review."
}
] | [
{
"body": "<p>From a short review,</p>\n\n<ul>\n<li>Make sure that your database has an index: <a href=\"https://docs.mongodb.com/manual/indexes/\" rel=\"nofollow noreferrer\">https://docs.mongodb.com/manual/indexes/</a></li>\n<li>For the 404, since most countries have more than 1 city, I would return \"Cities not found\", I might even include the provided country and city in the return message so that the admin can be provided with an informative message</li>\n<li>I would have 2 different messages when the input data is bad, one for City, and one for country. Furthermore, for bad input data, I would use return code 400.</li>\n<li>It's very minor, but <code>CountryId</code> looks better than <code>countryid</code></li>\n<li>Instead of <code>if (isValidCountryid && isValidStateid) {</code> I would check for bad data, and exit immediately, it makes for a lower cyclomatic complexity</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T12:45:41.797",
"Id": "220343",
"ParentId": "220331",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Utilize the query object, this type of querying is more suitable there than as params.</li>\n<li>Use object destructuring.</li>\n<li>Dry your code, see how we're mapping over <code>[countryId, stateId]</code> to check the validity of the input. Ideally, you would have been using a module like <code>Joi</code> for that.</li>\n<li>Maintain a <a href=\"https://en.wikipedia.org/wiki/Happy_path\" rel=\"nofollow noreferrer\">happy path</a> and break out of the function early when erroring.</li>\n<li>Use <code>async/await</code> instead of <code>.then()</code>.</li>\n<li>Return a <code>400</code> when the input is invalid.</li>\n<li>User proper camelCase (in both the DB and the backend).</li>\n<li>Check the array length instead of checking the existence of the first element. So <code>if (arr.length)</code> not <code>if (arr[0])</code>. The reason for that is at some cases the first element of the array could be 'falsy' (such as <code>''</code> and <code>0</code>) which can be valid sometimes.</li>\n<li>When erroring, return an <code>error</code> field, not a <code>msg</code> one.</li>\n<li>Study javascript's array methods such as <code>map</code>, <code>reduce</code>, <code>filter</code>, and <code>every</code>. They will save your life more often than you thought.</li>\n</ul>\n\n<pre><code>router.get(\"/citylist\", async (req, res) => {\n try {\n\n const { countryid, stateId } = req.query\n\n const validInput = [countryid, stateid].map(mongoose.Types.ObjectId.isValid).every(Boolean)\n if (!validInput) return res.status(400).json({ error: \"Country or State Id is not valid\" })\n\n const cities = await CityModel.find({ countryId, stateId })\n if (!cities || cities.length) return res.status(404).json({ error: \"City not found\" })\n\n res.json(cities);\n\n } catch (error) {\n res.status(500).json({ error })\n }\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-31T21:40:24.993",
"Id": "227235",
"ParentId": "220331",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T07:09:13.673",
"Id": "220331",
"Score": "2",
"Tags": [
"javascript",
"performance",
"node.js",
"mongodb",
"express.js"
],
"Title": "Retrieve a city list for a country and state"
} | 220331 |
<p>Problem:</p>
<blockquote>
<p>Source (with example): <a href="https://leetcode.com/problems/island-perimeter/" rel="nofollow noreferrer">https://leetcode.com/problems/island-perimeter/</a></p>
<p>You are given a map in form of a two-dimensional integer grid where 1
represents land and 0 represents water.</p>
<p>Grid cells are connected horizontally/vertically (not diagonally). The
grid is completely surrounded by water, and there is exactly one
island (i.e., one or more connected land cells).</p>
<p>The island doesn't have "lakes" (water inside that isn't connected to
the water around the island). One cell is a square with side length 1.
The grid is rectangular, width and height don't exceed 100. Determine
the perimeter of the island.</p>
</blockquote>
<p>Below is my solution. I haven't coded in Java since college and I'm trying to pick it up again. How is my style and is there any new Java features I can apply to the method to make it more concise? Thank you in advance!</p>
<p>Code:</p>
<pre><code>class Solution {
private int m;
private int n;
public int islandPerimeter(int[][] grid) {
m = grid.length;
n = grid[0].length;
int perimeter = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
perimeter += getPerimeter(i, j, grid);
}
}
}
return perimeter;
}
private int getPerimeter(int i, int j, int[][] grid) {
int perimeter = 0;
if (i == 0 || grid[i-1][j] == 0) {
perimeter++;
}
if (j == 0 || grid[i][j-1] == 0) {
perimeter++;
}
if (i == m-1 || grid[i+1][j] == 0) {
perimeter++;
}
if (j == n-1 || grid[i][j+1] == 0) {
perimeter++;
}
return perimeter;
}
}
</code></pre>
| [] | [
{
"body": "<p>Storing properties of <code>grid</code>, which is a method parameter, into instance fields m and n, is bad practise. Now the reader has to wonder why their scope is exposed outside the method. M and n should stay in the same scope (they should be method variables).</p>\n\n<p><code>M</code> and <code>n</code> are bad names for <code>width</code> and <code>height</code>. There's nothing wrong with width and height and these would communicate their intended purpose immediately.</p>\n\n<p>While <code>i</code> and <code>j</code> are common loop index variables, <code>x</code> and <code>y</code> are more commonly used for indexing a two dimensional grid. Some people use <code>row</code> and <code>col</code>, which are fine too.</p>\n\n<p>While scanning every element is clean and works well for small input, you could just find the first element that has a \"coastline\" and check it's neighbors, ignoring all elements that don't have a \"coastline\". Follow the coastline clockwise and stop once you reach the first element again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T11:15:31.423",
"Id": "220338",
"ParentId": "220335",
"Score": "1"
}
},
{
"body": "<p>Instead of looking for cool new features of Java i would strongly suggest that you concentrate on the basics of Java: Objects:</p>\n\n<h2>Think in Objects:</h2>\n\n<p>So far you have identified these Objects: <code>Map</code>, a <code>Cell</code> and an <code>Island</code> - so make some Objects of that type.</p>\n\n<pre><code>Map map = new Map(int[][] src);\nIsland island = map.extractIsland();\nint diameter = island.getPerimater();\n</code></pre>\n\n<p>the <code>Map</code> needs some methods to properly extract the island</p>\n\n<pre><code>Cell cell = getCellAt(int x, int y);\n</code></pre>\n\n<p>and a method to gain relationship between each <code>Cells</code> on the map:</p>\n\n<pre><code>List<Cell> getNeighbours(Cell center);\n</code></pre>\n\n<p>and some elementary methods on the <code>Cell</code> class</p>\n\n<pre><code>boolean isWater();\nboolean isLand();\nint getAmountCoasts();\n</code></pre>\n\n<p>if you would have these elementary Objects you can simply create readable Code - see this example:</p>\n\n<pre><code>Cell center; //yes, here center.isLand() = true\nList<Cell> neigbour = map.getNeighbours(center);\nfor (Cell neigbour: neigbours){\n if (neigbour.isWater()){\n center.addCoast();\n }\n}\n</code></pre>\n\n<h2>once you are here you can use features from java 8</h2>\n\n<pre><code>List<Cell> landCells = cells.stream.filter(Cell::isLand).collect(CollectorsToList());\nint perimeter = landCells.stream.mapToInt(Cell::.getAmountCoasts).sum();\n</code></pre>\n\n<p>Hint: you better let the <code>Island</code> class handle that, see first hints - Responsibility for coastLine is within the <code>Island</code> class!)</p>\n\n<h2>NOTE:</h2>\n\n<p>it's hard to think in objects whenever you try minimal code snippets as suggested from leet code. if minimal code is required, look maybe you are interested at <a href=\"https://codegolf.stackexchange.com/\">CodeGolf</a>...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T12:51:33.650",
"Id": "220344",
"ParentId": "220335",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T10:48:59.497",
"Id": "220335",
"Score": "3",
"Tags": [
"java",
"algorithm"
],
"Title": "Island perimeter code challenge in Java"
} | 220335 |
<p>My scenario is the following: I'm modelling a Program which has many Modules. Each Module has Symbols, some of which pointing at dependencies, which are other Modules. So a Module can be pointed to by many other Modules as a dependency.</p>
<p>Now I want to be able to modify a Module (typically, running an optimiser on its contents, removing unused dependencies, etc), and then any other Module which has it as a dependency should point to the "new" version.</p>
<p>I've tried two approaches:</p>
<ul>
<li>Having a <code>ModuleId</code> for each <code>Module</code>, and have <code>Module</code>s point to their dependencies by their <code>ModuleId</code>. Then I can update the <code>Module</code> associated to a <code>ModuleId</code> and all links are still valid. One drawback is that there's no compile-time guarantee that I won't try to update a non-existing <code>Module</code>.</li>
<li>Using <code>Rc<RefCell<Content>></code> to store the content to be updated, in which case I can update <code>Content</code> without any of the dependency links breaking. I find it suspicious that I have to use such advanced tools for this, and they're not risk free as <code>RefCell</code> is checked at run time.</li>
</ul>
<p>I'm wondering if I missed another approach, and which one would be the most idiomatic.</p>
<p><a href="https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=0242a911d7ff374632d5b84faf27b04f" rel="nofollow noreferrer">Here</a> is a link to a simplified playground with both approaches, and my code below:</p>
<pre class="lang-rust prettyprint-override"><code>mod with_module_id {
use std::collections::hash_map::{Entry, HashMap};
type Content = usize;
#[derive(Debug)]
struct Module {
content: Content,
dependency: Option<ModuleId>,
}
type ModuleId = String;
#[derive(Debug)]
struct Prog {
modules: HashMap<ModuleId, Module>,
}
fn update_module(p: Prog, id: ModuleId, c: Content) -> Prog {
let mut p = p;
match p.modules.entry(id.clone()) {
Entry::Occupied(mut m) => m.get_mut().content = c,
_ => panic!("module id not found: {}", id),
};
p
}
pub fn run() {
let m0 = Module {
content: 42,
dependency: None,
};
let m1 = Module {
content: 43,
dependency: Some(String::from("m0")),
};
let m2 = Module {
content: 44,
dependency: Some(String::from("m0")),
};
let p = Prog {
modules: vec![
(String::from("m0"), m0),
(String::from("m1"), m1),
(String::from("m2"), m2),
]
.into_iter()
.collect(),
};
println!("We start with this program:\n{:#?}\n", p);
let p = update_module(p, String::from("m0"), 151);
println!("We update module m0 to contain 151:\n{:#?}\n", p);
println!("We try to update an unexisting module and boom...");
let _p = update_module(p, String::from("invalid :("), 404);
}
}
mod with_ref_cell {
use std::rc::Rc;
use std::cell::RefCell;
type Content = usize;
#[derive(Debug)]
struct Module {
content: Rc<RefCell<Content>>,
dependency: Option<Rc<Module>>,
}
fn update_module(m: Rc<RefCell<Content>>, c: Content) {
*m.borrow_mut() = c;
}
pub fn run() {
let content0 = Rc::new(RefCell::new(42));
let m0 = Module {
content: Rc::clone(&content0),
dependency: None,
};
let content1 = Rc::new(RefCell::new(43));
let m0 = Rc::new(m0);
let m1 = Module {
content: Rc::clone(&content1),
dependency: Some(Rc::clone(&m0)),
};
let content2 = Rc::new(RefCell::new(44));
let m2 = Module {
content: Rc::clone(&content2),
dependency: Some(Rc::clone(&m0)),
};
println!("We start with this program:\n{:#?}\n\n{:#?}\n", m1, m2);
update_module(content0, 151);
println!("We update module m0 to contain 151:\n{:#?}\n\n{:#?}\n", m1, m2);
}
}
fn main() {
with_ref_cell::run();
with_module_id::run();
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T11:10:29.663",
"Id": "220336",
"Score": "2",
"Tags": [
"graph",
"rust",
"reference"
],
"Title": "Modelling a program with modules, symbols, and dependencies"
} | 220336 |
<p>Recently I made a script to get available IP automatically. I was woundering if anyone can give me tips on how to make this code look better, preferably in a class and OOP. I'm gonna show the code to my boss, but i want it to look clean and nice before i do so, and hopefully learn a thing or two about writing better code.</p>
<p>Code:</p>
<pre><code>import requests
from orionsdk import SwisClient
import getpass
# Brukerinfromasjon
npm_server = 'mw-solarwinds.yy.dd'
username = 'jnk'
password = getpass.getpass()
server_navn = input('Skriv inn DNS navn: ')
dns_ip = '10.96.17.4' # 10.96.17.5 = Felles
dns_sone = 'yy.dd'
verify = False
if not verify:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
swis = SwisClient(npm_server, username, password) # Kjører mot IPAM med brukerinformasjon
subnets = {
'ka-windows': ['10.112.12.0', '24'],
'ka-linux': ['10.112.10.0', '24'],
'ka-exa-mgmt': ['10.112.26.0', '28']
}
print("Tilgjengelige subnets: ")
for i in subnets:
print(i)
print("--------------")
found = False
while not found:
inp = input("Skriv in Subnet: ")
if inp in subnets:
'''
Finner ledig IP adresse i subnet
'''
sub_ip = subnets[inp][0]
sub_cdir = subnets[inp][1]
ipaddr = swis.invoke('IPAM.SubnetManagement', 'GetFirstAvailableIp', sub_ip, sub_cdir)
'''
Sette DNS > IP
'''
dns = swis.invoke('IPAM.IPAddressManagement', 'AddDnsARecord', server_navn, ipaddr, dns_ip, dns_sone)
print("IP: {} > DNS: {}".format(ipaddr, server_navn))
found = True
else:
print("Det er ikke et subnet, velg en fra listen.")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:56:40.510",
"Id": "425737",
"Score": "1",
"body": "Your title is too generic. Your title should describe what you r code does, not what you want out of the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:30:30.360",
"Id": "425743",
"Score": "1",
"body": "It might also help to translate console output from your native language to English before posting it here for review."
}
] | [
{
"body": "<p>Not sure if it's any better as a class...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\n\nimport getpass\nimport requests\n\nfrom orionsdk import SwisClient\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\n\n\nclass Subnet_Explorer(dict):\n def __init__(self, npm_server, auth, dns, verify, **kwargs):\n super(Subnet_Explorer, self).__init__(**kwargs)\n self.update(\n npm_server = npm_server,\n auth = auth,\n dns = dns,\n server_navn = input('Skriv inn DNS navn: '),\n swis = SwisClient(npm_server, auth['username'], auth['password'])\n )\n\n if verify == False:\n requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\n def directed_exploration(self, subnets):\n \"\"\"\n Yields tuple of IP and DNS addresses from select subnets\n \"\"\"\n unexplored_subnets = subnets.keys()\n while True:\n print(\"Unexplored Subnets: {unexplored_subnets}\".format(\n unexplored_subnets = unexplored_subnets))\n inp = input(\"Skriv in Subnet: \")\n\n if not unexplored_subnets or inp not in unexplored_subnets:\n print(\"Det er ikke et subnet, velg en fra listen.\")\n break\n\n unexplored_subnets.remove(inp)\n ipaddr = self['swis'].invoke('IPAM.SubnetManagement',\n 'GetFirstAvailableIp',\n subnets[inp][0],\n subnets[inp][1])\n dns = self['swis'].invoke('IPAM.IPAddressManagement',\n 'AddDnsARecord',\n self['server_navn'],\n ipaddr,\n self['dns']['ip'],\n self['dns']['sone'])\n\n yield ipaddr, self['server_navn']\n\n\nif __name__ == '__main__':\n \"\"\"\n Running as a script within this block, eg. someone ran;\n\n python script_name.py --args\n\n to get here, usually.\n \"\"\"\n\n auth = {\n 'username': 'jnk',\n 'password': getpass.getpass(),\n }\n\n dns = {\n 'ip': '10.96.17.4',\n 'sone': 'yy.dd',\n }\n\n subnet_explorer = Subnet_Explorer(\n npm_server = 'mw-solarwinds.yy.dd',\n auth = auth,\n dns = dns,\n verify = False)\n\n exploration = subnet_explorer.directed_exploration(\n subnets = {\n 'ka-windows': ['10.112.12.0', '24'],\n 'ka-linux': ['10.112.10.0', '24'],\n 'ka-exa-mgmt': ['10.112.26.0', '28']\n })\n\n print(\"--------------\")\n for ipaddr, server_navn in exploration:\n print(\"IP: {ipaddr} > DNS: {server_navn}\".format(\n ipaddr = ipaddr,\n server_navn = server_navn))\n print(\"--------------\")\n</code></pre>\n\n<p>... though perhaps ya see some things ya like. Regardless ya may want to consider is adding some <em><code>argparse</code></em> stuff after the <code>if __name__ == '__main__':</code> line. And probably best to use anything from above modifications with care as I may have made things a bit more messy by turning towards classes.</p>\n\n<p>Is there a reason for setting <code>dns = swis.invoke(...)</code> when it's not being used for anything?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T06:18:47.753",
"Id": "425942",
"Score": "1",
"body": "Thank you for this, im trying to learn writing more in classes. DNS variable that is set was used for debugging purposes, when printed it tells me operatilm was successfull."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T17:25:32.603",
"Id": "425983",
"Score": "0",
"body": "Most welcome @JohnnyNiklasson, ya may want to hunt down some of my other [Python](https://math.stackexchange.com/a/3171877/657433) answers then, scattered about but there's nifty tricks also within the comments of [some](https://codereview.stackexchange.com/a/217374/197446)... If you're not `yield`ing or `return`ing the `dns` variable then might be a good idea to have an `if self.get('debug', 0) >= 1:` line just previous; in other-words avoid the work when debugging isn't required... Oh and Git (or some version) tracking is a good idea, also allows for generating metrics for the boss later ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T18:01:49.033",
"Id": "426086",
"Score": "0",
"body": "Thanks for advices! :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T21:48:01.390",
"Id": "454970",
"Score": "0",
"body": "Welcome for sure @JohnnyNiklasson, and I'm glad that this collaboration has been acceptable! Feel free to send your boss my way if they wish for more code-review/scripting like this because, regardless of language used, I enjoy finding solutions to meaningful challenges."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T02:11:51.660",
"Id": "220393",
"ParentId": "220339",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220393",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T11:51:28.583",
"Id": "220339",
"Score": "2",
"Tags": [
"python",
"networking",
"client",
"ip-address"
],
"Title": "Script to get available IP automatically"
} | 220339 |
<p>Until now we have always initialized the <strong>repositories</strong>, that containing MySql functions, at the beginning of each <code>Form</code></p>
<p>Something like that</p>
<p>Form example code:</p>
<pre><code>public partial class FormTest: Form
{
private readonly ProductRepository prodRep = new ProductRepository();
private readonly UserRepository userRep = new UserRepository();
private readonly CarRepository carRep = new CarRepository();
private readonly RegistryRepository regRep = new RegistryRepository();
public FormTest()
{
InitializeComponent();
var product = prodRep.Get();
var listUsers = userRep.GetAll();
}
}
</code></pre>
<p>Repository example code:</p>
<pre><code>namespace Gestionale.DataRepository
{
public class ProductRepository
{
public Product GetId(string id)
{
using (var db = new DatabaseConnection())
{
const string query = "SELECT * FROM product WHERE id_product = @Id";
return db.con.QueryFirstOrDefault<Product >(query, new { Id = id });
}
}
public List<Product> GetAll()
{
using (DatabaseConnection db = new DatabaseConnection())
{
const string query = "SELECT * FROM product";
return db.con.Query<Product>(query).ToList();
}
}
}
}
</code></pre>
<p>We were thinking of creating a new file with all the <strong>repositories</strong> inside and initializing it at the startup of the program.</p>
<ol>
<li><p>Is it a suitable procedure?</p></li>
<li><p>Positive and negative aspects ?</p></li>
<li>Other methods?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:36:52.787",
"Id": "425729",
"Score": "0",
"body": "Depends. What's in these repositories' constructors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:39:04.537",
"Id": "425730",
"Score": "3",
"body": "FWIW you would get much more useful feedback if you included your actual real code rather than a simple illustrative example that narrows everything down to one specific issue/question. This is *Code Review*, not Stack Overflow ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:39:21.800",
"Id": "425731",
"Score": "0",
"body": "@MathieuGuindon It's only a collection of function. There isn't a costructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:43:12.193",
"Id": "425732",
"Score": "0",
"body": "There's a very interesting architecture discussion about coupling, dependencies, and UI design patterns that could happen if you were interested in feedback on any/all aspects of the code (*real* code), as mandated by the site's [help/on-topic]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:51:28.443",
"Id": "425734",
"Score": "0",
"body": "@MathieuGuindon \nI added an example of the repository code"
}
] | [
{
"body": "<p>Frankly, if your repositories don't have state (i.e. <code>private</code> member variables), their methods should be marked as <code>static</code>, and ergo, each repository class should be marked as <code>static</code> and you have no need to worry about instantiation anywhere. They're essentially utility functions to be called whenever you need them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:26:54.587",
"Id": "425741",
"Score": "0",
"body": "You're right, we never thought about it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:36:35.943",
"Id": "425747",
"Score": "0",
"body": "The OP's constructor is doing database work. That means the designer stops working if the connection string has a typo, the command times out, or anything else goes wrong with hitting the MySQL database in the constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:46:07.373",
"Id": "425756",
"Score": "0",
"body": "Agree - that's a repudiation of the form class design, while I was addressing the repository class design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:47:09.283",
"Id": "425757",
"Score": "0",
"body": "@MathieuGuindon if i move the call of function in the form load event, like your answer, can this method be considered valid ?\nIn the case that I showed you, yes the calls are in the constructor, but I have other forms where the functions are called inside the form load or only through the buttons."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:53:24.130",
"Id": "425759",
"Score": "0",
"body": "@LorenzoBelfanti it's valid if it works, I guess. Whether it's well-architected is a whole other question. If it's just a throw-away prototype, \"Smart UI\" is probably fine. The problem is when the prototype ends up being the production app, and then needs to grow features - it tends to grow hair and tentacles as well! If your app is any decent size or of any significant importance, seriously consider looking into UI design patterns suitable for WinForms applications."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:21:41.317",
"Id": "220348",
"ParentId": "220345",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>private readonly ProductRepository prodRep = new ProductRepository();\nprivate readonly UserRepository userRep = new UserRepository();\nprivate readonly CarRepository carRep = new CarRepository();\nprivate readonly RegistryRepository regRep = new RegistryRepository();\n</code></pre>\n</blockquote>\n\n<p>From a very pragmatic point of view, there's nothing inherently wrong with newing up your dependencies like this - especially since they're just default constructors <em>without any side-effects</em>.</p>\n\n<p>From an architectural point of view, there's now absolutely no way to bring up that form without having it work with the MySQL database: the form is <em>tightly coupled</em> with its dependencies, and in a maintainable, testable code base, you want exactly the opposite of that.</p>\n\n<p>The main problem is in the form's constructor:</p>\n\n<blockquote>\n<pre><code> var product = prodRep.Get();\n\n var listUsers = userRep.GetAll();\n</code></pre>\n</blockquote>\n\n<p>Turning a blind eye on the extraneous vertical whitespace and the uselessness of these local variables, what's happening here is that the form's constructor is <em>side-effecting</em>, and has a very significant chance of throwing exceptions - two things that directly and severely contradict best practices.</p>\n\n<p>When I do this:</p>\n\n<pre><code>using (var form = new FormTest())\n{\n\n}\n</code></pre>\n\n<p>I expect to get a <code>FormTest</code> instance to work with, <em>period</em>.</p>\n\n<p>What's happening is, I <em>may</em> get a <code>FormTest</code> instance to work with, and I'm hitting a MySQL database, synchronously at that. If anything goes wrong in any of these hidden repository dependencies, I'm not getting a <code>FormTest</code> instance. Instead I get an unhandled exception I had no reason to expect.</p>\n\n<p>So, <em>when</em> should the initial load happen then, if not in the form's constructor? Forms have a <code>Load</code> event (see <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/winforms/order-of-events-in-windows-forms\" rel=\"nofollow noreferrer\">order of events in Windows Forms</a>) that's exactly for this. Handle the form's <code>Load</code> event, and move the database work there.</p>\n\n<pre><code>public FormTest()\n{\n InitializeComponent();\n Load += FormTest_Load;\n}\n\nprivate void FormTest_Load(object sender, EventArgs e)\n{\n products = prodRep.Get();\n listUsers = userRep.GetAll();\n}\n</code></pre>\n\n<p>The constructor is invoked by the WinForms designer: having it do database work means everytime the designer is loaded, you're hitting the database. Don't do this.</p>\n\n<hr>\n\n<p>A constructor should do as little work as possible, and tells its caller what it needs, what its dependencies are.</p>\n\n<pre><code>private readonly ProductRepository _products;\nprivate readonly UserRepository _users;\nprivate readonly CarRepository _cars;\nprivate readonly RegistryRepository _registries;\n\npublic FormTest(ProductRepository products, UserRepository users, CarRepository cars, RegistryRepository registries)\n : this()\n{\n _products = products;\n _users = users;\n _cars = cars;\n _registries = registries;\n}\n</code></pre>\n\n<p>We're still <em>tightly coupled</em> with concrete types, but at least now the dependencies are explicit. What's missing is a <em>unit of work</em> abstraction:</p>\n\n<pre><code>private readonly IUnitOfWork _context;\n\npublic FormTest(IUnitOfWork context)\n : this()\n{\n _context = context;\n}\n</code></pre>\n\n<p>But that's still leaving the form responsible for running the entire show: it's a <em>Smart UI</em> that knows how everything works and does everything.</p>\n\n<p>The form doesn't need to know about repositories or a unit of work; the form needs products, users, cars, registries: it needs a <em>model</em> object that encapsulates the data it wants to <em>present</em>:</p>\n\n<pre><code>private readonly AppModel _model;\n\npublic FormTest(AppModel model)\n : this()\n{\n _model = model;\n}\n</code></pre>\n\n<p>The object responsible for creating the form, is also responsible for populating that <em>model</em>: let's call it the <em>presenter</em>. The presenter's own dependencies include the <em>unit of work</em>, and its job is to update the model as needed, and respond to whatever happens in the <em>view</em> - the form.</p>\n\n<p>So if there's a button on the form that can create a new product, its <code>Click</code> handler should be as simple as this:</p>\n\n<pre><code>public event EventHandler CreateItem;\nprivate void CreateProductButton_Click(object sender, EventArgs e)\n{\n CreateItem?.Invoke(sender, e);\n}\n</code></pre>\n\n<p>The role of a form isn't to run the entire show and know everything that needs to happen for new data to end up in the database: the role of a form is strictly to <em>present the model to the user</em>, and provide an interface for the user to interact with it.</p>\n\n<p>So the <em>presenter</em> would handle that <code>CreateItem</code> event, by hitting the database through the repositories (asynchronously?), and then updating the model accordingly - and the view should have data bindings against the model, so no code whatsoever should be needed for this in the view.</p>\n\n<p>Look into the <em>Model-View-Presenter</em> UI pattern if this sounds interesting.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T14:34:42.890",
"Id": "220349",
"ParentId": "220345",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:30:58.977",
"Id": "220345",
"Score": "-2",
"Tags": [
"c#",
"winforms",
"repository"
],
"Title": "Initialize global repository or in forms?"
} | 220345 |
<p>I'm writing an application that will end up with a set of standard CRUD operations for a bunch of object types, and I thought it would help simplify things if all the separate controllers had some common functionality. This will be using a view interface for everything rather than RESTful responses. I haven't been able to find a lot of examples of this type of thing and I'm concerned I'm just creating code smell. In addition to providing common functionality, this allows me to pass the view template and handle most of the differences between objects there.</p>
<p>Some questions: </p>
<ul>
<li>in the case of <code>E</code>, I'm unable to specify that it should be an implementer of <code>@Entity</code>, though that would be an accurate statement. Is there a better way? Should I just create an identifying interface for those classes?</li>
<li>is there a better way to address the ID type of the repository? The entities will all have either a Long or String primary key. While this works, I know it's wrong, but don't know how to correct it. <em>(note, I didn't include the overload method for <code>editObject</code> that would accept a Long)</em></li>
<li>I feel like the this may not be the right/best way to construct a new object based on the generic type. Is there a better way?</li>
<li>has this approach been tried and discarded as a poor one (which is why there aren't a lot of examples)?</li>
</ul>
<pre class="lang-java prettyprint-override"><code>@Slf4j
class AbstractController<E, R extends JpaRepository<E, ? super Object>> {
private final R repository;
private Class<E> eClass;
private String TEMPLATE_PREFIX;
String getList() {
return TEMPLATE_PREFIX + "/list";
}
protected AbstractController(R repository, String templatePrefix) {
this.repository = repository;
this.TEMPLATE_PREFIX = templatePrefix;
}
ModelAndView listObjects(@RequestParam(required = false) Integer page,
@RequestParam(required = false) Integer size) {
ModelAndView modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/list");
modelAndView.addObject("items", repository.findAll(getPageRequest(page, size)));
return modelAndView;
}
ModelAndView newObject() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
ModelAndView modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/edit");
modelAndView.addObject("item", eClass.getConstructor().newInstance());
return modelAndView;
}
ModelAndView editObject(String id) {
ModelAndView modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/edit");
modelAndView.addObject("item", repository.findById(id));
return modelAndView;
}
ModelAndView saveObject(E entity,
BindingResult result) {
ModelAndView modelAndView;
if (result.hasErrors()) {
LOGGER.debug("error result: {}", result.getAllErrors());
modelAndView = new ModelAndView(TEMPLATE_PREFIX + "/edit");
} else {
repository.save(entity);
modelAndView = new ModelAndView("redirect:/" + TEMPLATE_PREFIX + "/list");
}
return modelAndView;
}
String deleteObject(final String id,
final RedirectAttributes redirectAttributes) {
repository.deleteById(id);
redirectAttributes.addAttribute("css", "success");
redirectAttributes.addFlashAttribute("msg", "The entry has been deleted.");
return "redirect:/" + TEMPLATE_PREFIX + "/list";
}
/**
* Provides defaults for a page request
*
* @param page which page
* @param size number of items
* @return page request parameters
*/
private PageRequest getPageRequest(Integer page, Integer size) {
return PageRequest.of(
(null == page) ? 0 : page,
(null == size) ? 10 : size);
}
}
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T13:31:43.907",
"Id": "220346",
"Score": "1",
"Tags": [
"java",
"generics",
"spring-mvc"
],
"Title": "Spring (boot) MVC Abstract Controller"
} | 220346 |
<p>The task
was taken from <a href="https://leetcode.com/problems/unique-email-addresses/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Every email consists of a local name and a domain name, separated by
the @ sign.</p>
<p>For example, in alice@leetcode.com, alice is the local name, and
leetcode.com is the domain name.</p>
<p>Besides lowercase letters, these emails may contain '.'s or '+'s.</p>
<p>If you add periods ('.') between some characters in the local name
part of an email address, mail sent there will be forwarded to the
same address without dots in the local name. For example,
"alice.z@leetcode.com" and "alicez@leetcode.com" forward to the same
email address. (Note that this rule does not apply for domain names.)</p>
<p>If you add a plus ('+') in the local name, everything after the first
plus sign will be ignored. This allows certain emails to be filtered,
for example m.y+name@email.com will be forwarded to my@email.com.
(Again, this rule does not apply for domain names.)</p>
<p>It is possible to use both of these rules at the same time.</p>
<p>Given a list of emails, we send one email to each address in the list.
How many different addresses actually receive mails? </p>
<p><strong>Example 1:</strong></p>
<p>Input:
["test.email+alex@leetcode.com","test.e.mail+bob.cathy@leetcode.com","testemail+david@lee.tcode.com"]</p>
<p>Output: 2</p>
<p>Explanation: "testemail@leetcode.com" and "testemail@lee.tcode.com"
actually receive mails </p>
<p>Note:</p>
<p>1 <= emails[i].length <= 100</p>
<p>1 <= emails.length <= 100</p>
<p>Each emails[i] contains exactly one '@' character.</p>
<p>All local and domain names are non-empty.</p>
<p>Local names do not start with a '+' character.</p>
</blockquote>
<p><strong>My declarative solution</strong></p>
<pre><code>/**
* @param {string[]} emails
* @return {number}
*/
var numUniqueEmails = emails => {
return emails.reduce((validMails, mail) => {
const names = mail.split('@');
let [local, domain] = names;
const iPlus = [...local].findIndex(x => x === '+');
if (iPlus !== -1) { local = local.substr(0, iPlus); }
const key = local.split('.').join('') + '@' + domain;
if (!validMails.has(key)) { validMails.add(key); }
return validMails
}, new Set).size;
};
</code></pre>
<p><strong>My Imperative solution</strong></p>
<pre><code>/**
* @param {string[]} emails
* @return {number}
*/
var numUniqueEmails2 = emails => {
const validMails = new Set();
for (const mail of emails) {
let [local, domain] = mail.split('@');
const iPlus = [...local].findIndex(x => x === '+');
if (iPlus !== -1) { local = local.substr(0, iPlus); }
const key = [...local].filter(x => x !== '.').join() + '@' + domain;
if (!validMails.has(key)) { validMails.add(key); }
}
return validMails.size;
};
</code></pre>
<p><strong>My solution with regex</strong></p>
<pre><code>/**
* @param {string[]} emails
* @return {number}
*/
var numUniqueEmails3 = emails => {
const validMails = new Set();
for (const mail of emails) {
let [local, domain] = mail.split('@');
local = local.replace(/\+(.*)$/, '')
.replace(/\./g, '');
console.log(local);
const key = `${local}@${domain}`;
if (!validMails.has(key)) { validMails.add(key); }
}
return validMails.size;
};
</code></pre>
<p><strong>Addendum</strong></p>
<p>in <code>numUniqueEmails</code> ran the code with this snippet:</p>
<pre><code> const names = mail.split('@');
let [local, domain] = names;
</code></pre>
<p>and got 90th percentile. Running it again with this snippet:</p>
<pre><code> let [local, domain] = mail.split('@');
</code></pre>
<p>gives me 25th percentile. I'd assume it should be the opposite. Does anyone know why this is the case and also how come the difference is so big?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T14:44:21.960",
"Id": "425887",
"Score": "0",
"body": "*\"Does anyone know why this is the case and also how come the difference is so big?\"* its not the code that is at fault. Leetcode's distributed processing service is to blame. The very same code submitted at different times of the day and week can return from above 90% to below 50%. It is more a metric of their service load and process spawning latency (Also likely that processes are run on variety of CPU's and clock speeds)"
}
] | [
{
"body": "<ul>\n<li>I don't know what you mean by declarative in this case. All these functions are pure (except the console.log), but the implementations of the functions are all imperative (which is fine of course)</li>\n<li>When adding to a set, you don't need to check if the key exists first. Just add it.</li>\n<li>Splitting the string into an array of chars isn't necessary. You can use string utils instead, for example indexOf('+'). You can also do a split('+')[0] to avoid having the iPlus variable.</li>\n<li>If you swap the reduce for a map, and wrap that in a Set, you don't need to add to set explicitly. It's probably a bit slower though.</li>\n<li>You could add some more newlines to the code to group related concepts, and make it more readable</li>\n</ul>\n\n<p>I came up with the solution below:</p>\n\n<pre><code>const getUniqueEmailKey = email => {\n const [local, domain] = email.split('@')\n return local\n .split('+')[0] // Take everything before +\n .split('.').join('') // Remove dots\n + '@' + domain\n}\n\nconst numUniqueEmails = emails => new Set(emails.map(getUniqueEmailKey)).size\n</code></pre>\n\n<p>About leetcode:\nTry running the code a few more times. The time you get is a bit random...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:21:06.020",
"Id": "425813",
"Score": "0",
"body": "You could replace the first split with a `string.slice()`, from the beginning of the string to the first instance of `+` (you can use `string.indexOf()` to find it). You can replace the second split with a global regex replace, replacing all `.` with blank strings. This way, you don't create a lot of intermediate arrays. `local.slice(0, local.indexOf('+')).replace(/\\./g, '')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:31:18.857",
"Id": "425814",
"Score": "1",
"body": "I don't think slice will work as expected if there are no + signs though. The regex is definitely better, should have thought of that"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:05:37.273",
"Id": "220374",
"ParentId": "220353",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "220374",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T15:05:04.270",
"Id": "220353",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"regex",
"ecmascript-6"
],
"Title": "Unique Email Addresses"
} | 220353 |
<p>Some days ago, I posted a question here: <a href="https://codereview.stackexchange.com/questions/219386/field-class-as-a-basis-for-a-role-playing-game">Field class as basis for a role playing game</a></p>
<p>I payed respect to tips I find useful and made a further development of my Field-classes. These classes have to serve as a basis for a role playing game later.</p>
<p>Now I tested my classes with a little snake game. You can download the program <a href="https://www.dropbox.com/s/rgr8p8cmt4myh0p/Snake.jar?dl=0" rel="noreferrer">here</a>.</p>
<p>The Field-"API" consists of three classes:</p>
<p><strong>Entity:</strong> These class is a basis for all elements that have to appear on a field. You can use this class directly or as a basis for you own Entity-classes.</p>
<pre><code>public class Entity {
protected String name;
protected char symbol;
protected int xCoordinate;
protected int yCoordinate;
// decides if entity can move around on a field
protected boolean moveable;
// decides if other entities can walk on that entity on a field
protected boolean walkable;
// decides if entity can appear on several positions simultaneously
protected boolean multifarious;
public Entity(String name, char symbol, boolean moveable, boolean walkable, boolean multifarious) {
this.name = name;
this.symbol = symbol;
this.moveable = moveable;
this.walkable = walkable;
this.multifarious = multifarious;
}
public Entity(String name, char symbol, boolean moveable, boolean walkable) {
this(name, symbol, moveable, walkable, false);
}
public boolean isMoveable() {
return moveable;
}
public boolean isWalkable() {
return walkable;
}
public boolean isMultifarious() {
return multifarious;
}
public String getName() {
return name;
}
public char getSymbol() {
return symbol;
}
public int getXCoordinate() {
return xCoordinate;
}
// if you want to change both x and y, you should prefer updateCoordinates(x, y) for better readability
public void setXCoordinate(int x) {
this.xCoordinate = x;
}
public int getYCoordinate() {
return yCoordinate;
}
// if you want to change both x and y, you should prefer updateCoordinates(x, y) for better readability
public void setYCoordinate(int y) {
this.yCoordinate = y;
}
public void updateCoordinates(int x, int y) {
setXCoordinate(x);
setYCoordinate(y);
}
}
</code></pre>
<p><strong>Field:</strong> These class contains the entities and manages and displays them.</p>
<pre><code>import java.util.List;
import java.util.ArrayList;
public class Field {
private int height;
private int width;
// only the last entity of a list is drawed on the field
// field is built like that: [height][width] -> List of Entities
private List<List<List<Entity>>> positions;
private boolean multipleEntitiesOnPosition;
private char emptyPositionRepresentation;
private List<Entity> placedEntities;
public Field(int height, int width, boolean multipleEntitiesOnPosition, char emptyPositionRepresentation) {
this.height = height;
this.width = width;
positions = new ArrayList<List<List<Entity>>>();
for (int i = 0; i < height; i++) {
positions.add(new ArrayList<List<Entity>>());
for (int j = 0; j < width; j++) {
positions.get(i).add(new ArrayList<Entity>());
}
}
this.multipleEntitiesOnPosition = multipleEntitiesOnPosition;
placedEntities = new ArrayList<Entity>();
this.emptyPositionRepresentation = emptyPositionRepresentation;
}
public Field(int height, int width, boolean multipleEntitiesOnPosition) {
this(height, width, multipleEntitiesOnPosition, '.');
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public List<Entity> getEntities() {
// user is not allowed to modify list, thats why a copy is given
return new ArrayList<Entity>(placedEntities);
}
private boolean checkForValidCoordinates(int x, int y) {
if (x >= height || y >= width || x < 0 || y < 0) {
return false;
}
return true;
}
public boolean addEntity(Entity entity, int x, int y) {
if (!checkForValidCoordinates(x, y)) {
return false;
}
// check if entity is already on field
if (placedEntities.contains(entity) && !entity.isMultifarious()) {
return false;
}
List<Entity> entityList = positions.get(x).get(y);
// check if entity is already on that position
if (entityList.contains(entity)) {
return false;
}
// check if rule about multiple entities on position is violated
if (!multipleEntitiesOnPosition && !entityList.isEmpty()) {
return false;
}
// check if another entity is already on field that can not be passed
for (Entity ent : entityList) {
if (!ent.isWalkable()) {
return false;
}
}
// check if entity gets placed on another entity that is not moveable
for (Entity ent : entityList) {
if (!ent.isMoveable()) {
return false;
}
}
placedEntities.add(entity);
entityList.add(entity);
entity.updateCoordinates(x, y);
return true;
}
public boolean removeEntity(Entity entity) {
if (!placedEntities.contains(entity)) {
return false;
}
placedEntities.remove(entity);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
List<Entity> entities = positions.get(i).get(j);
if (entities.contains(entity)) {
entities.remove(entity);
if (!entity.isMultifarious()) {
break;
}
}
}
}
return true;
}
public boolean moveEntity(Entity entity, int newX, int newY) {
if (!checkForValidCoordinates(newX, newY)) {
return false;
}
// check if another entity is already on field that can not be passed
for (Entity ent : positions.get(newX).get(newY)) {
if (!ent.isWalkable()) {
return false;
}
}
// check if entity is on field
if (!placedEntities.contains(entity)) {
return false;
}
// check if entity is moveable
if (!entity.isMoveable()) {
return false;
}
positions.get(entity.getXCoordinate()).get(entity.getYCoordinate()).remove(entity);
positions.get(newX).get(newY).add(entity);
entity.updateCoordinates(newX, newY);
return true;
}
public boolean moveEntity(Entity entity, Direction direction) {
switch (direction) {
case UP:
return moveEntity(entity, entity.getXCoordinate() - 1, entity.getYCoordinate());
case DOWN:
return moveEntity(entity, entity.getXCoordinate() + 1, entity.getYCoordinate());
case LEFT:
return moveEntity(entity, entity.getXCoordinate(), entity.getYCoordinate() - 1);
case RIGHT:
return moveEntity(entity, entity.getXCoordinate(), entity.getYCoordinate() + 1);
}
return false;
}
public boolean hasPositionEntities(int x, int y) {
if (positions.get(x).get(y).isEmpty()) {
return false;
}
return true;
}
public List<Entity> getEntitiesOfPosition(int x, int y) {
// user is not allowed to modify list, thats why a copy is given
return new ArrayList<Entity>(positions.get(x).get(y));
}
public String toString() {
StringBuilder returnValue = new StringBuilder();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
List<Entity> entities = positions.get(i).get(j);
if (!entities.isEmpty()) {
char lastSymbol = entities.get(entities.size() - 1).getSymbol();
returnValue.append(lastSymbol);
} else {
returnValue.append(emptyPositionRepresentation);
}
}
returnValue.append('\n');
}
return returnValue.toString();
}
}
</code></pre>
<p><strong>Direction:</strong> This is just an enum that simplifies moving some entities.</p>
<pre><code>public enum Direction {
UP, DOWN, LEFT, RIGHT
}
</code></pre>
<p>To test the functionality of my classes and to test the ability of them to serve usefully for applications I made a "Snake-Game" where a player has to eat all snacks and escape from the snake. If you want, you can also give me hints how to improve these classes, I would be thankful!</p>
<p><strong>Main.java</strong></p>
<pre><code>public class Main {
public static void main(String[] args) {
new Game().play();
}
}
</code></pre>
<p><strong>Game.java</strong></p>
<pre><code>import java.util.Scanner;
public class Game {
public static Scanner scanner = new Scanner(System.in);
public void play() {
boolean run = true;
while (run) {
System.out.println("[1] Start new Game");
System.out.println("[2] Exit Game");
System.out.print("Input: ");
String input = scanner.next();
System.out.println();
switch (input) {
case "1":
new SnakeGame().play();
break;
case "2":
run = false;
break;
}
}
}
}
</code></pre>
<p><strong>SnakeGame.java</strong></p>
<pre><code>import java.util.Scanner;
import java.util.Random;
import java.util.List;
public class SnakeGame {
private static Scanner scanner = new Scanner(System.in);
private Field field;
private Player player;
private Snake snake;
private int score;
private int numOfSnacks;
private int snacksEaten;
public SnakeGame() {
field = new Field(10, 20, false);
player = new Player(field);
snake = new Snake(field, player);
field.addEntity(player, 1, 1);
field.addEntity(snake, 9, 19);
generateSnacks();
score = 0;
snacksEaten = 0;
}
private void generateSnacks() {
numOfSnacks = 20;
int numOfPlacedSnacks = 0;
Random random = new Random();
while (numOfPlacedSnacks < numOfSnacks) {
Entity snack = new Entity("Snack", '#', false, true);
int x = random.nextInt(field.getHeight());
int y = random.nextInt(field.getWidth());
if (!field.hasPositionEntities(x, y)) {
field.addEntity(snack, x, y);
numOfPlacedSnacks++;
}
}
}
public void play() {
while (!snakeCatchedPlayer() && numOfSnacks != snacksEaten) {
System.out.println("Score: " + score + "\n");
System.out.println(field);
player.move();
checkIfPlayerEatSnack();
boolean snakeMoved = snake.move();
clearScreen();
if (!snakeMoved) {
System.out.println("The snake stumbled!\n");
}
}
System.out.println(field);
if (snakeCatchedPlayer()) {
System.out.println("It catched you!\n");
}
if (numOfSnacks == snacksEaten) {
System.out.println("Congratulations! You ate all snacks!");
}
System.out.println("Final score: " + score + "\n");
}
// checks if player and snake are on same position
private boolean snakeCatchedPlayer() {
boolean sameXCoordinate = player.getXCoordinate() == snake.getXCoordinate();
boolean sameYCoordinate = player.getYCoordinate() == snake.getYCoordinate();
if (sameXCoordinate && sameYCoordinate) {
return true;
}
return false;
}
private void checkIfPlayerEatSnack() {
List<Entity> entityList = field.getEntitiesOfPosition(player.getXCoordinate(), player.getYCoordinate());
for (Entity ent : entityList) {
if (ent.getName().equals("Snack")) {
field.removeEntity(ent);
score++;
snacksEaten++;
}
}
}
private void clearScreen() {
for (int i = 0; i < 20; i++) {
System.out.println();
}
}
}
</code></pre>
<p><strong>Player.java</strong></p>
<pre><code>import java.util.Scanner;
public class Player extends Entity {
private static Scanner scanner = new Scanner(System.in);
private Field field;
public Player(Field field) {
super("Player", 'P', true, true);
this.field = field;
}
public void move() {
System.out.print("Input: (w, a, s, d): ");
String input = scanner.next();
System.out.println();
switch (input) {
case "w":
field.moveEntity(this, Direction.UP);
break;
case "a":
field.moveEntity(this, Direction.LEFT);
break;
case "s":
field.moveEntity(this, Direction.DOWN);
break;
case "d":
field.moveEntity(this, Direction.RIGHT);
break;
}
}
}
</code></pre>
<p><strong>Snake.java</strong></p>
<pre><code>import java.util.Random;
public class Snake extends Entity {
private static Random random = new Random();
private Field field;
private Player player;
public Snake(Field field, Player player) {
super("Snake", 'S', true, true);
this.field = field;
this.player = player;
}
// returns if snake was able to move
public boolean move() {
// able to move?
if (random.nextInt(4) == 3) {
return false;
}
if (player.getXCoordinate() > xCoordinate) {
field.moveEntity(this, xCoordinate + 1, yCoordinate);
return true;
} else if (player.getXCoordinate() < xCoordinate) {
field.moveEntity(this, xCoordinate - 1, yCoordinate);
return true;
}
if (player.getYCoordinate() > yCoordinate) {
field.moveEntity(this, xCoordinate, yCoordinate + 1);
return true;
} else if (player.getYCoordinate() < yCoordinate) {
field.moveEntity(this, xCoordinate, yCoordinate - 1);
return true;
}
return false;
}
}
</code></pre>
| [] | [
{
"body": "<p>The way to move things is extremely restricted. Instead of marking entities moveable (mobile?), encapsulate the behaviour of mobility behind an interface and inject a suitable implementation to each entity. When the time comes to move an entity, whoever is responsible for triggering it, fetch the mobility implementation from the entity and have it perform the motion on the entity in question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T17:31:21.670",
"Id": "220363",
"ParentId": "220355",
"Score": "1"
}
},
{
"body": "<p>I only got to the core classes, not the game implementation. Hopefully this will give you something to think about.</p>\n\n<h1>General</h1>\n\n<p>Classes that are not designed for extension should be explicitly marked as final. Variables that will not be reassigned should also be marked as final. This makes it easier for readers of your code.</p>\n\n<p>I'm assuming this API is designed only for a console UI. You've made several decisions which tie you strongly to that format, as noted below.</p>\n\n<h1>Entity</h1>\n\n<p>Avoid extension where possible. Classes are limited to exactly one parent class, and you can design yourself into a corner. I'd suggest making <code>Entity</code> an interface and copying the implementation into an abstract class. Clients can then choose whether or not to use the base implementation.</p>\n\n<p>Classes that should not be instantiable should be declared as <code>abstract</code>. Your design is unclear - some instances (Snake, Player) extend <code>Entity</code>, while others just are entities (Snack). The difference appears to be whether or not the Entity can move, but movement is not part of the contract of the Entity class.</p>\n\n<p>None of the protected properties should be protected. You lose encapsulation of them - they no longer belong to Entity. All the variables are already available via accessors.</p>\n\n<p><code>walkable</code> is not a great property name. Something like <code>blocksMovement</code> would be more clear.</p>\n\n<p>Encoding the <code>symbol</code> directly onto an <code>Entity</code> ties you pretty strongly to a console UI. <code>symbol</code> becomes meaningless if you add GUI support and clients don't implement a console version of their game.</p>\n\n<p>The comments should all be Javadoc. Since This class is intended as part of your API, it should in general be much more strongly documented.</p>\n\n<p>\"multifarious\" does not mean \"can appear in multiple locations at the same time\". The property is never used. Don't add support for features unless you're sure you need them, because you have to support them forever or break your clients. The entire concept of the property is dubious - how can an entity instance have a single x coordinate, a single y coordinate, and yet exist in multiple locations?</p>\n\n<h1>Field</h1>\n\n<p>As of recent Java versions, you no longer need to specify the generic type information on the RHS in most cases.</p>\n\n<p>The constructor is easier to read if all the simple assignments occur before you build the <code>positions</code> variable.</p>\n\n<p>Where possible, assign variables where they're defined.</p>\n\n<p>Again you're directly tying yourself to a console with <code>emptyPositionRepresentation</code>. If it's your intent to do so, it should be mentioned. If not, it should be fixed.</p>\n\n<p>In the constructor, it's a little cleaner to keep the reference to the created <code>List</code> around rather than calling <code>get()</code> <code>j</code> times.</p>\n\n<p>You can't track the position of an <code>Entity</code> in both <code>Entity</code> and <code>Field</code>. It will confuse clients and they will get out synch. Let the <code>Field</code> handle this.</p>\n\n<p>Good use of a defensive copy in <code>getEntities()</code>. Using <code>Collections.unmodifiableList()</code> is another option. Note that the entities themselves can still be modified by callers.</p>\n\n<p><code>checkValidCoordinates</code> can have its logic simplified to <code>return !(x >= height ...</code> or <code>return (x >= 0) && (x < height) ..</code>. <code>hasPositionEntities</code> can likewise be simplified.</p>\n\n<p>You're always checking <code>!checkValidCoordinates</code>. It would be easier if the method was <code>areInvalidCoordinates</code>.</p>\n\n<p>Rather than dealing with a <code>List<List<List<Entity>>></code>, it might be easier to deal with a <code>Position[][]</code>, where <code>Position</code> is a wrapper for a List. You can add some simple methods to that new class which would clean up your code quite a bit.</p>\n\n<p><code>addEntity</code> is checking if the entity has been placed, and then it's checking the position to see if it's already there. The second check shouldn't be needed - if it's on the position, it should be tracked in the placed entities already.</p>\n\n<p>Rather than tracking <code>multipleEntities</code> as a boolean, perhaps track a capacity for the position? Then you have a lot more flexibility than just one or many.</p>\n\n<p>It would clean up your code if <code>placedEntities</code> was a <code>Map</code> of entities to their positions.</p>\n\n<p>The validation checks are not consistent for adding vs. moving into a space. Specifically, <code>add()</code> checks to see if any of the entities in the position are moveable, for reasons that are not clear. If you decided to use a <code>Position</code> object, you could move that logic into one method on the Position.</p>\n\n<p><code>getEntities()</code> appears to be unused and can be removed.</p>\n\n<p>You might consider throwing exceptions in some cases rather than just returning <code>false</code>. For instance, if the client tries to move something that's not on the field, an exception is harder to miss than a return value.</p>\n\n<p><code>moveEntity</code> isn't making sure that the entity is on the field.</p>\n\n<p>Don't have a switch statement that does something for each possible enum value. Move that logic to the enum.</p>\n\n<p>If you were to make all these changes, your code might look something like:</p>\n\n<pre><code>public abstract class AbstractEntity implements Entity {\n\n private final String name;\n private final char symbol;\n\n /** controls if this entity can move around on a {@link Field} */\n private final boolean moveable;\n\n /** controls if other entities can walk on that entity on a {@link Field} */\n private final boolean blocksMovement;\n\n public AbstractEntity(final String name, final char symbol, final boolean moveable, final boolean blocksMovement) {\n this.name = name;\n this.symbol = symbol;\n this.moveable = moveable;\n this.blocksMovement = blocksMovement;\n }\n\n public boolean isMoveable() {\n return this.moveable;\n }\n\n public boolean blocksMovement() {\n return this.blocksMovement;\n }\n\n public String getName() {\n return this.name;\n }\n\n public char getSymbol() {\n return this.symbol;\n }\n\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>public enum Direction {\n\n UP(-1, 0),\n DOWN(+1, 0),\n LEFT(0, -1),\n RIGHT(0, 1);\n\n private final int adjustX;\n private final int adjustY;\n\n private Direction(final int adjustX, final int adjustY) {\n this.adjustX = adjustX;\n this.adjustY = adjustY;\n }\n\n public int newX(final Position position) {\n return position.getXCoordinate() + this.adjustX;\n }\n\n public int newY(final Position position) {\n return position.getYCoordinate() + this.adjustY;\n }\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>public interface Entity {\n\n boolean isMoveable();\n boolean blocksMovement();\n String getName();\n char getSymbol();\n\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>public final class Field {\n\n private final int height;\n private final int width;\n\n // only the last entity of a list is drawn on the field\n // field is built like that: [height][width] -> List of Entities\n private final Position[][] positions;\n private final Map<Entity, Position> placedEntities = new HashMap<>();\n\n public Field(final int height, final int width, final int positionCapacity) {\n this(height, width, positionCapacity, '.');\n }\n\n private Field(\n final int height,\n final int width,\n final int positionCapacity,\n final char emptyPositionRepresentation) {\n\n this.height = height;\n this.width = width;\n\n positions = new Position[height][width];\n for (int i = 0; i < height; i++) {\n for (int j = 0; j < width; j++) {\n positions[i][j] = new Position(i, j, positionCapacity, emptyPositionRepresentation);\n }\n }\n }\n\n public int getHeight() {\n return this.height;\n }\n\n public int getWidth() {\n return this.width;\n }\n\n public boolean addEntity(final Entity entity, final int x, final int y) {\n if (this.areInvalidCoordinates(x, y)) {\n return false;\n }\n\n if (this.placedEntities.containsKey(entity)) {\n return false;\n }\n\n final Position position = positions[x][y];\n if (!position.canAddEntity()) {\n return false;\n }\n\n this.placedEntities.put(entity, position);\n position.add(entity);\n\n return true;\n }\n\n public boolean removeEntity(final Entity entity) {\n if (!placedEntities.containsKey(entity)) {\n return false;\n }\n\n final Position position = placedEntities.remove(entity);\n position.remove(entity);\n return true;\n }\n\n public boolean moveEntity(final Entity entity, final int newX, final int newY) {\n if (this.areInvalidCoordinates(newX, newY)) {\n return false;\n }\n\n if (!placedEntities.containsKey(entity)) {\n return false;\n }\n\n if (!entity.isMoveable()) {\n return false;\n }\n\n final Position newPosition = positions[newX][newY];\n if (!newPosition.canAddEntity()) {\n return false;\n }\n\n final Position oldPosition = this.placedEntities.put(entity, newPosition);\n oldPosition.remove(entity);\n newPosition.add(entity);\n\n return true;\n }\n\n public boolean moveEntity(final Entity entity, final Direction direction) {\n final Position position = this.placedEntities.get(entity);\n if (position == null) {\n return false;\n }\n\n return moveEntity(entity, direction.newX(position), direction.newY(position));\n }\n\n public boolean hasEntitiesAt(final int x, final int y) {\n return !this.positions[x][y].isEmpty();\n }\n\n public Collection<Entity> getEntitiesAt(final int x, final int y) {\n return this.positions[x][y].getEntities();\n }\n\n public Position getPositionForEntity(final Entity entity) {\n return this.placedEntities.get(entity);\n }\n\n public String toString() {\n final StringBuilder returnValue = new StringBuilder();\n for (int i = 0; i < this.height; i++) {\n for (int j = 0; j < this.width; j++) {\n returnValue.append(positions[i][j].asChar());\n }\n returnValue.append('\\n');\n }\n return returnValue.toString();\n }\n\n private boolean areInvalidCoordinates(final int x, final int y) {\n return (x < 0) || (x >= this.height) || (y < 0) && (y >= this.width);\n }\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>public final class Position {\n\n private final int xCoordinate;\n private final int yCoordinate;\n private final int capacity;\n private final char emptyPositionRepresentation;\n private final List<Entity> entities = new ArrayList<>();\n\n public Position(\n final int xCoordinate,\n final int yCoordinate,\n final int capacity,\n final char emptyPositionRepresentation) {\n this.xCoordinate = xCoordinate;\n this.yCoordinate = yCoordinate;\n this.capacity = capacity;\n this.emptyPositionRepresentation = emptyPositionRepresentation;\n }\n\n public int getXCoordinate() {\n return this.xCoordinate;\n }\n\n public int getYCoordinate() {\n return this.yCoordinate;\n }\n\n public boolean contains(final Entity entity) {\n return this.entities.contains(entity);\n }\n\n public boolean isEmpty() {\n return this.entities.isEmpty();\n }\n\n public boolean add(final Entity entity) {\n if (this.capacity > this.entities.size()) {\n return false;\n }\n return this.entities.add(entity);\n }\n\n public boolean remove(final Entity entity) {\n return this.entities.remove(entity);\n }\n\n public boolean canAddEntity() {\n if (this.capacity > this.entities.size()) {\n return false;\n }\n\n for (final Entity entity : this.entities) {\n if (entity.blocksMovement()\n || !entity.isMoveable()) {\n return false;\n }\n }\n\n return true;\n }\n\n public Collection<Entity> getEntities() {\n return Collections.unmodifiableCollection(this.entities);\n }\n\n /**\n * @return a character representation of the entities in this position.\n */\n public char asChar() {\n if (entities.isEmpty()) {\n return this.emptyPositionRepresentation;\n }\n\n return this.entities.get(entities.size() - 1).getSymbol();\n }\n\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T05:42:42.033",
"Id": "220500",
"ParentId": "220355",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T15:34:52.107",
"Id": "220355",
"Score": "7",
"Tags": [
"java",
"beginner",
"game",
"api",
"snake-game"
],
"Title": "Snake Game with own Field API"
} | 220355 |
<p>I wrote code to show the structure of a Fibonacci sequence pattern in a graphical way. First I structure a tree given a variable the user inputs for how many iterations of the sequence they want to print. Then, it converts the numbers into the Fibonacci sequence.</p>
<p>My concern is that this doesn't seem very efficient, first I build a tree, then go through each node again and do the <em>entire</em> Fibonacci calculation on it. Instead, I was hoping for a suggestion to change the code so that it could generate the nodes and the Fibonacci number at the same time. Maybe, instead of two recursive functions, there is just one that calls itself: </p>
<pre><code>fibo(num)=fibo(num-1)+fibo(num-2)
</code></pre>
<p>where <code>(num-1)</code> is the left node and <code>(num-2)</code> is on the right.<br></p>
<pre><code>from binarytree import Node
# Generates a binarytree with the correct *iterations* numbers.
def makeTree(node):
if node.value > 1:
node.left = makeTree(Node(node.value - 1))
node.right = makeTree(Node(node.value - 2))
return node
# Converts the iterated binary tree numbers into fibonacci numbers
def fibonacci(a, b , num):
if num > 0:
a += b
return fibonacci(b, a, num - 1)
return a
a = int(input("Enter number: "))
fibTree = makeTree(Node(a))
for x in fibTree:
x.value = fibonacci(0, 1, x.value)
print(fibTree)
</code></pre>
<p>Expected result if a user enters 5 as how many iterations they want.<br><br>
<a href="https://i.stack.imgur.com/ICG4L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ICG4L.png" alt="fibo seq console log"></a></p>
| [] | [
{
"body": "<p>One thing I would recommend is using <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoization</a>. Make a dictionary of fibonacci numbers that you've already calculated (do the math once when the user gives you input). When you go to calculate a node's fibonacci value, just do a check in the dictionary for the appropriate value. This will avoid calculating the lower levels so much.<br>\nActually, if you only know the level the node is on, you could instead put the fibonacci values in an array (python list) where the index of the array is the number that should be shown on that level of the tree.\nEither way, there are ways to use memoization to avoid duplicate effort, and it can make a big difference in your speed for a lot of problems.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T23:01:59.100",
"Id": "220384",
"ParentId": "220357",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:15:21.840",
"Id": "220357",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"tree",
"fibonacci-sequence"
],
"Title": "Fibonacci sequence binary tree console logger"
} | 220357 |
<p>Task: Return true if a transaction is allowed and return false if transaction is prohibited. </p>
<p>Details:
1. String is represented as an "array" that can contain up to three elements. </p>
<p>We need to evaluate a charge against a list of rules and see if we can allow the transaction to happen.</p>
<p>Each rule (Allow or Deny) can contain up to two statements divided by "AND" or "OR"</p>
<p>The following comparison operators for rules are valid: </p>
<pre><code> ">", "<", ">=", "<=", "==", "!="
</code></pre>
<p>The rest of the rules can be made up.</p>
<p>Example Input (Complex):</p>
<pre><code>"['CHARGE: card_country = US & currency = USD & amount = 600 &
ip_country = CA','ALLOW: amount > 500 AND currency!=EUR', 'DENY:
card_country == AUS]"
</code></pre>
<p>Outcome: <code>True</code> (because 600>500 and USD!=EUR and USD!=AUS)<br>
Example Input 2 (Simple):</p>
<pre><code>"['CHARGE: card_country = US & currency = USD & amount = 200 &
ip_country = CA','ALLOW: amount > 500"
</code></pre>
<p>Outcome: <code>False</code> (Because 200<500) </p>
<hr>
<p>My Implementation and questions. </p>
<ol>
<li><p>I struggled to figure out how to efficiently parse this string in multiple formats, so I mostly used <code>String.Split</code> and <code>Trim()</code>. Not sure if should've used regex instead? </p></li>
<li><p>I'm not sure if I structured the code correctly? I do have some classes, but I'm not sure if I even need "Rule" and "RuleSet" is there an easier way? </p></li>
<li><p>Major issue - it's hard to figure out how to interpret comparators from a string into actual code. What technique is usually used to work with dynamic comparisons? </p></li>
<li><p>Probably will fail on a lot of cases at this point. How to correctly capture exceptions and test? (I cannot wrap everything in try catch, I do not think.) </p></li>
<li><p>Charge object is a parameter name and value, not static fields. Should I use fields "currency", "amount", etc. for Charge class? </p></li>
<li><p>Overall, the code looks too complex and hard to follow. Any suggestions on how to improve?</p></li>
</ol>
<p>Radar.cs </p>
<pre><code>public class Radar
{
private readonly List<string> cleanUpValues = new List<string>() { "'", "]", "["};
private readonly List<string> operators = new List<string>() { ">", "<", ">=", "<=", "==", "!=" };
public bool CheckTransaction(string input)
{
input = Utils.RemoveStrings(input, cleanUpValues);
var result = input.Split(',');
if (result.Count()<=1)
{
throw new ArgumentOutOfRangeException("input", "radar string has invalid format");
}
var charge = new Charge();
RuleSet allowRules = null;
RuleSet denyRules = null;
foreach (var res in result)
{
if (res.TrimStart().StartsWith("CHARGE:"))
{
charge = CreateCharge(res.Replace("CHARGE:",""));
}
else if (res.TrimStart().StartsWith("ALLOW:"))
{
allowRules = CreateRuleSet(res.Replace("ALLOW:", ""), true);
}
else if (res.TrimStart().StartsWith("DENY:"))
{
denyRules = CreateRuleSet(res.Replace("DENY:",""), false);
}
}
var chargeString = result[0];
var ruleString = result[1];
return EvaluateRulesAgainstCharge(charge, allowRules, denyRules);
}
public Charge CreateCharge(string chargeString)
{
Charge charge = new Charge();
var splitParameters = chargeString.Split('&');
foreach (var parameter in splitParameters)
{
var param = parameter.Split('=');
var value = param[1].Trim();
charge.Parameters.Add(new ChargeParameter(param[0].Trim(), param[1].Trim()));
}
return charge;
}
public RuleSet CreateRuleSet(string ruleString, bool IsAllowed)
{
var rules = new List<string>();
bool andOperator = false;
if (ruleString.Contains("AND"))
{
rules = ruleString.Split(new string[] {"AND"}, StringSplitOptions.RemoveEmptyEntries).ToList();
andOperator = true;
}
else if (ruleString.Contains("OR"))
{
rules = ruleString.Split(new string[] {"OR"}, StringSplitOptions.RemoveEmptyEntries).ToList();
}
else
{
rules.Add(ruleString);
}
var ruleSet = new RuleSet(IsAllowed, andOperator);
foreach (var rule in rules)
{
foreach (var op in operators)
{
if (rule.Contains(op))
{
var ruleParams = rule.Split(new string[] { op }, StringSplitOptions.RemoveEmptyEntries);
Rule r = new Rule(op, ruleParams[0].Trim(), ruleParams[1].Trim());
ruleSet.Rules.Add(r);
}
}
}
return ruleSet;
}
public bool EvaluateRulesAgainstCharge(Charge charge, RuleSet allowRules, RuleSet denyRules)
{
bool AllowTransaction = true;
if (allowRules != null)
{
foreach (var rule in allowRules.Rules)
{
var chargeParam = charge.Parameters.First(p => p.ParameterName == rule.ParameterName);
if (rule.ParameterName == "amount")
{
AllowTransaction = AllowTransaction && Utils.Compare<double>(rule.Operator, Double.Parse(chargeParam.ParameterValue), Double.Parse(rule.Value));
}
else
{
AllowTransaction = AllowTransaction && Utils.Compare<string>(rule.Operator, chargeParam.ParameterValue, rule.Value);
}
if (!AllowTransaction)
break;
}
}
if (denyRules != null)
{
foreach (var rule in denyRules.Rules)
{
var chargeParam = charge.Parameters.First(p => p.ParameterName == rule.ParameterName);
if (rule.ParameterName == "amount")
{
AllowTransaction = AllowTransaction && !Utils.Compare<double>(rule.Operator, Double.Parse(chargeParam.ParameterValue), Double.Parse(rule.Value));
}
else
{
AllowTransaction = AllowTransaction && !Utils.Compare<string>(rule.Operator, chargeParam.ParameterValue, rule.Value);
}
if (!AllowTransaction)
break;
}
}
return AllowTransaction;
}
}
</code></pre>
<p>Charge.cs </p>
<pre><code>public class Charge
{
private List<ChargeParameter> parameters = new List<ChargeParameter>();
public List<ChargeParameter> Parameters { get => parameters; set => parameters = value; }
}
</code></pre>
<p>ChargeParameter.cs </p>
<pre><code>public class ChargeParameter
{
public string ParameterName { get; private set; }
public string ParameterValue { get; private set; }
public ChargeParameter(string parameterName, string parameterValue)
{
ParameterName = parameterName;
ParameterValue = parameterValue;
}
}
</code></pre>
<p>Rule.cs </p>
<pre><code>public class Rule
{
public string Operator { get; private set; }
public string ParameterName { get; private set; }
public string Value { get; private set; }
public Rule(string op, string parameterName, string value)
{
Operator = op;
ParameterName = parameterName;
Value = value;
}
}
</code></pre>
<p>RuleSet.cs </p>
<pre><code>public class RuleSet
{
public bool IsAllow { get; private set; }
public List<Rule> Rules { get; private set; }
public bool AndOperator { get; private set; }
public RuleSet(bool isAllow, bool andOperator)
{
IsAllow = isAllow;
AndOperator = andOperator;
Rules = new List<Rule>();
}
public void AddRule(Rule rule)
{
Rules.Add(rule);
}
}
</code></pre>
<p>Utils.cs </p>
<pre><code>public static class Utils
{
public static string RemoveStrings(string input, List<string> charsToRemove)
{
foreach (var c in charsToRemove)
{
input = input.Replace(c, string.Empty);
}
return input;
}
public static bool Compare<T>(string op, T left, T right) where T : IComparable<T>
{
switch (op)
{
case "<": return left.CompareTo(right) < 0;
case ">": return left.CompareTo(right) > 0;
case "<=": return left.CompareTo(right) <= 0;
case ">=": return left.CompareTo(right) >= 0;
case "==": return left.Equals(right);
case "!=": return !left.Equals(right);
default: throw new ArgumentException("Invalid comparison operator: {0}", op);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T16:59:20.210",
"Id": "426334",
"Score": "0",
"body": "Hi! Can you elaborate more on the CHARGE: input? Will it always contain the four fields \"card_country\", \"ip_country\", \"currency\" and \"amount\", or could it contain more/less fields?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T18:15:00.947",
"Id": "426358",
"Score": "0",
"body": "@cariehl, I think it will always stay the same"
}
] | [
{
"body": "<p>I'm not sure how to answer all your questions but at least I'll provide my two cents :) </p>\n\n<ol>\n<li>Don't use regex unless you really need to. Regex is <a href=\"https://blog.codinghorror.com/regex-performance/\" rel=\"nofollow noreferrer\">notorious for its slow performance on large strings</a>. </li>\n<li>I was thinking about some rule engine before I got to your code. So I think your class structure is perfectly fine.</li>\n</ol>\n\n<hr>\n\n<p>Regarding the code readability: \n - You could rename <code>Utils.RemoveStrings</code> to <code>Utils.SanitizeInput</code> or something in order to better express the intention behind your method. Also, you can move <code>cleanUpValues</code> inside in order to reduce the number of parameters.\n - Charge parameters can be converted to auto-property</p>\n\n<pre><code>public List<ChargeParameter> Parameters { get; } = new List<ChargeParameter>();\n</code></pre>\n\n<ul>\n<li>Please pay attention there is some dead code. </li>\n<li>Many methods can be made private\n\n<ul>\n<li>No need to use <code>&&</code> operator for your evaluation. It can be rewritten like this. </li>\n</ul></li>\n</ul>\n\n<pre><code> private bool EvaluateRulesAgainstCharge(Charge charge, RuleSet allowRules, RuleSet denyRules)\n {\n var allowTransaction = CheckRules(charge, allowRules, true);\n\n if (!allowTransaction)\n return false;\n\n allowTransaction = CheckRules(charge, denyRules, false);\n return allowTransaction;\n }\n\n private static bool CheckRules(Charge charge, RuleSet rules, bool expectedResult)\n {\n var allowTransaction = true;\n if (rules != null)\n {\n foreach (var rule in rules.Rules)\n {\n var chargeParam = charge.Parameters.First(p => p.ParameterName == rule.ParameterName);\n if (rule.ParameterName == \"amount\")\n {\n allowTransaction = Utils.Compare(rule.Operator, double.Parse(chargeParam.ParameterValue),\n double.Parse(rule.Value)) == expectedResult;\n }\n else\n {\n allowTransaction = Utils.Compare(rule.Operator, chargeParam.ParameterValue, rule.Value) == expectedResult;\n }\n\n if (!allowTransaction)\n break;\n }\n }\n\n return allowTransaction;\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:23:18.647",
"Id": "220412",
"ParentId": "220358",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:16:28.470",
"Id": "220358",
"Score": "5",
"Tags": [
"c#",
"strings",
"dynamic-programming"
],
"Title": "Identify fraudulent bank transactions"
} | 220358 |
<p>This is the improved code of <a href="https://codereview.stackexchange.com/questions/220189/sfml-snake-game-in-c">a question I asked some days ago</a>.</p>
<h1>main.cpp</h1>
<pre><code>#include "app.h"
int main() {
Game::app game(800, 600, L"Test");
game.start();
game.end();
}
</code></pre>
<h1>app.h</h1>
<pre><code>#pragma once
#include <SFML/Graphics.hpp>
#include "Snake.h"
#include "Board.h"
namespace Game {
class app {
public:
app(int windowWidth, int windowHeight, const wchar_t* name);
~app() = default;
// Runs the app
void start();
void end();
private:
// MEMBER VARIABLES
const int winWidth, winHeight;
const float common_divisor;
sf::RenderWindow window;
Board board;
sf::Font calibri;
// MEMBER FUNCTIONS
void drawWindow();
void handleEvents();
void updateWindow();
};
}
</code></pre>
<h1>app.cpp</h1>
<pre><code>#include "app.h"
#include <iostream>
#include <thread>
#include <chrono>
Game::app::app(int windowWidth, int windowHeight, const wchar_t* name)
: winWidth{ windowWidth }, winHeight{ windowHeight }, common_divisor{ 40.0f } {
if (!calibri.loadFromFile("res/fonts/arial.ttf")) {
std::wcout << L"[ERROR]: Couldn't load font\n";
}
window.create(sf::VideoMode(winWidth, winHeight), name);
window.setFramerateLimit(5);
}
// Handles any game event
void Game::app::handleEvents() {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::TextEntered:
board.changeDirection(static_cast<char>(event.text.unicode));
}
}
}
// Draws all game objects
void Game::app::drawWindow() {
for (size_t i = 0, h = Board::height; i < h; ++i) {
for (size_t j = 0, w = Board::width; j < w; ++j) {
// Draws walls
if (board[i * w + j] == 2) {
sf::RectangleShape rect;
rect.setSize({ common_divisor, common_divisor });
rect.setPosition({ common_divisor * j, common_divisor * i});
window.draw(rect);
}
// Draws snake
else if (board[i * w + j] == 3) {
sf::RectangleShape rect;
rect.setFillColor(sf::Color::Green);
rect.setSize({ common_divisor, common_divisor });
rect.setPosition({ common_divisor * j, common_divisor * i });
window.draw(rect);
}
// Draws food
else if (board[i * w + j] == 4) {
sf::RectangleShape rect;
rect.setFillColor(sf::Color::Red);
rect.setSize({ common_divisor, common_divisor });
rect.setPosition({ common_divisor * j, common_divisor * i });
window.draw(rect);
}
}
}
// Draws the game score
sf::Text text;
text.setFont(calibri);
text.setPosition({ 0.0f, 0.0f });
text.setString("Score: " + std::to_string(board.score()));
text.setFillColor(sf::Color::Black);
window.draw(text);
}
// Updates the render window
void Game::app::updateWindow() {
window.clear(sf::Color::Black);
drawWindow();
window.display();
}
// Starts the app
void Game::app::start() {
while (window.isOpen()) {
handleEvents();
board.update(window);
updateWindow();
}
}
void Game::app::end() {
std::wcout << L"Game over!\nScore: " << board.score() << L'\n';
std::this_thread::sleep_for((std::chrono::milliseconds)3000);
}
</code></pre>
<h1>Snake.h</h1>
<pre><code>#pragma once
#include <SFML/Graphics.hpp>
#include <vector>
#include "Coord.h"
class Snake {
public:
Snake();
~Snake() = default;
// Changes the dir value based on the input
void changeDirection(char input);
// Adds a piece to the snake and returns its location
Coord add();
size_t size();
/* Moves all pieces and returns
the previous position of last piece */
Coord follow();
Coord moveHead(); // Moves and returns position of new head
Coord headLocation() const;
private:
// MEMBER VARIABLES
struct Snake_segment
{
Coord current, previous;
};
enum direction {
UP = 0,
RIGHT,
DOWN,
LEFT
};
std::vector<Snake_segment> snakeContainer;
direction dir;
public:
Snake_segment operator[](int i) const;
};
</code></pre>
<h1>Snake.cpp</h1>
<pre><code>#include "Snake.h"
// Initializes a two-piece snake
Snake::Snake()
: dir { RIGHT } {
Snake_segment head{ {10, 7}, {9, 7} };
snakeContainer.push_back(head);
--head.current.x;
snakeContainer.push_back(head);
}
Coord Snake::add() {
snakeContainer.push_back({
snakeContainer.back().previous,
snakeContainer.back().previous
});
return snakeContainer.back().current;
}
size_t Snake::size() {
return snakeContainer.size();
}
// Changes the direction based on input (BUGGED)
void Snake::changeDirection(char input) {
switch (input) {
case 'w':
if (dir != DOWN) dir = UP;
break;
case 'd':
if (dir != LEFT) dir = RIGHT;
break;
case 's':
if (dir != UP) dir = DOWN;
break;
case 'a':
if (dir != RIGHT) dir = LEFT;
}
}
// All the pieces follow the head
Coord Snake::follow() {
auto it = snakeContainer.begin();
for (auto prev = it++; it != snakeContainer.end(); ++it, ++prev) {
it->previous = it->current;
it->current = prev->previous;
}
return snakeContainer.back().previous;
}
Coord Snake::moveHead() {
snakeContainer[0].previous = snakeContainer[0].current;
switch (dir) {
case UP:
--snakeContainer[0].current.y;
break;
case RIGHT:
++snakeContainer[0].current.x;
break;
case DOWN:
++snakeContainer[0].current.y;
break;
case LEFT:
--snakeContainer[0].current.x;
}
return snakeContainer.front().current;
}
Snake::Snake_segment Snake::operator[](int i) const { return snakeContainer[i]; }
Coord Snake::headLocation() const { return snakeContainer.front().current; }
</code></pre>
<h1>Board.h</h1>
<pre><code>#pragma once
#include "Snake.h"
class Board {
public:
Board();
~Board() = default;
void update(sf::RenderWindow& win);
void changeDirection(char input);
char operator[](int i) const;
int score() const;
static constexpr int width = 20;
static constexpr int height = 15;
private:
enum Tile {
OPEN = 1,
WALL,
SNAKE,
FOOD
};
// MEMBER VARIABLES
Snake snake;
std::string map;
int m_score;
// MEMBER FUNCTIONS
void genFood();
bool place(Coord coord, int item); // Sets a cell a certain value
bool isEmpty(Coord coord) const;
int at(Coord coord) const;
};
</code></pre>
<h1>Board.cpp</h1>
<pre><code>#include "Board.h"
#include <random>
Board::Board()
: m_score{ 0 } {
// Creates a 20x15 grid
map = {
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
};
genFood();
}
int Board::at(Coord coord) const {
return map[coord.y * width + coord.x];
}
bool Board::isEmpty(Coord coord) const {
return at(coord) == OPEN;
}
// Sets a cell a certain value
bool Board::place(Coord coord, int item) {
if (item != OPEN && !isEmpty(coord))
return false;
map[coord.y * width + coord.x] = item;
return true;
}
void Board::genFood() {
int fx, fy;
do {
std::random_device gen;
std::uniform_int_distribution<int> disX(0, width - 1);
std::uniform_int_distribution<int> disY(0, height - 1);
fx = disX(gen);
fy = disY(gen);
} while (map[fy * Board::width + fx] != OPEN);
map[fy * width + fx] = FOOD;
}
void Board::update(sf::RenderWindow& win) {
auto newHead{ snake.moveHead() };
place(snake.follow(), OPEN);
switch (at(snake.headLocation())) {
case WALL:
case SNAKE:
win.close();
break;
case FOOD:
place(snake.headLocation(), OPEN);
place(snake.add(), SNAKE);
m_score += 100;
genFood();
}
place(newHead, SNAKE);
}
void Board::changeDirection(char input) {
snake.changeDirection(input);
}
char Board::operator[](int i) const { return map[i]; }
int Board::score() const { return m_score; }
</code></pre>
<h1>Coord.h</h1>
<pre><code>#pragma once
struct Coord {
unsigned int x, y;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:32:53.580",
"Id": "425772",
"Score": "0",
"body": "Immediately after this update i replaced the random device with a pseudo random generator."
}
] | [
{
"body": "<p>Your program is definitely improved over the last version. Good job! Here are some ideas for you about further improvements.</p>\n\n<h2>Make the object interface easy for the user</h2>\n\n<p>The <code>app</code> object has two public functions, <code>start</code> and <code>end</code> that are apparently intended to be called in that order. To me, it would make more sense to eliminate <code>end</code> and simply move the contents of <code>end</code> to the end of <code>start</code> outside the <code>while</code> loop. That way the user only need to make a single call. Another idea would be to have a freestanding function that does what <code>main</code> currently is doing. It might look like this:</p>\n\n<pre><code>void snakes(int width, int height, const wchar_t *label) {\n Game::app game(width, height, label);\n game.start();\n}\n</code></pre>\n\n<h2>Try to make the application portable</h2>\n\n<p>The application currently tries to load the font from \"res/fonts/arial.ttf\" but no such file is on my machine so that load attempt fails. The error message is good, but could be better if it were to tell the user the actual path name the program is trying to use. Even better would be to allow the user to select a font or at least make it configurable per platform. This also leads us to the next suggestion.</p>\n\n<h2>Reduce or name and isolate constants</h2>\n\n<p>To run this code on my Linux machine, I created a new variable:</p>\n\n<pre><code>static const auto fontfile{\"/usr/share/fonts/gnu-free/FreeSans.ttf\"};\n</code></pre>\n\n<p>Then I used <code>fontfile</code> to load the file instead of having a hardcoded string embedded within the constructor. This way it's much easier to find and, if needed, change in the future. Similarly, instead of passing a constant to construct the <code>common_divisor</code>, one could instead compute it like this:</p>\n\n<pre><code>common_divisor{static_cast<float>(windowWidth)/Board::width}\n</code></pre>\n\n<p>Using that method, the code will continue to work even with different size windows as long as they have a 4:3 aspect ratio. This brings us to the next suggestion.</p>\n\n<h2>Avoid hardcoding large, regular data structures</h2>\n\n<p>There's nothing particularly <em>wrong</em> with having the default map hardcoded as in the current code, but it would be very simple to make it much more flexible and interesting. One way to do that is to construct the entire <code>Board</code> on the fly. Here's one way to do that:</p>\n\n<pre><code>Board::Board() : \n map(static_cast<size_t>(width*height), static_cast<char>(OPEN))\n{\n // set top and bottom walls\n for (unsigned i=0; i < width; ++i) {\n place({i, 0}, WALL);\n place({i, height-1}, WALL);\n }\n // set left and right walls\n for (unsigned j=1; j < height-1; ++j) {\n place({0, j}, WALL);\n place({width-1, j}, WALL);\n }\n\n // create two-segment snake\n place(snake.headLocation(), SNAKE);\n place(snake.add(), SNAKE);\n\n // add a bit of food\n genFood();\n}\n</code></pre>\n\n<p>Now it is able to accept an arbitrary size window. Another subtle point here is that when a variable has a default that is always assigned when the object is constructed, assign it inline with the declaration instead. In this case the relevant declaration is:</p>\n\n<pre><code>int m_score = 0;\n</code></pre>\n\n<p>Also, if you wanted to always have a 4:3 aspect ratio, you could define <code>height</code> in terms of <code>width</code> like this:</p>\n\n<pre><code>static constexpr int height = width * 3 / 4;\n</code></pre>\n\n<h2>Consider using finer-grained helper functions</h2>\n\n<p>At the moment, the code includes a function called <code>genFood()</code> which find a random empty square and then puts food there. Since there's already a function to put an object at an arbitrary location, I'd suggest the only thing missing is a function to find a random empty square. I'd write it like this:</p>\n\n<pre><code>Coord Board::randomEmpty() const {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_int_distribution<unsigned> disX(1, width - 2);\n static std::uniform_int_distribution<unsigned> disY(1, height - 2);\n Coord coord{disX(gen),disY(gen)};\n\n while (!isEmpty(coord)) {\n coord = {disX(gen),disY(gen)};\n }\n return coord;\n}\n</code></pre>\n\n<p>Then where the code currentl uses <code>genFood</code>, one would write this:</p>\n\n<pre><code>place(randomEmpty(), Food);\n</code></pre>\n\n<p>I'd suggest that using <code>randomEmpty()</code> to initialize the snake's location might also be good as long as the direction was chosen such as to not cause the player to immediately crash into a wall! Also note here that the maximums are <code>width - 2</code> and <code>height - 2</code> and not <code>width - 1</code> and <code>height - 1</code> which are the locations of walls and thus not actually candidate locations for the food.</p>\n\n<h2>Use helper functions to simplify code</h2>\n\n<p>Now that there are some helper functions in the code, such as <code>Board::at()</code>, I'd suggest that using them would make the code simpler and easier to read and understand. Here's a way to rewrite the <code>app::drawWindow()</code> function:</p>\n\n<pre><code>void Game::app::drawWindow() {\n for (unsigned i = 0, h = board.height; i < h; ++i) {\n for (unsigned j = 0, w = board.width; j < w; ++j) {\n Coord here{j, i};\n sf::RectangleShape rect;\n rect.setSize({ common_divisor, common_divisor });\n rect.setPosition({ common_divisor * j, common_divisor * i });\n switch(board.at(here)) {\n case Board::WALL:\n window.draw(rect);\n break;\n case Board::SNAKE:\n rect.setFillColor(sf::Color::Green);\n window.draw(rect);\n break;\n case Board::FOOD: \n rect.setFillColor(sf::Color::Red);\n window.draw(rect);\n }\n }\n }\n // Draws the game score\n sf::Text text;\n text.setFont(calibri);\n text.setCharacterSize(common_divisor);\n text.setPosition({ 0.0f, 0.0f });\n text.setString(\"Score: \" + std::to_string(board.score()));\n text.setFillColor(sf::Color::Black);\n window.draw(text);\n}\n</code></pre>\n\n<p>This requires that both <code>Board::at()</code> and the <code>enum</code> are made <code>public</code> instead of <code>private</code> but it makes the code much easier to read and understand. It also eliminates the need for the <code>operator[]</code>. This version also scales the score string so that it is always the same size as the wall.</p>\n\n<h2>Consider more fully using SFML</h2>\n\n<p>SFML includes a number of virtual base objects that make things simpler if you use them. For instance, you could derive <code>app</code> from <a href=\"https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Drawable.php\" rel=\"noreferrer\"><code>sf::Drawable</code></a> and change from <code>drawWindow()</code> to this instead:</p>\n\n<pre><code>void draw(sf::RenderTarget& target, sf::RenderStates states) const override;\n</code></pre>\n\n<p>Then within <code>updateWindow()</code> it would look like this:</p>\n\n<pre><code>void Game::app::updateWindow() {\n window.clear(sf::Color::Black);\n window.draw(*this);\n window.display();\n}\n</code></pre>\n\n<h2>Make sure you have all required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string</code> but doesn't <code>#include <string></code>. Also, carefully consider which <code>#include</code>s are part of the interface (and belong in the <code>.h</code> file) and which are part of the implementation and therefore belong in the <code>.cpp</code> file.</p>\n\n<h2>Don't use unnecessary <code>#include</code>s</h2>\n\n<p>This is a complementary suggestion to the one above. The code has <code>#include \"Snake.h\"</code> in <code>app.h</code> but nothing from that include file is actually needed in that code. For that reason, that <code>#include</code> should be eliminated. Also <code>Snake.h</code> includes <code>SFML/Graphics.hpp</code> but also makes no use of it.</p>\n\n<h2>Don't store variables that aren't needed</h2>\n\n<p>The <code>winWidth</code> and <code>winHeight</code> variables are not really needed within the class. Instead, use the passed values within the <code>app</code> constructor and don't bother saving them.</p>\n\n<h2>Reconsider the class interface</h2>\n\n<p>The <code>Board</code> class knows almost nothing about SFML and that's pretty good design because it means that only the <code>app</code> class needs to deal with SFML. But it's not quite perfect. The <code>update</code> function is passed an <code>sf::RenderWindow</code>. I'd suggest that a better way to do this is to eliminate the parameter and instead pass a <code>bool</code> back that is <code>true</code> if the user has crashed.</p>\n\n<h2>Eliminate redundant data</h2>\n\n<p>Each <code>Snake_segment</code> contains both the current and previous coordinates. However, only the current position and direction are really needed. The head of the snake needs the direction, but all subsequent nodes only need to update their current position to the previous segment's current position. The only slightly tricky part is to keep track of where to add a tail piece, but I'm sure that you will be able to see how to do this with a bit of thought.</p>\n\n<h2>Clean up as the program ends</h2>\n\n<p>Almost everything is automatically cleaned up at the end of the program except that there may be extra keystrokes in the input buffer. It would be nice to empty those out before the program leaves so they don't show up on the command line after the game is over.</p>\n\n<h2>Tighten up the interface</h2>\n\n<p>The <code>Board::place</code> routine takes a <code>Coord</code> and an <code>int item</code> as parameters. It would be a wee bit more correct and also aid the reader of the code if it took a <code>Tile item</code> as the second parameter instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:37:31.523",
"Id": "220376",
"ParentId": "220360",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T16:25:56.483",
"Id": "220360",
"Score": "7",
"Tags": [
"c++",
"beginner",
"snake-game",
"sfml"
],
"Title": "Improved snake game in SFML (C++)"
} | 220360 |
<p>I read on SO and other pages that I should avoid JavascriptResult, I do not realy know why, but now I use JsonResult, because it is more common.</p>
<p>Here is my Ajax in the cshtml:</p>
<pre><code> $.ajax({
type: "POST",
url: "@Url.Action("AddFolder")",
data: {
id: currentFolderObject.id,
folderId: _childFolderId,
newFolderName: data.text,
parent: _parentsChildId
},
success: function (serverData) {
if (!serverData.message === undefined) {
if (!serverData.success) {
alert(serverData.message);
}
}
else {
SetFolderModel(serverData.id, serverData.folderId, serverData.newFolderName, false, serverData.parent, "");
if (!serverData.parent.match("_")) {
FolderProperties(node, serverData.node);
}
else {
$('#foldertree').jstree(true).refresh();
}
}
},
})
</code></pre>
<p>So with that Ajax I am calling my AddFolder in my Controller. I think I am doing it rly complicated. On client side I have to use <code>jstree</code> which has a specific structure ( <a href="https://www.jstree.com/docs/json/" rel="nofollow noreferrer">https://www.jstree.com/docs/json/</a> ). And that is why I am posting here.</p>
<pre><code> [HttpPost]
public JsonResult AddFolder(int id, string folderId, string newFolderName, string parent)
{
bool publish;
int mrNumber = 0;
int parentFolder = Convert.ToInt32(GetFolderId(id).Split('_')[0]);
int lastPeriod = GetLastPeriod();
string mrDate = Helper.ConvertToIsoDate(DateTime.Now.ToString().Split(' ')[0]);
if (lastPeriod == -1)
throw new Exception(ErrorMessages.PeriodNotFound);
if (parent == "#")
{
publish = true;
try
{
folderId = (_ministerratRepository.GetLastMainFolderId() + 1).ToString();
}
catch (Exception ex)
{
Logging.LogToFile(ex, (int?)Helper.LogLevel.Error);
return Json(new { success = false, message = ErrorMessages.CountFolderNotPossible }, JsonRequestBehavior.AllowGet);
}
}
else
{
publish = false;
if (parent.Contains("_"))
mrNumber = GetLastMrNumber(lastPeriod, folderId);
else
mrNumber = GetLastMrNumber(lastPeriod, folderId) + 1;
int folderIdIndex = 0;
if (folderId.Count(x => x == '_') == 1)
{
folderIdIndex = GetLastFolderIdOfMinisterrat(folderId, parentFolder);
if (Convert.ToInt32(folderId.Split('_')[1]) <= folderIdIndex)
folderId = parentFolder + "_" + Convert.ToInt32(folderIdIndex + 1);
}
else
{
folderIdIndex = GetLastFolderIdOfMinisterrat(folderId, parentFolder);
if (Convert.ToInt32(folderId.Split('_')[2]) <= folderIdIndex)
folderId = parent + "_" + Convert.ToInt32(folderIdIndex + 1);
}
}
if (mrNumber < 0)
throw new Exception(ErrorMessages.MrNumberNotFound);
try
{
id = _ministerratRepository.AddFolder(folderId, parent, lastPeriod, mrNumber, newFolderName, publish, mrDate);
if (id == -1)
throw new Exception(ErrorMessages.NoIdFound);
}
catch (NpgsqlException ex)
{
NpgsqlError(ex);
}
catch (Exception ex)
{
Logging.LogToFile(ex, (int?)Helper.LogLevel.Error);
return Json(new { success = false, message = ErrorMessages.AddFolderNotPossible }, JsonRequestBehavior.AllowGet);
}
return Json(new { id, folderId, newFolderName, parent });
}
</code></pre>
<p>Inside this <code>AddFolder</code> there are some other methods, they are basically returning integers from a DB query. I need <code>folderId</code> and <code>parent</code> to add the folder to the right layer. root (parent) is for example 26, child is 26_1, subchild is 26_1_1. I check that with the underscore.</p>
<p>For me it is looking very long to achieve the main goal to add a folder and I am not sure if i can achiev this easier because in my opinion this method is realy long in comparison to just Add a folder.</p>
<p>Furthermore I would like to know if my naming is correct (parameters, classes, methods) I am using here.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T17:34:47.577",
"Id": "220364",
"Score": "1",
"Tags": [
"c#",
"javascript",
"asp.net-mvc"
],
"Title": "Add a folder with jstree"
} | 220364 |
<p>It has been a <strong>royal pain</strong> that MSForm controls are missing simple events such as <code>MouseOver</code> and <code>Blur</code>, and I find myself often having a complex system of <code>MouseMove</code> events to achieve these for hover effects and other stylings.</p>
<p>To solve this issue I've created two class modules <code>EventListenerEmitter</code> and <code>EventListenerItem</code>.</p>
<h1>Listening for the events</h1>
<p>The UserForm stores the <code>EventListnerEmitter</code> using <code>WithEvents</code> so that it can then listen for raised events. The UserForm also has to pass itself as a parameter into a method named <code>AddEventListnerAll </code>, that is where the controls and form are stored.</p>
<pre class="lang-vb prettyprint-override"><code>Private WithEvents Emitter As EventListnerEmitter
Private Sub UserForm_Activate()
Set Emitter = New EventListnerEmitter
Emitter.AddEventListnerAll Me
End Sub
</code></pre>
<p>You can listen for all events in one event handler <code>EmittedEvent</code> (see the example below).</p>
<pre class="lang-vb prettyprint-override"><code>Private Sub Emitter_EmittedEvent(Control As Object, ByVal EventName As String, ByRef EventParameters As Scripting.Dictionary)
'Select statements are really handy working with these events
Select Case True
'Change color when mouseover, for a fun hover effect :)
Case EventName = "MouseOver" And TypeName(Control) = "CommandButton"
Control.BackColor = 9029664
'Don't forget to change it back!
Case EventName = "MouseOut" And TypeName(Control) = "CommandButton"
Control.BackColor = 8435998
End Select
End Sub
</code></pre>
<p>You can also listen just to specific events as well.</p>
<pre class="lang-vb prettyprint-override"><code>Private Sub Emitter_Focus(Control As Object)
'CHANGE BORDER COLOR FOR TEXTBOX TO A LIGHT BLUE
If TypeName(Control) = "TextBox" Then
Control.BorderColor = 16034051
End If
End Sub
Private Sub Emitter_Blur(Control As Object)
'CHANGE BORDER COLOR BACK TO A LIGHT GREY
If TypeName(Control) = "TextBox" Then
Control.BorderColor = 12434877
End If
End Sub
</code></pre>
<hr />
<h1>EventListenerEmitter</h1>
<p>This is the main entry point, and its purpose is to create and hold an array of the <code>EventListenerItems</code> and to be the mediator between the Userform and the <code>EventListenerItems</code>.</p>
<p>The Userform and each of its controls are passed through the function <code>AddEventListner</code> which are then stored in the array <code>EventList() As New EventListnerItem</code>. This invokes a method in <code>EventListnerItem</code> also named <code>AddEventListner</code> (this step is to have a <code>WithEvents</code> on that specific control).</p>
<p>Here is the code for <code>EventListnerEmitter</code>(minus a helper function <code>IsArrayEmpty</code>).</p>
<pre class="lang-vb prettyprint-override"><code>'ARRAY OF ALL THE DIFFERENT EVENT ListenerS FOR EVERY USERFORM CONTROL +FORM ITSELF
Private EventList() As New EventListenerItem
'ALL CURRENT POSSIBLE EVENTS THAT CAN BE EMITTED. NOTE, EMITTEDEVENT IS SENT FOR ALL!
Public Event EmittedEvent(ByRef Control As Object, ByVal EventName As String, ByRef EventParameters As Scripting.Dictionary)
Public Event Click(ByRef Control As Object)
Public Event DblClick(ByRef Control As Object, ByRef Cancel As MSForms.ReturnBoolean)
Public Event KeyUp(ByRef Control As Object, ByRef KeyCode As MSForms.ReturnInteger, ByRef Shift As Integer)
Public Event KeyDown(ByRef Control As Object, ByRef KeyCode As MSForms.ReturnInteger, ByRef Shift As Integer)
Public Event MouseOver(ByRef Control As Object)
Public Event MouseOut(ByRef Control As Object)
Public Event MouseMove(ByRef Control As Object, ByRef Shift As Integer, ByRef X As Single, ByRef Y As Single)
Public Event Focus(ByRef Control As Object)
Public Event Blur(ByRef Control As Object)
Public Event Change(ByRef Control As Object)
'***********************************************************************************
' PUBLIC METHODS
'***********************************************************************************
'CALLED BY EVENTLISTENERCOLLECTION CLASS - MAIN ENTRYWAY OF EMITTING ALL EVENTS
Public Sub EmitEvent(ByRef Control As Object, ByVal EventName As String, ByRef EventParameters As Scripting.Dictionary)
'EVENT RAISED FOR ALL EVENTS. THIS IS A WAY FOR THE USER TO COLLECT FROM A SINGLE LOCATION.
RaiseEvent EmittedEvent(Control, EventName, EventParameters)
'SPECIFIC EVENTS PER OBJECT-TYPE
Select Case EventName
Case "Click"
RaiseEvent Click(Control)
Case "DblClick"
RaiseEvent DblClick(Control, EventParameters("Cancel"))
Case "KeyUp"
RaiseEvent KeyUp(Control, EventParameters("KeyCode"), EventParameters("Shift"))
Case "KeyDown"
RaiseEvent KeyDown(Control, EventParameters("KeyCode"), EventParameters("Shift"))
Case "MouseOver"
RaiseEvent MouseOver(Control)
Case "MouseOut"
RaiseEvent MouseOut(Control)
Case "Focus"
RaiseEvent Focus(Control)
Case "Blur"
RaiseEvent Blur(Control)
Case "MouseMove"
RaiseEvent MouseMove(Control, EventParameters("Shift"), EventParameters("X"), EventParameters("Y"))
End Select
End Sub
'MUST CALL THIS IF YOU WANT TO programmatically SET CONTROL! OTHERWISE, EVENT'S WILL BE OFF!
Public Sub SetFocusToControl(ByRef Control As Object)
'If the user was to set focus through VBA then this code will fall apart considering
'it is unaware of that event occurring.
If Not Control Is Nothing Then
Control.setFocus
EmitEvent Control, "Focus", Nothing
End If
End Sub
'ADD EVENT ListenerS ON SPECIFIC CONTROLS - ALSO CALLED BY AddEventListenerAll
Public Sub AddEventListener(ByRef Control As Object)
'Events are stored in a private EventListenerItem array
If IsArrayEmpty(EventList) Then
ReDim EventList(0 To 0)
Else
ReDim Preserve EventList(0 To UBound(EventList) + 1)
End If
'CALL AddEventListener IN EventListenerItem. THIS IS KEPT IN
EventList(UBound(EventList)).AddEventListener Control, Me
End Sub
'ADD EVENT Listener TO ALL CONTROLS INCLUDING THE FORM
Public Sub AddEventListenerAll(ByRef Form As Object)
AddEventListener Form
Dim Ctrl As MSForms.Control
For Each Ctrl In Form.Controls
AddEventListener Ctrl
Next Ctrl
End Sub
</code></pre>
<hr />
<h1>EventListenerItem</h1>
<p>This class contains one control only, and stores that control under the appropriate <code>WithEvents</code> variable.</p>
<p>Additionally, it stores a reference to the emitter class <code>Private WithEvents pEmitter As EventListenerEmitter</code>.</p>
<p>As this control has events it will call <code>EmitEvent</code> from the <code>EventListenerEmitter</code> class, where it will then raise the appropriate events.</p>
<p><strong>All controls will be listening for these events</strong> to then store whether or not it is the current hovered or focused control. This is how I'm able to then raise my custom events <code>hover</code> and <code>blur</code>.</p>
<p>I've broken this class up into sections for readability.</p>
<h3>Private Variables</h3>
<pre class="lang-vb prettyprint-override"><code>'SET FROM AddEventListener - NEEDED TO EMIT EVENT BACK TO IT.
Private WithEvents pEmitter As EventListenerEmitter
'CONTROLS THAT HAVE THE EVENTS CURRENTLY
Private WithEvents Form As MSForms.UserForm
Private WithEvents Txt As MSForms.Textbox
Private WithEvents Lbl As MSForms.Label
Private WithEvents Btn As MSForms.CommandButton
Private WithEvents Cmb As MSForms.ComboBox
Private WithEvents Frm As MSForms.Frame
'PROPERTIES OF SPECIFIC CONTROL
Private pControl As Object 'Used for comparison
Private IsHoveredControl As Boolean
Private IsFocusedControl As Boolean
</code></pre>
<h3>Public Functions</h3>
<p>Only one public function. It's called from <code>EventListenerEmitter</code> class.</p>
<pre class="lang-vb prettyprint-override"><code>'ONLY PUBLIC METHOD. CALLED FROM EVENTListener CLASS MODULE
Public Sub AddEventListener(ByRef ControlOrForm As Object, ByRef Emitter As EventListenerEmitter)
'CAPTURE THE EMITTER CLASS. WILL USE THIS TO EMIT EVENTS FROM EACH CONTROL
Set pEmitter = Emitter
'USED TO COMPARE CHECK IF IT IS THE CONTROL TRIGGERING THE EVENT
Set pControl = ControlOrForm
'SET CONTROL(OR FORM) BASED ON IT'S TYPE
Select Case TypeName(ControlOrForm)
Case "CommandButton"
Set Btn = ControlOrForm
Case "ComboBox"
Set Cmb = ControlOrForm
Case "Frame"
Set Frm = ControlOrForm
Case "Label"
Set Lbl = ControlOrForm
Case "TextBox"
Set Txt = ControlOrForm
Case Else
If IsUserform(ControlOrForm) Then
Set Form = ControlOrForm
End If
End Select
End Sub
</code></pre>
<h3>Private helper functions</h3>
<pre class="lang-vb prettyprint-override"><code>'CALLED ON MOUSEMOVE EVENT, THIS IS A WAY OF CREATING A MOUSEOVER AND MOUSEOUT EVENT
Private Sub CheckIfHoveredControl()
If Not IsHoveredControl Then
IsHoveredControl = True
pEmitter.EmitEvent pControl, "MouseOver", Dict()
End If
End Sub
'CALLED ON MOUSEMOVE EVENT, THIS IS A WAY OF CREATING A MOUSEOVER AND MOUSEOUT EVENT
Private Sub CheckIfFocusedControl()
If Not IsFocusedControl Then
If TypeName(pControl) = "Frame" Then
pEmitter.SetFocusToControl pControl.ActiveControl
Else
IsFocusedControl = True
pEmitter.EmitEvent pControl, "Focus", Dict()
End If
End If
End Sub
'CHECK TO SEE IF OBJ IS A USERFORM
Private Function IsUserform(ByRef Obj As Object) As Boolean
If TypeOf Obj Is MSForms.UserForm Then
IsUserform = True
End If
End Function
'SIMPLE DICTIONARY FACTORY - USED TO PASS EVENT PARAMETERS BACK TO EMITTER
Private Function Dict(ParamArray KeyValue() As Variant) As Scripting.Dictionary
'CHECK IF THERE IS EVEN PARAMETERS
If Not ArrayCount(KeyValue) Mod 2 = 0 Then
Debug.Print "Function Dict() requires an even amount of key value arguments." _
& " Only provided " & ArrayCount(KeyValue)
Exit Function
End If
Set Dict = New Scripting.Dictionary
Dim Index As Long
For Index = LBound(KeyValue) To UBound(KeyValue) Step 2
Dict.Add KeyValue(Index), KeyValue(Index + 1)
Next Index
End Function
'USED WITH Dict To SEE IF THERE ARE AN EVEN AMOUNT OF PARAMETERS
Private Function ArrayCount(ByVal SourceArray As Variant) As Long
ArrayCount = UBound(SourceArray) - LBound(SourceArray) + 1
End Function
</code></pre>
<h3>Event Listener</h3>
<p>This is so that each control can check if it is the current hovered or focused control and store that information. This is used to then raise custom events.</p>
<pre class="lang-vb prettyprint-override"><code>' ONCE AN EVENT HAS EMMITED, EACH EVENTListenerITEM WILL LISTEN FOR THAT EVENT
Private Sub pEmitter_EmittedEvent(ByRef Control As Object, ByVal EventName As String, ByRef EventParameters As Scripting.Dictionary)
'CREATE A MOUSEOVER MOUSEOUT EVENTS
Select Case EventName
Case "MouseOver"
If pControl.Name <> Control.Name And IsHoveredControl Then
IsHoveredControl = False
pEmitter.EmitEvent pControl, "MouseOut", Dict()
End If
Case "Focus"
If pControl.Name <> Control.Name And IsFocusedControl Then
IsFocusedControl = False
pEmitter.EmitEvent pControl, "Blur", Dict()
ElseIf pControl.Name = Control.Name And IsFocusedControl = False Then
IsFocusedControl = True
End If
End Select
End Sub
</code></pre>
<h3>Events Per control</h3>
<pre class="lang-vb prettyprint-override"><code>'------------------------------------------------------------------------
' USERFORM
'------------------------------------------------------------------------
Private Sub Form_Click()
pEmitter.EmitEvent pControl, "Click", Dict()
End Sub
Private Sub Form_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
pEmitter.EmitEvent pControl, "DblClick", Dict("Cancel", Cancel)
End Sub
Private Sub Form_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfHoveredControl
pEmitter.EmitEvent pControl, "MouseMove", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Form_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
pEmitter.EmitEvent pControl, "MouseDown", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Form_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
pEmitter.EmitEvent pControl, "MouseUp", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
'------------------------------------------------------------------------
' COMMAND BUTTON
'------------------------------------------------------------------------
Private Sub Btn_Click()
pEmitter.EmitEvent pControl, "Click", Dict()
End Sub
Private Sub Btn_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
pEmitter.EmitEvent pControl, "DblClick", Dict("Cancel", Cancel)
End Sub
Private Sub Btn_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfHoveredControl
pEmitter.EmitEvent pControl, "MouseMove", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Btn_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfFocusedControl
pEmitter.EmitEvent pControl, "MouseUp", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Btn_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
pEmitter.EmitEvent pControl, "MouseDown", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Btn_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
CheckIfFocusedControl
pEmitter.EmitEvent pControl, "KeyUp", Dict("KeyCode", KeyCode, "Shift", Shift)
End Sub
Private Sub Btn_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
pEmitter.EmitEvent pControl, "KeyDown", Dict("KeyCode", KeyCode, "Shift", Shift)
End Sub
'------------------------------------------------------------------------
' LABEL
'------------------------------------------------------------------------
Private Sub Lbl_Click()
pEmitter.EmitEvent pControl, "Click", Dict()
End Sub
Private Sub Lbl_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
pEmitter.EmitEvent pControl, "DblClick", Dict("Cancel", Cancel)
End Sub
Private Sub Lbl_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfHoveredControl
pEmitter.EmitEvent pControl, "MouseMove", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub lbl_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
pEmitter.EmitEvent pControl, "MouseDown", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub lbl_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
pEmitter.EmitEvent pControl, "MouseUp", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
'------------------------------------------------------------------------
' Frame
'------------------------------------------------------------------------
Private Sub Frm_Click()
pEmitter.EmitEvent pControl, "Click", Dict()
End Sub
Private Sub Frm_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
pEmitter.EmitEvent pControl, "DblClick", Dict("Cancel", Cancel)
End Sub
Private Sub Frm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfHoveredControl
pEmitter.EmitEvent pControl, "MouseMove", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Frm_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfFocusedControl 'FRAME DOESN'T TAKE FOCUS BUT ACTIVE CONTROL IN FRAME DOES
pEmitter.EmitEvent pControl, "MouseDown", Dict()
End Sub
Private Sub Frm_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
pEmitter.EmitEvent pControl, "MouseUp", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
'------------------------------------------------------------------------
' Textbox
'------------------------------------------------------------------------
Private Sub Txt_Click()
pEmitter.EmitEvent pControl, "Click", Dict()
End Sub
Private Sub Txt_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
pEmitter.EmitEvent pControl, "DblClick", Dict("Cancel", Cancel)
End Sub
Private Sub Txt_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfHoveredControl
pEmitter.EmitEvent pControl, "MouseMove", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Txt_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
CheckIfFocusedControl
pEmitter.EmitEvent pControl, "MouseUp", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Txt_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
pEmitter.EmitEvent pControl, "MouseDown", Dict("Button", Button, "Shift", Shift, "X", X, "Y", Y)
End Sub
Private Sub Txt_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
CheckIfFocusedControl
pEmitter.EmitEvent pControl, "KeyUp", Dict("KeyCode", KeyCode, "Shift", Shift)
End Sub
Private Sub Txt_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
pEmitter.EmitEvent pControl, "KeyDown", Dict("KeyCode", KeyCode, "Shift", Shift)
End Sub
</code></pre>
<hr />
<p>This has worked for my overall needs to this point and I like how simple it is to use; however, I feel like there are better design patterns out there than what I currently have that are more flexible for change.</p>
<p>At this point, I only have a small list of events that I'm emitting and already it can be quite a bit of code to maintain. I would love any suggestion as I'm always looking to improve on best practices and writing clean code.</p>
<p><a href="https://github.com/todar/VBA-Userform-EventListener" rel="noreferrer">Here</a> is my Github Repository in case you need the full code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:00:35.933",
"Id": "425809",
"Score": "0",
"body": "Now that's a very refreshing post to review! Good job, and welcome to CR!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:05:05.687",
"Id": "425811",
"Score": "0",
"body": "Thank you, I was worried the post got too verbose. Appreciate the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:06:39.287",
"Id": "425812",
"Score": "1",
"body": "There's a reason this site has 2x the maximum post length of Stack Overflow ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T01:49:33.467",
"Id": "426107",
"Score": "1",
"body": "I get a Type mismatch error at this line `EmitEvent Control, \"Focus\", \"\"`. You should use Nothing in place of the vbNullString but I would probably just make `EventParameters` optional."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T14:44:23.263",
"Id": "426191",
"Score": "0",
"body": "@TinMan Good catch on the error and good point on making it optional. I'll update the code above to remove the error!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T17:52:58.763",
"Id": "426216",
"Score": "0",
"body": "Updated my code on [Github](https://github.com/todar/VBA-Userform-EventListener) where I added the improvements that @MathieuGuindon suggested. I Don't think I'm supposed to update my question to reflect those changes so please correct me if I'm mistaken."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T07:18:34.590",
"Id": "426242",
"Score": "1",
"body": "@RobertTodar That's correct, you [shouldn't update](https://codereview.meta.stackexchange.com/a/1765/146810) the code in your question (ever technically - in case someone's working on a review as you edit - but generally I think it's fine if your question has had no activity yet for a couple of days). However you _can_ post a separate follow-up question with updated code (see the linked discussion). NB is there something specific to your original code which you want feedback on & Matt's answer didn't cover? If so then consider making a note of that in the bounty description (or a new question)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T14:49:35.513",
"Id": "426315",
"Score": "1",
"body": "@Greedo looks like I can't [update the bounty notes](https://meta.stackoverflow.com/questions/253267/how-can-i-edit-my-bounty) to add even more clarification. Essentially, I'm looking for a **full code review** that can tell me if my overall design can be improved before I start adding a bunch of controls and events to it. Are there better ways for abstractions and/or encapsulation? Is this a candidate for interfaces? I'll even take feedback if my code is designed well. The main goal is to learn and grow in how I approach problems like this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T16:17:05.167",
"Id": "426327",
"Score": "0",
"body": "@RobertTodar Sorry, totally missed the bounty description. FWIW if you had left no description/ wanted to change it, you could have flagged the question for moderator attention, had the bounty cancelled (restoring your lost rep) and re-added one with a new description. Better than cluttering the comments. However I think your current description is enough to go on for most people."
}
] | [
{
"body": "<p>No time for a full-blown review, but glancing over the code, a few points stick out:</p>\n\n<hr>\n\n<h3>Enthusiastic Abstractions</h3>\n\n<p>In a few places, you extracted a trivial one-liner function that is only used in a single place. IMO that's the wrong abstraction to use - for example:</p>\n\n<pre><code>Private Function IsUserform(ByRef Obj As Object) As Boolean\n\n If TypeOf Obj Is MSForms.UserForm Then\n IsUserform = True\n End If\n\nEnd Function\n</code></pre>\n\n<p>That could have been written as <code>IsUserForm = TypeOf obj Is MSForms.UserForm</code>, an expression that is perfectly fine to have inline IMO:</p>\n\n<pre><code> Case Else\n\n If TypeOf ControlOrForm Is MSForms.UserForm Then\n Set Form = ControlOrForm\n End If\n</code></pre>\n\n<p>That <code>If</code> block should really have an <code>Else</code> clause that throws an error to tell the calling code \"I'm afraid I can't let you do that\" or something. It's currently silently failing, and that's never good.</p>\n\n<p><code>ArrayCount</code> is also probably better off as a local variable if it's only used in one place - otherwise it should be in some utilities module, and I'd call it <code>ArrayLength</code>, more in-line with standard terminology.</p>\n\n<pre><code>Private Function Dict(ParamArray KeyValue() As Variant) As Scripting.Dictionary\n\n 'CHECK IF THERE IS EVEN PARAMETERS\n Dim arrayCount As Long\n arrayCount = UBound(KeyValue) - LBound(KeyValue) + 1\n\n If Not arrayCount Mod 2 = 0 Then\n Debug.Print \"Function Dict() requires an even amount of key value arguments.\" _\n & \" Only provided \" & arrayCount\n Exit Function\n End If\n</code></pre>\n\n<p>There's no need to invoke the function twice, even less so just for a <code>Debug.Print</code> statement. That said, this should be a serious bug, and I would expect it to throw a run-time error, not just output to the <code>Debug</code> pane.</p>\n\n<pre><code> If arrayCount Mod 2 <> 0 Then\n Err.Raise 5, TypeName(Me), \"Invalid parameters: expecting key/value pairs, but received an odd number of arguments.\"\n End If\n</code></pre>\n\n<p>I'd spell it <code>ToDictionary</code> though, and the <code>KeyValue()</code> argument would probably be clearer as <code>keyValuePairs()</code> - I like my arrays and collections pluralized.</p>\n\n<hr>\n\n<h3>Stringly-Typed Events</h3>\n\n<p>The one single thing that's making the solution much flakier than it needs to be, is the fact that the event names are all hard-coded string literals, everywhere.</p>\n\n<p>What's missing is a <code>Public Enum</code>, somewhere:</p>\n\n<pre><code>Public Enum EmittedEvent\n Click\n DoubleClick\n MouseMove\n MouseOut\n MouseOver\n MouseDown\n MouseUp\n KeyUp\n KeyDown\n Focus\n Blur\nEnd Enum\n</code></pre>\n\n<p>Then you get auto-completion at the call sites, <code>Option Explicit</code> is protecting you from a typo, and you can refactor/rename them at will without breaking everything:</p>\n\n<pre><code>Public Sub EmitEvent(ByRef Control As Object, ByVal EventType As EmittedEvent, ByRef EventParameters As Scripting.Dictionary)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:20:27.163",
"Id": "425823",
"Score": "0",
"body": "I really like `KeyValuePairs()`, that stands out a bunch more to me. Where would you store the `Public Enum`? I originally started off in that direction, and something felt wrong having it declared globally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:40:20.843",
"Id": "425824",
"Score": "0",
"body": "I'd put the enum in the emitter class I think."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:00:32.590",
"Id": "220382",
"ParentId": "220370",
"Score": "6"
}
},
{
"body": "<h2>Scripting.Dictionary</h2>\n\n<p>The code is not using any of the Dictionary's special features. Replacing the Scripting.Dictionaries with VBA.Collections will eliminate the external reference, make the class easier to distribute and MAC friendly. </p>\n\n<h2>Synergies</h2>\n\n<p>Most of the pieces in place but they just don't work together as smoothly as they could. </p>\n\n<p>Take a look at this code snippet from the TestFormEvents userform. </p>\n\n<pre><code>Private Sub Emitter_Blur(Control As Object)\n\n RendorEventLabel Control, Blur\n\n 'CHANGE BORDER COLOR BACK TO A LIGHT GREY\n If TypeName(Control) = \"TextBox\" Then\n Control.BorderColor = 12434877\n Control.BorderStyle = fmBorderStyleNone\n Control.BorderStyle = fmBorderStyleSingle\n End If\n\nEnd Sub\n</code></pre>\n\n<p>Pretty straight forward but it just handles a textbox. What if you wanted to add effects for all 6 of the supported controls (UserForm, Textbox, Label, CommandButton, ComboBox, and Frame)? A Select Case would help. Of course, you would have to have to make sure that each of the Cases is cased right, <strong>no IntelliSense for strings</strong>. </p>\n\n<pre><code>Private Sub Emitter_Blur(Control As Object)\n\n RendorEventLabel Control, Focus\n\n 'CHANGE BORDER COLOR FOR TEXTBOX TO A LIGHT BLUE\n Select Case TypeName(Control)\n Case \"UserForm\"\n\n Case \"TextBox\"\n Control.BorderColor = 16034051\n Control.BorderStyle = fmBorderStyleNone\n Control.BorderStyle = fmBorderStyleSingle\n Case \"Label\"\n\n Case \"CommandButton\"\n\n Case \"ComboBox\"\n\n Case \"Frame\"\n\n End Select\n\nEnd Sub\n</code></pre>\n\n<p>This looks pretty good but should I have added `Case \"MultiPage\"? No, MultiPage is not supported <strong>There is no way to know what controls are supported without examining the source code.</strong></p>\n\n<p>Now say that we wanted to do something a little fancier like change CommandButton's scrollbar property. Oh, they don't have a scrollbar...ugh no IntelliSense...the Control is typed as an Object. No problem really, we can just create a <strong>separate variable for each supported control</strong>. Yuck!</p>\n\n<h2>Tweaks</h2>\n\n<p>The first thing that I would do is add another enumeration for supported controls.</p>\n\n<pre><code>Public Enum EmitterControls\n ecUserForm\n ecTextbox\n ecLabel\n ecCommandButton\n ecComboBox\n ecFrame\nEnd Enum\n</code></pre>\n\n<p>But how to implement the enumeration? We could bubble it up as a parameter. That would work but I think that there is a better way. </p>\n\n<p>I would make these changes to the EventListenerItem class\n - Add a ControlType Property \n - Change the scope of the MSForms variables to Public\n - Rename the MSForms to match there Type (CommandButton As MSForms.CommandButton)\n - Retype the Control from Object to EventListenerItem \n - Pass the instance of the EventListenerItem as Control</p>\n\n<p>Here is how the code snippet above would look after the changes:</p>\n\n<pre><code>Private Sub Emitter_Blur(Control As EventListenerItem)\n\n RendorEventLabel Control, Focus\n\n 'CHANGE BORDER COLOR FOR TEXTBOX TO A LIGHT BLUE\n Select Case Control.ControlType\n Case EmitterControls.ecUserForm\n\n Case EmitterControls.ecTextbox\n Control.TextBox.BorderColor = 16034051\n Control.TextBox.BorderStyle = fmBorderStyleNone\n Control.TextBox.BorderStyle = fmBorderStyleSingle\n Case EmitterControls.ecLabel\n\n Case EmitterControls.ecCommandButton\n\n Case EmitterControls.ecComboBox\n\n Case EmitterControls.ecFrame\n\n End Select\n\nEnd Sub\n</code></pre>\n\n<p>The big pay off is having IntelliSense available for writing the Select Case and accessing the MsForms control properties.</p>\n\n<p><a href=\"https://i.stack.imgur.com/nLeTG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nLeTG.png\" alt=\"Enumeration IntelliSense\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/tCPsq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tCPsq.png\" alt=\"EventListenerItem MsForms Control IntelliSense\"></a></p>\n\n<p>This setup would also allow us to add an <code>ActiveEventListenerItem</code> property to the EventListenerEmitter class, which just might come in handy.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T06:38:53.830",
"Id": "220702",
"ParentId": "220370",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T19:24:09.793",
"Id": "220370",
"Score": "10",
"Tags": [
"design-patterns",
"vba"
],
"Title": "Userform Event Listener and Emitter"
} | 220370 |
<p>I'm practicing for my Technical Interview and I'm worried my code does not meet the bar. What can I do to improve this answer?</p>
<p>Here is the question: <a href="https://www.careercup.com/question?id=5739126414901248" rel="nofollow noreferrer">https://www.careercup.com/question?id=5739126414901248</a></p>
<p>Given</p>
<p><code>colors = ["red", "blue", "green", "yellow"];</code> and a string</p>
<p><code>str = "Lorem ipsum dolor sit amet";</code></p>
<p>write a function that prints each letter of the string in different colors. ex. <code>L</code> is red, <code>o</code> is blue, <code>r</code> is green, <code>e</code> is yellow, <code>m</code> is red, after the space, <code>i</code> should be blue.</p>
<p>My answer:</p>
<pre><code>static void TestPrintColors()
{
string[] colors = new string[4] {"red", "blue", "green", "yellow"};
string str = "Lorem ipsum dolor sit amet";
PrintColors(colors, str);
}
static void PrintColors(string[] colors, string str)
{
char log;
ConsoleColor originalColor = Console.ForegroundColor;
int colorIndex = 0;
ConsoleColor currentColor = originalColor;
for (int i = 0; i < str.Length; i++)
{
log = str[i];
if (log == ' ')
{
Console.WriteLine(log);
continue;
}
switch(colors[colorIndex])
{
case "red":
currentColor = ConsoleColor.Red;
break;
case "blue":
currentColor = ConsoleColor.Blue;
break;
case "green":
currentColor = ConsoleColor.Green;
break;
case "yellow":
currentColor = ConsoleColor.Yellow;
break;
default:
currentColor = originalColor;
break;
}
colorIndex++;
if (colorIndex >= colors.Length)
{
colorIndex = 0;
}
Console.ForegroundColor = currentColor;
Console.WriteLine(log);
}
Console.ForegroundColor = originalColor;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T22:40:04.033",
"Id": "425834",
"Score": "0",
"body": "Have you tested the code? If you have tested the code could you please provide the code that calls this function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T00:02:49.530",
"Id": "425837",
"Score": "0",
"body": "@pacmaninbw The calling function is `TestPrintColors()`. That in turn would be called from a Console Application's `Main` method."
}
] | [
{
"body": "<h3>Don't worry about performance.</h3>\n\n<p>You're writing a handful of strings to the console, and it takes milliseconds. When you start writing tens of thousands of strings, and notice it taking seconds, then you can you start to look for optimizations. Until then, the cleanliness of your code is much more important.</p>\n\n<hr>\n\n<h3>Your function is too long.</h3>\n\n<p>This is a fifty-line function. It has the responsibilities of iterating through two lists in parallel, skipping spaces, parsing color names, setting the console color, writing to console, and resetting the console color when it's all done. That's a lot! Break it up into smaller functions.</p>\n\n<hr>\n\n<h3>Switch statements are ugly.</h3>\n\n<p>I don't mean that they are never appropriate, but <code>ConsoleColor</code> is an <code>enum</code>, and it's possible to parse enums (while ignoring case sensitivity). You should replace this switch statement with a function call.</p>\n\n<hr>\n\n<h3>Don't initialize variables until you need them.</h3>\n\n<p>With few exceptions, modern languages are very good about optimizing variable allocation. Putting <code>char log = str[i]</code> inside the loop will not result in additional memory usage, and it will save me (a potential reviewer or maintenance programmer) from having to think about that character before or after the loop.</p>\n\n<hr>\n\n<h3>Other tips...</h3>\n\n<p>You say this is practice for an interview, so it could be a good place for you to show off your knowledge of C#. With a little trouble, you could leverage Regular Expressions and LINQ to save you from manually manipulating array indexes. With a little more trouble, you could leverage IDisposable to ensure the original ForegroundColor is restored when all is said and done.</p>\n\n<p>On the other hand, you could also shoot yourself in the foot attempting to do those things. If you don't honestly have in-depth knowledge about C#, it might be best just to aim for code that is as simple as possible. I think the best way to do that is to make small functions with clear names, to show you are thinking about the maintainability and reusability of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T22:04:18.903",
"Id": "425831",
"Score": "1",
"body": "Nicely said! Thank you for the great response! I would like to update my code and get feedback, what is the best way to do that? Sorry I'm, new here. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T22:18:15.850",
"Id": "425832",
"Score": "2",
"body": "Welcome to CodeReview! The usual rule is that you may make edits to your code until the first answer is posted. At this point, if you were to edit this question my answer would look silly. Please, feel free to post a follow-up question with your updated code, maybe linking back to this one for reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T14:32:33.937",
"Id": "425884",
"Score": "0",
"body": "Nice answer! Upvoted! Could you implement your comments in code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T14:47:58.370",
"Id": "425888",
"Score": "0",
"body": "Variable allocation in this case isn’t a question of optimisation. The language *requires* that the variable inside the loop only takes a single stack address, which gets reused. This is pretty much universal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T19:22:06.563",
"Id": "426368",
"Score": "1",
"body": "*practice for an interview ... it could be a good place for you to show off your knowledge of C#*. \"Practice\", fine. Especially if you write different versions as a compare and contrast exercise. But I strongly councel caution to consider situations. Wanton cleverness is detrimental to code maintenance and sometimes a job interview fail. Good OO skills are more important. And clever code makes that skill imperative as it exacerbates weak OO structure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T19:29:56.763",
"Id": "426370",
"Score": "0",
"body": "@radarbob Completely agree. For a toy app that prints colored words to a console, I probably *would not* create a `public class ColoredConsoleWriter : IDisposable` that resets to the initial color in its `Dispose()`. But I probably *would*, when discussing my solution with an interviewer, talk about the possibility of doing so. I would want to show that I know how C# handles resource cleanup, which could be important for the real code I'll write after I make it through the interview process."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:57:22.910",
"Id": "220381",
"ParentId": "220371",
"Score": "11"
}
},
{
"body": "<h2>Declaring array size</h2>\n\n<p>Since you're declaring and initializing the array in one step, you don't need to declare the array size. Omitting the array size means you can add/remove elements from the initialization without needing to worry about also changing the number in the declaration.</p>\n\n<pre><code>// before\nstring[] colors = new string[4] {\"red\", \"blue\", \"green\", \"yellow\"};\n\n\n// after\nstring[] colors = new string[] {\"red\", \"blue\", \"green\", \"yellow\"};\n</code></pre>\n\n<h2>Circular looping</h2>\n\n<p>You can make this a neat one-liner using the modulus operator (or if you want your code to be ugly, a ternary operator). It's personal preference but the modulus operator has the added benefit of allowing you to iterate backwards because it will wrap your index/iterator even if it goes negative.</p>\n\n<pre><code>// before\ncolorIndex++;\n\nif (colorIndex >= colors.Length)\n{\n colorIndex = 0;\n}\n\n\n// after\ncolorIndex = (colorIndex + 1) % colors.Length;\n</code></pre>\n\n<h2>For loop</h2>\n\n<p>You use a for loop to iterate your string, but the iterator/index variable <code>i</code> is only used to retrieve the char element from the appropriate position. Since the rest of your code isn't dependent on the numerical index value, you can just use a foreach loop. Remember to remove the declaration for the log variable if you declare it in your foreach loop.</p>\n\n<pre><code>// before\nfor (int i = 0; i < str.Length; i++)\n{\n log = str[i];\n\n\n// after\nforeach (char log in str) \n{\n</code></pre>\n\n<h2>Checking for white space</h2>\n\n<p>C#'s char primitive type has a built-in check for white space which covers more than just spacebar.</p>\n\n<pre><code>// before\nif (log == ' ')\n\n// after\nif (char.IsWhiteSpace(log))\n</code></pre>\n\n<h2>Switch statements</h2>\n\n<p>As mentioned by another answer, switch statements are ugly. But there's another reason to opt for a different solution: if you want to add more colors to your array, you will also need to remember to add more cases to the switch statement.</p>\n\n<pre><code>// before\nswitch (colors[colorIndex])\n{\n case \"red\":\n currentColor = ConsoleColor.Red;\n break;\n\n case \"blue\":\n currentColor = ConsoleColor.Blue;\n break;\n\n case \"green\":\n currentColor = ConsoleColor.Green;\n break;\n\n case \"yellow\":\n currentColor = ConsoleColor.Yellow;\n break;\n\n default:\n currentColor = originalColor;\n break;\n}\n\n// after\nif (!Enum.TryParse(colors[colorIndex], true, out currentColor))\n{\n currentColor = originalColor;\n}\n</code></pre>\n\n<hr>\n\n<p>The adjustments I pointed out result in significantly less code that is more maintainable. It is functionally the same, and flexible in that you can easily add more colors later if you wanted to by just adding them to your array initialization.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T00:19:34.483",
"Id": "220388",
"ParentId": "220371",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "220381",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T19:36:24.600",
"Id": "220371",
"Score": "10",
"Tags": [
"c#",
"performance"
],
"Title": "Prints each letter of a string in different colors"
} | 220371 |
<p>I'm working with a dictionary with 11830 keys/values, that have to loop over 13905 strings, that can have up to 50 words each. My series looks like this:</p>
<pre><code> strings
"hello foo helloo"
"bye bar byer"
</code></pre>
<p>And my dictionary like this:</p>
<pre><code>dic={'hello':'hi','bye':'byebye'}
</code></pre>
<p>So I want my final <code>Series</code> to look like this:</p>
<pre><code> strings
"hi foo helloo"
"byebye bar byer"
</code></pre>
<p>I achieved that like this:</p>
<pre><code>for k,v in dicc.items():
b=b.apply(lambda x: re.sub(r'\b'+k+r'\b',r'\b'+v+r'\b',x))
</code></pre>
<p>But it's quite slow. Is there a faster way to do it?</p>
<p>Edit: noticed splitting the string didn't solve the issue of replacing substrings that matched the dictionary.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:05:22.743",
"Id": "220373",
"Score": "2",
"Tags": [
"python",
"strings",
"pandas"
],
"Title": "Faster way to replace strings in pandas series using dictionary in Python"
} | 220373 |
<p>I have a case where I want to apply a format if a property is true or if it is not set at all. Here is what I have: </p>
<pre><code>var item = {};
item.name = "Option 1";
if (item.addTags==true || item.addTags==null) {
// user wants to add tags. if not set then default is to add tags
}
else {
// property is set and is not true. do not add tags
}
</code></pre>
<p>Is there any potential issues with doing it this way? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:46:47.293",
"Id": "425815",
"Score": "1",
"body": "If it is not set at all - does it not include `undefined`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:12:46.483",
"Id": "425821",
"Score": "1",
"body": "Why have the `else` scope at all if it's no-op?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:49:31.437",
"Id": "425825",
"Score": "0",
"body": "@MathieuGuindon good point. lol i hadn't progressed that far in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:50:28.227",
"Id": "425826",
"Score": "0",
"body": "I'd think it's a bit early to have it peer reviewed then ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:50:33.283",
"Id": "425827",
"Score": "0",
"body": "@Avanthika in JavaScript if the value is `undefined` the loose equality would catch it when using `value==null`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:53:29.593",
"Id": "425828",
"Score": "0",
"body": "@MathieuGuindon could we say your comment identifying an area of improvement in the code is the reason code review exists and that your comment should receive an upvote? Also, it there is different behavior in the actual code of each block. In the example above though, the else block is unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T21:55:14.833",
"Id": "425829",
"Score": "0",
"body": "Sure, ...still, you'd get a lot meatier feedback with a meatier piece of code ;-)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-16T20:43:09.783",
"Id": "220377",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Applying option if property is true or not set at all"
} | 220377 |
<p>I have a number of names divided into several lists. I am printing all the names which occur in more than one list, sorted by the number of occurrences.</p>
<p>What is a better/easier/more pythonic way of doing this? I feel like my solution is overly complicated.</p>
<pre><code>import numpy as np
list_1 = ['John Cleese', 'Terry Gilliam']
list_2 = ['Eric Idle', 'Terry Jones', 'Michael Palin']
list_3 = ['Graham Chapman', 'Sir Lancelot the Brave', 'Terry Jones']
list_4 = ['Arthur, King of the Britons', 'Terry Jones', 'John Cleese']
list_5 = ['Michael Palin', 'Sir Robin the Not-Quite-So-Brave-as-Sir-Lancelot']
all = sorted(np.unique(list_1+list_2+list_3+list_4+list_5))
def in_how_many(name):
result = 0
if name in list_1:
result += 1
if name in list_2:
result += 1
if name in list_3:
result += 1
if name in list_4:
result += 1
if name in list_5:
result += 1
return result
names_list = []
for name in all:
if in_how_many(name) > 1:
name_dict = {'name': name, 'value': in_how_many(name)}
names_list.append(name_dict)
for person in sorted(names_list, key=lambda k: k['value'], reverse=True):
print '\'%s\' is in %s lists' % (person['name'], person['value'])
</code></pre>
<p>This prints:</p>
<pre><code>'Terry Jones' is in 3 lists
'John Cleese' is in 2 lists
'Michael Palin' is in 2 lists
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:24:53.293",
"Id": "425883",
"Score": "0",
"body": "Your examples are very Pythonic ;-)"
}
] | [
{
"body": "<p>What you want is <a href=\"https://docs.python.org/2/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a>, and the <a href=\"https://docs.python.org/2/library/collections.html#collections.Counter.most_common\" rel=\"nofollow noreferrer\"><code>Counter.most_common</code></a> method.</p>\n\n<p>A naive implementation could be:</p>\n\n<pre><code>import collections\n\nlists = [list_1, list_2, list_3, list_4, list_5]\ncounter = collection.Counter(sum(lists))\n\nfor name, amount in counter.most_common():\n print('\\'%s\\' is in %s lists' % (name, amount))\n</code></pre>\n\n<p>This however will mean if <code>list_1</code> is <code>['a'] * 5</code> it will say <code>'a'</code> is in five lists when this isn't true. A dictionary comprehension is all that's needed for this building a dictionary from the lists, setting the value to 1. And you can take advantage of the fact <code>collection.Counter</code> has addition defined.</p>\n\n<pre><code>counter = sum(\n collection.Counter({name: 1 for name in names})\n for names in lists\n)\n</code></pre>\n\n<hr>\n\n<p>Without using <code>collections.Counter</code> I would advise you use <code>set</code>. Firstly it removes the need for using <code>np.unique</code> and emphasis the fact that <code>sorted</code> is redundant, as sets are unordered.</p>\n\n<p>It also means that making <code>all</code> is simple and reduces <code>name in list_1</code> from an <span class=\"math-container\">\\$O(n)\\$</span> operation to an <span class=\"math-container\">\\$O(1)\\$</span> operation. Leading to faster code.</p>\n\n<p>As shown earlier it's easier to work with lists, rather than a list of variable names and so <code>lists</code> is defined the same as above.</p>\n\n<pre><code>sets = [set(names) for names in lists]\nall = sum(sets)\n\n\ndef in_how_many(value, sets):\n return sum(\n value in set_\n for set_ in sets\n )\n</code></pre>\n\n<hr>\n\n<p>No matter which of the above two solutions you use you still have a couple of other problems:</p>\n\n<ul>\n<li>Don't put code in global scope, have a <code>main</code> function. This makes it harder to do bad things or mess up.</li>\n<li>You should use <code>if __name__ == '__main__'</code> to only allow the code in <code>main</code> to run if it's the 'main' file.</li>\n<li>In relation to the above two, notice that I pass <code>sets</code> to <code>in_how_many</code>. This is because you shouldn't rely on global scope as it makes reusing the same code harder to do.</li>\n<li>Modulo formatting was deprecated for a while, because it's generally worse than <code>str.format</code> and is more susceptible to errors. I suggest using <code>str.format</code> or upgrading to Python 3.7 to take advantage of f-strings.</li>\n<li>Import <code>print_function</code> form <code>__future__</code> to make <code>print</code> a function. This makes it easier to upgrade to Python 3.</li>\n</ul>\n\n<pre><code>from __future__ import print_function\nimport collections\nimport functools\nimport operator\n\n\ndef main(lists):\n counter = functools.reduce(\n operator.add,\n (\n collections.Counter(set(names))\n for names in lists\n )\n )\n\n for name, amount in counter.most_common():\n print('{name!r} is in {amount} lists'.format(name=name, amount=amount))\n # print(f'{name!r} is in {amount} lists') # Python 3.7 f-string.\n\n\nif __name__ == '__main__':\n main(...)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T11:52:19.477",
"Id": "425880",
"Score": "0",
"body": "Your second code block does not work at all. `sum` of values which do not have addition with `0` defined need a zero-element supplied as second argument to `sum`. Using an empty `collections.Counter` (mind typo in your code) would work, but the rest still doesn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T13:47:11.260",
"Id": "425965",
"Score": "0",
"body": "@Graipher You are correct, that it doesn't work. But this is because `sum` isn't the same as `reduce(add, ...)`. It seems to be something like `reduce(add, [0] + ...)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T14:05:04.937",
"Id": "425969",
"Score": "0",
"body": "Yes, something like that. But even when fixing that, I could not get it to work..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T14:08:08.163",
"Id": "425970",
"Score": "0",
"body": "@Graipher Ah, I missed an `s` above. I've verified that the above works in 2.7.16."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T01:02:27.247",
"Id": "220390",
"ParentId": "220387",
"Score": "4"
}
},
{
"body": "<p>This exercise can be solved using the tools in the Python standard library, namely the <a href=\"https://docs.python.org/3/library/collections.html\" rel=\"nofollow noreferrer\"><code>collections</code></a> module and the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"nofollow noreferrer\"><code>itertools</code></a> module.</p>\n\n<ul>\n<li>First, you want to ensure that just because a name appears twice in the same list, it is not double-counted. Use <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map</code></a> and <a href=\"https://docs.python.org/3/library/functions.html#func-set\" rel=\"nofollow noreferrer\"><code>set</code></a> for that (or a comprehension).</li>\n<li>Then you want to parse all names from all lists, use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable\" rel=\"nofollow noreferrer\"><code>itertools.chain.from_iterable</code></a> for that.</li>\n<li>Finally you need to count how often each name appeared, which you can use <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> for (just like in the <a href=\"https://codereview.stackexchange.com/a/220390/98493\">other answer</a> by <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">@Peilonrayz</a>).</li>\n</ul>\n\n\n\n<pre><code>from collections import Counter\nfrom itertools import chain\n\nlists = [list_1, list_2, list_3, list_4, list_5]\n\nno_of_lists_per_name = Counter(chain.from_iterable(map(set, lists)))\n\nfor name, no_of_lists in no_of_lists_per_name.most_common():\n if no_of_lists == 1:\n break # since it is ordered by count, once we get this low we are done\n print(f\"'{name}' is in {no_of_lists} lists\")\n# 'Terry Jones' is in 3 lists\n# 'John Cleese' is in 2 lists\n# 'Michael Palin' is in 2 lists\n</code></pre>\n\n<p>If you are learning Python now, don't learn Python 2, unless you <em>really</em> have to. <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">It will become unsupported in less than a year</a>. And Python 3(.6+) has nice <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-strings</code></a>, which make formatting a lot easier (I used them in the code above).</p>\n\n<p>Note that you can mix string quotation marks. I.e. if you need single-quotes <code>'</code> inside your string, use double-quotes <code>\"\"</code> to make the string (and vice-versa). This way you don't need to escape them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T13:57:14.647",
"Id": "425967",
"Score": "0",
"body": "@Peilonrayz Because I started with OP's code and did not think of it. Afterwards I saw it in your answer but decided to leave it, so both alternatives are there."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T12:01:20.707",
"Id": "220408",
"ParentId": "220387",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T00:03:14.870",
"Id": "220387",
"Score": "7",
"Tags": [
"python",
"python-2.x"
],
"Title": "Count reoccurring elements in multiple lists in Python"
} | 220387 |
<p>I am creating an online voting platform where users could vote on publicly-held polls. It uses Kreait Firebase library (as Google didn't create a PHP library for Firebase Admin).</p>
<p>I am very new to PHP and am not sure about how I should format my PHP code. It is messy. Please help me improve the code.</p>
<pre><code><?php
$request = json_decode(file_get_contents("php://input"));
if (!isset($request->pollPath) || !isset($request->votes)) {
print_r($request);
echo "pollPath and/or votes have not been sent!";
exit;
}
require __DIR__.'/../vendor/autoload.php';
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
$pollPath = $request->pollPath;
$votes = $request->votes;
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/../service.credentials.json');
$firebase = (new Factory)
->withServiceAccount($serviceAccount)
->asUser('brokerServer')
->create();
$pollsDatabase = $firebase->getDatabase();
$electionRef = $pollsDatabase->getReference('publicPolls/' . $request->pollPath);
$postsRef = $electionRef->getChild('posts');
$postsCount = $postsRef->getSnapshot()->numChildren();
if ($postsCount != count($request->votes)) {
echo "Array of votes doesn't match the election's position count";
exit;
}
$votesRef = $electionRef->getChild('votes');
$electionVotes = $votesRef->getValue();
if (!isset($electionVotes))
$electionVotes = [];
$postsValue = $postsRef->getValue();
for ($i = 0; $i < $postsCount; $i++) {
$postValue = &$postsValue[$i];
$postVotes = &$electionVotes[$i];
if (!isset($postVotes)) {
$postVotes = [];
$postCands = count($postValue['candidates']);
for ($j = 0; $j < $postCands; $j++)
$postVotes[$postValue['candidates'][$j]] = 0;
}
if (isset($request->votes[$i]))
$postVotes[$request->votes[$i]] += 1;
}
$votesRef->set($electionVotes);
print_r($electionVotes);
echo "done";
</code></pre>
<p>The code basically gets a JSON fetch request from the client with the path of the election (in Firebase) and an array of votes (mapping index of positions in election to the candidates chosen).</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T00:25:40.457",
"Id": "220389",
"Score": "1",
"Tags": [
"php"
],
"Title": "PHP to cast votes on an open-to-public election"
} | 220389 |
<p>This one is a research attempt to find out how to convert <code>long</code> values as unsigned long integers to <code>String</code>s. It is much slower than <code>java.lang.Long.toUnsignedString</code>, but it was fun to code:</p>
<p><strong><code>net.coderodde.util.Long</code></strong></p>
<pre><code>package net.coderodde.util;
import java.util.Random;
/**
* This class contains a method for converting {@code long} values to unsigned
* strings.
*
* @author Rodion "rodde" Efremov
* @version 1.61 (May 16, 2019)
*/
public final class Long {
/**
* Caching a string builder in order to save some computation.
*/
private static final StringBuilder STRING_BUILDER =
new StringBuilder(java.lang.Long.SIZE);
/**
* Maps individual radices and bits to the numbers they represent in the
* given radix.
*/
private static final Digit[][] bitIndexToDigitChainMaps = new Digit[37][];
/**
* Maps a given internal representation of a digit character to its visual
* glyph.
*/
private static char[] digitsToCharsMap;
/**
* This static inner class represents a single decimal digit.
*/
static final class Digit {
/**
* The actual decimal digit.
*/
int value;
/**
* The higher-order decimal digit.
*/
Digit next;
Digit(int digit) {
this.value = digit;
}
}
static {
initializeBitDigitLists();
initalizeDigitsToCharMap();
}
private static final void initializeBitDigitLists() {
for (int radix = 2; radix != 37; radix++) {
bitIndexToDigitChainMaps[radix] = new Digit[java.lang.Long.SIZE];
for (int bitIndex = 0; bitIndex < 63; bitIndex++) {
long value = 1L << bitIndex;
bitIndexToDigitChainMaps[radix][bitIndex] =
getDigitList(value, radix);
}
bitIndexToDigitChainMaps[radix][java.lang.Long.SIZE - 1] =
getLastDigitList(radix);
}
}
private static final void initalizeDigitsToCharMap() {
digitsToCharsMap = new char[] {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
}
/**
* Converts the given {@code long} value as unsigned to a
* {@link java.lang.String} using the input radix.
*
* @param value the value to convert.
* @param radix the requested radix.
* @return the string representation of the input value as unsigned.
*/
public static String toUnsignedString(long value, int radix) {
checkRadix(radix);
final Digit leastSignificantDigit = new Digit(0);
for (int bitIndex = 0; bitIndex != java.lang.Long.SIZE; bitIndex++) {
if ((value & (1L << bitIndex)) != 0) {
digitsPlus(bitIndexToDigitChainMaps[radix][bitIndex],
leastSignificantDigit,
radix);
}
}
return inferString(leastSignificantDigit);
}
public static String toUnsignedBinaryString(long value) {
return toUnsignedString(value, 2);
}
public static String toUnsignedOctalString(long value) {
return toUnsignedString(value, 8);
}
public static String toUnsignedString(long value) {
return toUnsignedString(value, 10);
}
public static String toUnsignedHexString(long value) {
return toUnsignedString(value, 16);
}
public static final class ThreadSafe {
/**
* Converts the given {@code long} value as unsigned to a
* {@link java.lang.String}. Unlike
* {@link net.coderodde.util.Long#toUnsignedString(long)}, this version
* is thread-safe.
*
* @param value the value to convert.
* @return the string representation of the input value as unsigned.
*/
public static String toUnsignedString(long value, int radix) {
final Digit leastSignificantDigit = new Digit(0);
for (int bitIndex = 0; bitIndex != java.lang.Long.SIZE; bitIndex++) {
if ((value & (1L << bitIndex)) != 0) {
digitsPlus(bitIndexToDigitChainMaps[radix][bitIndex],
leastSignificantDigit,
radix);
}
}
return inferStringThreadSafe(leastSignificantDigit);
}
public static String toUnsignedBinaryString(long value) {
return toUnsignedString(value, 2);
}
public static String toUnsignedOctalString(long value) {
return toUnsignedString(value, 8);
}
public static String toUnsignedString(long value) {
return toUnsignedString(value, 10);
}
public static String toUnsignedHexString(long value) {
return toUnsignedString(value, 16);
}
}
/**
* Infers the {@code long} string from the digit-wise representation.
*
* @param leastSignificantDigit the least-significant digit of the value.
* @return the string representing the digit-wise number.
*/
private static final String inferString(Digit leastSignificantDigit) {
STRING_BUILDER.setLength(0);
return inferString(leastSignificantDigit, STRING_BUILDER);
}
/**
* Infers the {@code long} string from the digit-wise representation. Unlike
* {@link net.coderodde.util.Long#inferString(net.coderodde.util.Long.Digit)},
* this implementation is thread-safe.
*
* @param leastSignificantDigit the least-significant digit of the number to
* infer.
* @return the string representation of the given number.
*/
private static final String inferStringThreadSafe(
Digit leastSignificantDigit) {
return inferString(leastSignificantDigit,
new StringBuilder(java.lang.Long.SIZE));
}
/**
* Infers the resulting string from the input digit list.
*
* @param leastSignificantDigit the digit list.
* @param stringBuilder the string builder.
* @return the resulting string.
*/
private static final String inferString(Digit leastSignificantDigit,
StringBuilder stringBuilder) {
for (Digit digit = leastSignificantDigit;
digit != null;
digit = digit.next) {
stringBuilder.append(digitsToCharsMap[digit.value]);
}
return stringBuilder.reverse().toString();
}
/**
* Performs the addition operation upon two input digit lists.
*
* @param sourceDigits the digits to add.
* @param targetDigits the digits to which to add.
*/
static final void digitsPlus(Digit sourceDigits,
Digit targetDigits,
int radix) {
Digit sourceDigit = sourceDigits;
Digit targetDigit = targetDigits;
Digit targetNumberHead = targetDigit;
boolean carryFlag = false;
//! Try to remove sourceDigit != null
while (sourceDigit != null && targetDigit != null) {
int digitValue = sourceDigit.value + targetDigit.value +
(carryFlag ? 1 : 0);
if (digitValue >= radix) {
digitValue -= radix;
carryFlag = true;
} else {
carryFlag = false;
}
targetNumberHead = targetDigit;
targetDigit.value = digitValue;
sourceDigit = sourceDigit.next;
targetDigit = targetDigit.next;
}
// Deal with the leftovers:
while (sourceDigit != null) {
int value = sourceDigit.value + (carryFlag ? 1 : 0);
if (value >= radix) {
value -= radix;
carryFlag = true;
} else {
carryFlag = false;
}
targetNumberHead.next = new Digit(value);
targetNumberHead = targetNumberHead.next;
sourceDigit = sourceDigit.next;
}
if (carryFlag) {
targetNumberHead.next = new Digit(1);
}
}
/**
* Computes the digit list representing {@code value}.
*
* @param value the target value.
* @return the digit list representing the input value.
*/
private static final Digit getDigitList(long value, int radix) {
Digit previousDigit = null;
Digit leastSignificantDigit = null;
while (value != 0L) {
int digit = (int)(value % radix);
if (previousDigit == null) {
previousDigit = new Digit(digit);
leastSignificantDigit = previousDigit;
} else {
Digit tmp = new Digit(digit);
previousDigit.next = tmp;
previousDigit = tmp;
}
// Drop the last digit of 'value':
value /= radix;
}
return leastSignificantDigit;
}
/**
* Copies the digit list starting from {@code leastSignificantDigit}.
*
* @param leastSignificantDigit the least-significant digit of the digit
* list to be copied.
* @return the copy of the input digit list.
*/
static final Digit copyDigitList(Digit leastSignificantDigit) {
Digit currentSourceDigit = leastSignificantDigit;
Digit returnDigit = new Digit(leastSignificantDigit.value);
Digit headTargetDigit = returnDigit;
currentSourceDigit = currentSourceDigit.next;
while (currentSourceDigit != null) {
Digit targetDigit = new Digit(currentSourceDigit.value);
headTargetDigit.next = targetDigit;
headTargetDigit = targetDigit;
currentSourceDigit = currentSourceDigit.next;
}
return returnDigit;
}
/**
* Returns the decimal number corresponding to {@code 2^64 - 1}.
*
* @return the decimal number corresponding to {@code 2^64 - 1}.
*/
private static final Digit getLastDigitList(int radix) {
Digit source = bitIndexToDigitChainMaps[radix][62];
Digit target = copyDigitList(source);
digitsPlus(source, target, radix);
return target;
}
private static final int BENCHMARK_ITERATIONS = 100_000;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
long seed = System.currentTimeMillis();
Random random1 = new Random(seed);
Random random2 = new Random(seed);
System.out.println("main(): seed = " + seed);
run(BENCHMARK_ITERATIONS, random1, random2, false); // Warm up.
run(BENCHMARK_ITERATIONS, random1, random2, true); // Benchmark.
}
private static final void run(int numberOfValuesToGenerate,
Random random1,
Random random2,
boolean printElapsedTime) {
long startTime = System.currentTimeMillis();
for (int iteration = 0;
iteration < numberOfValuesToGenerate;
iteration++) {
long value = random1.nextLong();
net.coderodde.util.Long.toUnsignedString(value);
}
long endTime = System.currentTimeMillis();
if (printElapsedTime) {
System.out.print("net.coderodde.util.Long.toString() in ");
System.out.print(endTime - startTime);
System.out.println(" milliseconds.");
}
startTime = System.currentTimeMillis();
for (int iteration = 0;
iteration < numberOfValuesToGenerate;
iteration++) {
long value = random2.nextLong();
java.lang.Long.toUnsignedString(value);
}
endTime = System.currentTimeMillis();
if (printElapsedTime) {
System.out.print("java.lang.Long.toString() in ");
System.out.print(endTime - startTime);
System.out.println(" milliseconds.");
}
}
private static final void checkRadix(int radix) {
if (radix < 2 || radix > digitsToCharsMap.length) {
throw new IllegalArgumentException("Bad radix: " + radix);
}
}
}
</code></pre>
<p><strong><code>net.coderodde.util.LongTest</code></strong></p>
<pre><code>package net.coderodde.util;
import java.util.Random;
import net.coderodde.util.Long.Digit;
import static net.coderodde.util.Long.digitsPlus;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* This unit test class tests the {@link net.coderodde.util.Long}.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (May 14, 2019)
*/
public class LongTest {
/**
* The number of brute force iteration when comparing the {@code toString}
* static methods.
*/
private static final int BRUTE_FORCE_ITERATIONS = 1_000;
@Test
public void testDigitsPlusOnEqualLengthSourceTargetNumbers() {
// Number 123:
Digit source3 = new Digit(1);
Digit source2 = new Digit(2);
Digit source1 = new Digit(3);
source1.next = source2;
source2.next = source3;
// Number 456:
Digit target3 = new Digit(4);
Digit target2 = new Digit(5);
Digit target1 = new Digit(6);
target1.next = target2;
target2.next = target3;
// Number 579:
digitsPlus(source1, target1, 10);
assertEquals(9, target1.value);
assertEquals(7, target2.value);
assertEquals(5, target3.value);
}
@Test
public void testDigitsPlusOnLongerTargetNumber() {
Digit source = new Digit(7);
Digit target = new Digit(8);
digitsPlus(source, target, 10);
assertEquals(5, target.value);
assertEquals(1, target.next.value);
}
@Test
public void testDigitsPlusWhenSourceIsLonger() {
// source = 591
Digit source1 = new Digit(1);
Digit source2 = new Digit(9);
Digit source3 = new Digit(5);
source1.next = source2;
source2.next = source3;
// target = 79
Digit target1 = new Digit(9);
Digit target2 = new Digit(7);
target1.next = target2;
// 591 + 79
digitsPlus(source1, target1, 10);
// 591 + 79 = 670
assertEquals(6, target1.next.next.value);
assertEquals(7, target1.next.value);
assertEquals(0, target1.value);
}
@Test
public void testDigitsPlusWhenSourceNumberContainsLongCarryChain() {
// 99500
Digit source1 = new Digit(0);
Digit source2 = new Digit(0);
Digit source3 = new Digit(5);
Digit source4 = new Digit(9);
Digit source5 = new Digit(9);
source1.next = source2;
source2.next = source3;
source3.next = source4;
source4.next = source5;
// 601
Digit target1 = new Digit(1);
Digit target2 = new Digit(0);
Digit target3 = new Digit(6);
target1.next = target2;
target2.next = target3;
// 100101
digitsPlus(source1, target1, 10);
assertEquals(1, target1.value);
assertEquals(0, target1.next.value);
assertEquals(1, target1.next.next.value);
assertEquals(0, target1.next.next.next.value);
assertEquals(0, target1.next.next.next.next.value);
assertEquals(1, target1.next.next.next.next.next.value);
}
@Test
public void testLongToStringWithBruteForce() {
long seed = System.currentTimeMillis();
Random random = new Random(seed);
System.out.println("testLongToStringWithBruteForce, seed = " + seed);
for (int i = 0; i < BRUTE_FORCE_ITERATIONS; i++) {
long value = random.nextLong();
int radix = 2 + random.nextInt(35);
String expected = java.lang.Long.toUnsignedString(value, radix);
String actual = net.coderodde.util.Long.toUnsignedString(value,
radix);
assertEquals(expected, actual);
}
}
@Test
public void testWhenValueIsNegative() {
String expected = java.lang.Long.toUnsignedString(-1000);
String actual = net.coderodde.util.Long.toUnsignedString(-1000);
assertEquals(expected, actual);
}
@Test(expected = IllegalArgumentException.class)
public void testThrowsWhenTooSmallRadix() {
net.coderodde.util.Long.toUnsignedString(1, 1);
}
@Test(expected = IllegalArgumentException.class)
public void testThrowsWhenTooLargeRadix() {
net.coderodde.util.Long.toUnsignedString(1, 37);
}
@Test
public void testWhenLargestRadix() {
assertEquals(java.lang.Long.toUnsignedString(1000L, 36),
net.coderodde.util.Long.toUnsignedString(1000L, 36));
}
}
</code></pre>
<p>So, how am I doing here? Are the unit tests in order? Is my code readable/maintainable?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T05:45:04.147",
"Id": "425845",
"Score": "4",
"body": "I have a hard time figuring out why a static utility method should deliberately be implemented in a thread unsafe manner. Adding a thread safe implementation next to the unsafe one makes the code twice as complicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T06:09:45.960",
"Id": "425850",
"Score": "2",
"body": "@TorbenPutkonen Feel free to point that out in a review, I haven't touched it in mine."
}
] | [
{
"body": "<p>Since you're asking about readability, let's take a look at that.</p>\n\n<p>Your functions and variables could be named better. Especially parts like this:</p>\n\n<pre><code>static final void digitsPlus(Digit sourceDigits,\n Digit targetDigits,\n int radix) {\n Digit sourceDigit = sourceDigits;\n Digit targetDigit = targetDigits;\n</code></pre>\n\n<p>How many <code>Digit</code> are passed to the function? 2? 2 lists of <code>Digit</code>? And why does it read like you're putting multiple <code>Digit</code> in a single <code>Digit</code>? I know, because I read the rest of the code. But from how this function is written, I'd have questions.</p>\n\n<p>But your tests are worse:</p>\n\n<pre><code>@Test\npublic void testDigitsPlusWhenSourceIsLonger() {\n // source = 591\n Digit source1 = new Digit(1);\n Digit source2 = new Digit(9);\n Digit source3 = new Digit(5);\n\n source1.next = source2;\n source2.next = source3;\n\n // target = 79\n Digit target1 = new Digit(9);\n Digit target2 = new Digit(7);\n\n target1.next = target2;\n // 591 + 79\n digitsPlus(source1, target1, 10);\n\n // 591 + 79 = 670\n assertEquals(6, target1.next.next.value);\n assertEquals(7, target1.next.value);\n assertEquals(0, target1.value);\n}\n</code></pre>\n\n<p>Why are there numbers in your variable names? Not just once, but all over the place. The moment you start putting numbers in your variable names, often you're either naming them wrong or using the wrong type of variable.</p>\n\n<p><code>testDigitsPlusWhenSourceIsLonger()</code> Longer than what? Probably the target number, but this function is ran on data already in storage. It takes no arguments. So your tests aren't reusable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T06:09:09.717",
"Id": "220398",
"ParentId": "220395",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T05:16:19.560",
"Id": "220395",
"Score": "4",
"Tags": [
"java",
"algorithm",
"formatting",
"integer",
"number-systems"
],
"Title": "Converting long values in Java to unsigned strings"
} | 220395 |
<p><strong>The task</strong>
is taken from <a href="https://leetcode.com/problems/valid-parentheses/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Given a string containing just the characters '(', ')', '{', '}', '['
and ']', determine if the input string is valid.</p>
<p>An input string is valid if:</p>
<ul>
<li>Open brackets must be closed by the same type of brackets.</li>
<li>Open brackets must be closed in the correct order.</li>
<li>Note that an empty string is also considered valid.</li>
</ul>
<p><strong>Example 1:</strong></p>
<pre><code>Input: "()"
Output: true
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: "()[]{}"
Output: true
</code></pre>
<p><strong>Example 3:</strong></p>
<pre><code>Input: "(]"
Output: false
</code></pre>
<p><strong>Example 4:</strong></p>
<pre><code>Input: "([)]"
Output: false
</code></pre>
<p><strong>Example 5:</strong></p>
<pre><code>Input: "{[]}"
Output: true
</code></pre>
</blockquote>
<p><strong>My functional solution</strong></p>
<pre><code>/**
* @param {string} s
* @return {boolean}
*/
var isValid = s => {
const par = {
"(": ")",
"{": "}",
"[": "]",
};
const rep = [];
return [...s].every(x => par[x]
? rep.push(par[x])
: rep.pop() === x) && !rep.length;
};
</code></pre>
<p><strong>My imperative soltion</strong></p>
<pre><code>/**
* @param {string} s
* @return {boolean}
*/
var isValid2 = s => {
const par = {
"(": ")",
"{": "}",
"[": "]",
};
const rep = [];
for (let i = 0; i < s.length; i++) {
if (par[s[i]]) {
rep.push(par[s[i]]);
} else {
if (rep.pop() !== s[i]) {
return false;
}
}
}
return rep.length === 0;
};
</code></pre>
| [] | [
{
"body": "<p>The code looks quite succinct and sufficient. The only suggestions I would offer are minor tweaks:</p>\n\n<ul>\n<li><p>for the imperative solution, a <code>for...of</code> loop could be used to eliminate the need to do bookkeeping on the counter variable and use it to index into the string to get each character:</p>\n\n<pre><code>for(const c of s) {\n if (par[c]) {\n rep.push(par[c]);\n } else {\n if (rep.pop() !== c) {\n return false;\n }\n}\n</code></pre></li>\n<li><p>for the functional solution, the callback function could be declared on a previous line, and then the <code>return</code> line can be reduced to a single line:</p>\n\n<pre><code>const pushOrPopMatch = x => par[x] ? rep.push(par[x]) : rep.pop() === x\nreturn [...s].every(pushOrPopMatch) && !rep.length;\n</code></pre>\n\n<p>That line defining <code>pushOrPopMatch()</code> is 73 characters long, which some might argue is too long for a line, given it would be inside a function and indented at least two spaces, so it may not be ideal</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-19T19:36:57.973",
"Id": "224495",
"ParentId": "220396",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "224495",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T05:35:41.240",
"Id": "220396",
"Score": "7",
"Tags": [
"javascript",
"programming-challenge",
"functional-programming",
"ecmascript-6",
"balanced-delimiters"
],
"Title": "Given a string containing just parentheses, determine if the input string is valid"
} | 220396 |
<p>I was tasked with writing a Matryoshka doll program that manages the following:</p>
<ul>
<li><strong>howManyDolls</strong> : returns an integer based on how many dolls are inside the stack</li>
<li><strong>howManyWearingBabushkas</strong> : returns an integer based on how many dolls are wearing a Babushka. The boolean variable <code>babushka</code> determines this.</li>
<li><strong>totalWeight</strong> : returns a double based on the weight of all the dolls in the stack</li>
</ul>
<p>I would appreciate feedback on the recursion part of the code, if it's the most efficient/proper way to use recursion in this context. I am very new to recursion, so I want to make sure I am doing the best I can going forward. </p>
<pre><code>public class Matryoshka {
private String name;
private double weight;
private boolean babushka;
private Matryoshka innerDoll;
public Matryoshka(String name, double weight, boolean babushka) {
this.name = name;
this.weight = weight;
this.babushka = babushka;
this.innerDoll = null;
}
public Matryoshka(String name, double weight, boolean babushka, Matryoshka doll) {
this.name = name;
this.weight = weight;
this.babushka = babushka;
this.innerDoll = doll;
}
public String getName() { return this.name; }
public double getWeight() { return this.weight; }
public boolean getBabushka() { return this.babushka; }
public boolean hasInnerDoll() {
return this.innerDoll != null;
}
public Matryoshka getInnerDoll() {
return this.innerDoll;
}
public int howManyDolls() {
if(this.innerDoll == null) { return 1; }
return 1 + this.innerDoll.howManyDolls();
}
public int howManyWearingBabushkas() {
if(!this.hasInnerDoll()) { return 0; }
if(!this.getBabushka()) { return 0 + this.getInnerDoll().howManyWearingBabushkas(); }
return 1 + this.getInnerDoll().howManyWearingBabushkas();
}
public double totalWeight() {
if(!this.hasInnerDoll()) { return this.getWeight(); }
return this.getWeight() + this.getInnerDoll().totalWeight();
}
}
</code></pre>
| [] | [
{
"body": "<p><strong>Naming</strong></p>\n\n<p>Field <code>babushka</code> should be named <code>wearingBabushka</code>, since that is what the field describes. The method accessing it becomes <code>isWearingBabushka()</code>. For some reason Java-people like exceptions in naming standards and are adamant that it's vital to have a non-standard getter name for boolean typed methods (yes I'm bitter about this, no need to go into it any deeper).</p>\n\n<p><strong>Final modifiers</strong></p>\n\n<p>The fields should be final, as they are not meant to be changed. Non-final fields always increase the cognitive load on the reader as they have to figure out where the fields are modified.</p>\n\n<p><strong>Constructors vs. static factory methods</strong></p>\n\n<p>In this application it could be useful to instantiate the objects with static factory methods.</p>\n\n<pre><code>public abstract class Matryoshka {\n\n public static Matryoshka of(String name, ...) {\n return new RootMatryoshka(name, ...);\n }\n\n public static Matryoshka of(String name, ..., Matryoshka innerMatryoshka) {\n Objects.requireNonNull(innerMatryoshka);\n return new OuterMatryoshka(name, ..., innerMatryoshka);\n }\n}\n</code></pre>\n\n<p>Static factory methods allow you to return a different implementations when needed. The root matryoshka would return static values from the methods that calculate weight etc. The outer matryoshkas would simply perform recursion and addition with no need for null checks (as the factory method prevents null values). There are rules on how classe that use static factory methods should be written, I won't replicate them here.</p>\n\n<p>But that's pretty much a matter of taste. The current implementation is just fine too.</p>\n\n<p><strong>Bugs</strong></p>\n\n<p>If the root matryoshka wears a babushka, the calculation returns an incorrect answer.</p>\n\n<p><strong>Style</strong></p>\n\n<p>I find the unnecessary use of <code>this</code> distracting. In my opinion it should be used only when there is a naming conflict. When done so, the number of references to this can be used as a metric for bad naming or problematic structure.</p>\n\n<p><strong>Tail recursion</strong></p>\n\n<p>Since you asked about efficiency, I have to talk about tail recursion. But be aware that this all is <em>total and complete premature optimization</em>. Each of the recursive methods could be replaced with a loop, which would eliminate the need for populating the stack on each recursion:</p>\n\n<pre><code>public int howManyDolls() {\n int dollCount = 0;\n\n Matryoshka currentDoll = this;\n while (currentDoll != null) {\n dollCount++;\n currentDoll = getInnerDoll();\n }\n return count;\n}\n</code></pre>\n\n<p>It probably won't affect running time, but at least you're not limited by the stack size. You can have millions of matryoshkas! But you will fail the recursion task, since now this has none.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:06:33.913",
"Id": "220411",
"ParentId": "220409",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220411",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T12:38:46.303",
"Id": "220409",
"Score": "3",
"Tags": [
"java",
"recursion"
],
"Title": "Matryoshka Doll Recursion"
} | 220409 |
<p>I wrote this code and it works fine for my purpose, to look for some values and copy paste the result to another sheet (online for selected column). I want to know the opinion from this community regarding my code. I just learned the VBA for 1 week.</p>
<pre><code>Option Explicit
Sub Analysis_ClientRating()
Dim lastrow As Long, i As Long, rowppt As Long, colppt As Long
Dim rowppt1 As Long, colppt1 As Long, rowppt2 As Long, colppt2 As Long
Dim rowppt3 As Long, colppt3 As Long
lastrow = ShNote.Range("C" & Rows.Count).End(xlUp).Row
rowppt = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
colppt = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
rowppt1 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
colppt1 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
rowppt2 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
colppt2 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
rowppt3 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
colppt3 = ShPPT.Cells(Rows.Count, 1).End(xlUp).Row
Call Entry_Point
For i = 6 To lastrow
Select Case ShNote.Cells(i, 5).Value
Case Is = 20
ShNote.Cells(i, 3).Copy
ShPPT.Cells(rowppt + 6, 3).PasteSpecial xlPasteValues
ShNote.Cells(i, 5).Copy
ShPPT.Cells(colppt + 6, 4).PasteSpecial xlPasteValues
rowppt = rowppt + 1
colppt = colppt + 1
Case Is >= 17
ShNote.Cells(i, 3).Copy
ShPPT.Cells(rowppt1 + 6, 6).PasteSpecial xlPasteValues
ShNote.Cells(i, 5).Copy
ShPPT.Cells(colppt1 + 6, 7).PasteSpecial xlPasteValues
rowppt1 = rowppt1 + 1
colppt1 = colppt1 + 1
Case Is >= 15
ShNote.Cells(i, 3).Copy
ShPPT.Cells(rowppt2 + 6, 9).PasteSpecial xlPasteValues
ShNote.Cells(i, 5).Copy
ShPPT.Cells(colppt2 + 6, 10).PasteSpecial xlPasteValues
rowppt2 = rowppt2 + 1
colppt2 = colppt2 + 1
Case Is >= 11
ShNote.Cells(i, 3).Copy
ShPPT.Cells(rowppt3 + 6, 12).PasteSpecial xlPasteValues
ShNote.Cells(i, 5).Copy
ShPPT.Cells(colppt3 + 6, 13).PasteSpecial xlPasteValues
rowppt3 = rowppt3 + 1
colppt3 = colppt3 + 1
End Select
Next i
Call Exit_Point
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T18:24:47.770",
"Id": "426090",
"Score": "0",
"body": "Hello, Thanks for the great feedback from the members of this community. As @damian pointed out two specific variables \"colppt & rowppt\" that I declared several times due to my lack of experience in VBA. I have 2 sheets, one for database and the other one is for \"the final result (FR) of the extraction of values from database\". My FR sheet has 4 tables with 4 categories. First time, I wrote my code, I only declared \"colppt & row ppt\" after writing last case I mentionned rowppt = rowppt + 1 same as for col ppt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T18:27:03.857",
"Id": "426091",
"Score": "0",
"body": "When I run my code, the result for data ranges the first 3 tables is overlapping on the first row of each tables only the last table the data is shown at each row based on the condition met. Therefore, I declared several row ppt & col ppt to prevent the overlapping data range for the same row."
}
] | [
{
"body": "<p>This is all I can think of:</p>\n\n<pre><code>Option Explicit\nSub Analysis_ClientRating()\n Dim lastrow As Long, i As Long, rowppt As Long, rowppt1 As Long, _\n rowppt2 As Long, rowppt3 As Long\n\n lastrow = ShNote.Range(\"C\" & ShNote.Rows.Count).End(xlUp).Row 'you need to qualify the Rows.count\n With shPPT 'you can use it so there is no need to write the sheet in between the with\n rowppt = .Cells(.Rows.Count, 1).End(xlUp).Row\n rowppt1 = rowppt 'them all gonna take the same value\n rowppt2 = rowppt\n rowppt3 = rowppt\n End With\n\n 'colpptl are redundant since you are always taking the same value for all the variables and using them along with rowpptl\n\n Call Entry_Point\n\n For i = 6 To lastrow\n Select Case ShNote.Cells(i, 5).Value\n Case Is = 20\n shPPT.Cells(rowppt + 6, 3).Value = ShNote.Cells(i, 3).Value 'because you are copying just 1 cell to another (values) .Value = .Value is faster\n shPPT.Cells(rowppt + 6, 4).Value = ShNote.Cells(i, 5).Value\n rowppt = rowppt + 1\n\n Case Is >= 17\n shPPT.Cells(rowppt1 + 6, 6).Value = ShNote.Cells(i, 3).Value\n shPPT.Cells(rowppt1 + 6, 7).Value = ShNote.Cells(i, 5).Value\n rowppt1 = rowppt1 + 1\n\n Case Is >= 15\n shPPT.Cells(rowppt2 + 6, 9).Value = ShNote.Cells(i, 3).Value\n shPPT.Cells(rowppt2 + 6, 10).Value = ShNote.Cells(i, 5).Value\n rowppt2 = rowppt2 + 1\n\n Case Is >= 11\n shPPT.Cells(rowppt3 + 6, 12).Value = ShNote.Cells(i, 3).Value\n shPPT.Cells(rowppt3 + 6, 13).Value = ShNote.Cells(i, 5).Value\n rowppt3 = rowppt3 + 1\n\n End Select\n Next i\n\n Call Exit_Point\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T15:40:13.393",
"Id": "220421",
"ParentId": "220410",
"Score": "0"
}
},
{
"body": "<p>If you've only learned VBA a week ago, then congratulations and a good job getting a working solution! Hopefully the information and tips here can provide some help in refining not only your solution, but to help guide your code in the future.</p>\n\n<p>You've avoided some basic traps because you're already using <code>Option Explicit</code> and you are assigning a type to each variable on the <code>Dim</code> line. Most professional VBA developers will advise that it's a better habit to declare each variable immediately before it's used, even down lower in the method. This avoids the \"wall of declarations\" up front.</p>\n\n<p>You have a potential problem on the statement to determine the <code>lastrow</code> value. It's an easy thing to miss, but when you use <code>Rows.Count</code>, you are referring to the number of rows on the <em>active worksheet</em>, NOT the number of rows on <code>ShNote</code> (which is what you want). So the fully accurate line is</p>\n\n<pre><code>lastrow = ShNote.Range(\"C\" & ShNote.Rows.Count).End(xlUp).Row\n</code></pre>\n\n<p>Of course the same thing goes for similar statements throughout your code.</p>\n\n<p>(I'm skipping around in your code, it will all make sense in the end I promise)</p>\n\n<p>The values that you're using in the <code>Select Case</code> statement are simple numbers, but those numbers are meaningless unless you give them context. What do those numbers mean in your workbook and for your data? Translate that \"meaning\" into your code. One way can be to create a set of constants. I've defined a set like this:</p>\n\n<pre><code>Const MAX_THRESHOLD As Long = 20\nConst HIGH_THRESHOLD As Long = 17\nConst MED_THRESHOLD As Long = 15\nConst LOW_THRESHOLD As Long = 13\n</code></pre>\n\n<p>Now you can change the values just be changing the definitions, and your code makes more sense as you (or me) reads it.</p>\n\n<p>Next, I have to question why you're calculating the same last row value on <code>ShPPT</code> eight times in a row. You can calculate it once, then copy the assignment to the other variables. You can also use more meaningful variable names, since we're defining why we're keeping track of the different rows.</p>\n\n<pre><code>Dim lastSourceRow As Long\nlastSourceRow = ShNote.Range(\"C\" & ShNote.Rows.Count).End(xlUp).Row\n\n'--- start all the rows at the same value\nDim lastMaxRow As Long\nDim lastHighRow As Long\nDim lastMedRow As Long\nDim lastLowRow As Long\nlastMaxRow = lastSourceRow\nlastHighRow = lastSourceRow\nlastMedRow = lastSourceRow\nlastLowRow = lastSourceRow\n</code></pre>\n\n<p>The separate \"counters\" you had for the columns of each threshold hold the exact same value as the rows, so they aren't needed.</p>\n\n<p>I see that each value is incremented separately, but there's also a very consistent pattern to the logic within each <code>Case</code>. When you see that, your first thought should be to break out a separate function that can isolate the logic in a single place. That makes it easier to change later. For example, your method could be</p>\n\n<pre><code>Private Function NowCopyPaste2(ByVal fromRow As Long, _\n ByVal toRow As Long, _\n ByVal toColumn As Long, _\n ByRef fromWS As Worksheet, _\n ByRef toWS As Worksheet) As Long\n fromWS.Cells(fromRow, 3).Copy\n toWS.Cells(toRow + 6, toColumn).PasteSpecial xlPasteValues\n fromWS.Cells(fromRow, 5).Copy\n toWS.Cells(toRow + 6, toColumn + 1).PasteSpecial xlPasteValues\n NowCopyPaste = toRow + 1\nEnd Function\n</code></pre>\n\n<p>This produces the same logic that exists in your original post. <strong>However</strong>, you're using copy/paste to transfer a value from one cell to another and there's a much simpler way that uses far less resources. Just simply assign the value of one cell to the other. The improved <code>NowCopyPaste</code> function is</p>\n\n<pre><code>Private Function NowCopyPaste(ByVal fromRow As Long, _\n ByVal toRow As Long, _\n ByVal toColumn As Long, _\n ByRef fromWS As Worksheet, _\n ByRef toWS As Worksheet) As Long\n toWS.Cells(toRow + 6, toColumn).Value = fromWS.Cells(fromRow, 3).Value\n toWS.Cells(toRow + 6, toColumn + 1).Value = fromWS.Cells(fromRow, 5).Value\n NowCopyPaste = toRow + 1\nEnd Function\n</code></pre>\n\n<p>Finally, the main logic of your code is more clear for the upfront work you've done and the clear definitions used:</p>\n\n<pre><code>'--- values are copied to the PowerPoint worksheet and sorted by\n' columns according to the threshold tests\nDim i As Long\nFor i = 6 To lastSourceRow\n Select Case ShNote.Cells(i, 5).Value\n Case Is = MAX_THRESHOLD\n lastMaxRow = NowCopyPaste(i, lastMaxRow, 3, ShNote, ShPPT)\n\n Case Is >= HIGH_THRESHOLD\n lastHighRow = NowCopyPaste(i, lastHighRow, 6, ShNote, ShPPT)\n\n Case Is >= MED_THRESHOLD\n lastMedRow = NowCopyPaste(i, lastMedRow, 9, ShNote, ShPPT)\n\n Case Is >= LOW_THRESHOLD\n lastLowRow = NowCopyPaste(i, lastLowRow, 12, ShNote, ShPPT)\n\n Case Else\n '--- what will you do here? (could be nothing but it's\n ' still a good idea to document with a comment that\n ' values in this range are not copied\n End Select\nNext i\n</code></pre>\n\n<p>Notice that I also have used comments prior to each logic block that explain what the code does and why. This will always be important for maintaining the code, even if you are the only one to ever look at it again.</p>\n\n<p>Here's the whole module in a single block:</p>\n\n<pre><code>Option Explicit\n\nPublic Sub AnalysisClientRating()\n Const MAX_THRESHOLD As Long = 20\n Const HIGH_THRESHOLD As Long = 17\n Const MED_THRESHOLD As Long = 15\n Const LOW_THRESHOLD As Long = 13\n\n Dim lastSourceRow As Long\n lastSourceRow = ShNote.Range(\"C\" & ShNote.Rows.Count).End(xlUp).Row\n\n '--- start all the rows at the same value\n Dim lastMaxRow As Long\n Dim lastHighRow As Long\n Dim lastMedRow As Long\n Dim lastLowRow As Long\n lastMaxRow = lastSourceRow\n lastHighRow = lastSourceRow\n lastMedRow = lastSourceRow\n lastLowRow = lastSourceRow\n\n '--- I don't know what your entry and exit points do, but you should\n ' create a comment that gives the next developer an idea why these\n ' methods exist and why they are here. what do they do?\n Entry_Point\n\n '--- values are copied to the PowerPoint worksheet and sorted by\n ' columns according to the threshold tests\n Dim i As Long\n For i = 6 To lastSourceRow\n Select Case ShNote.Cells(i, 5).Value\n Case Is = MAX_THRESHOLD\n lastMaxRow = NowCopyPaste(i, lastMaxRow, 3, ShNote, ShPPT)\n\n Case Is >= HIGH_THRESHOLD\n lastHighRow = NowCopyPaste(i, lastHighRow, 6, ShNote, ShPPT)\n\n Case Is >= MED_THRESHOLD\n lastMedRow = NowCopyPaste(i, lastMedRow, 9, ShNote, ShPPT)\n\n Case Is >= LOW_THRESHOLD\n lastLowRow = NowCopyPaste(i, lastLowRow, 12, ShNote, ShPPT)\n\n Case Else\n '--- what will you do here? (could be nothing but it's\n ' still a good idea to document with a comment that\n ' values in this range are not copied\n End Select\n Next i\n\n Exit_Point\n\nEnd Sub\n\nPrivate Function NowCopyPaste(ByVal fromRow As Long, _\n ByVal toRow As Long, _\n ByVal toColumn As Long, _\n ByRef fromWS As Worksheet, _\n ByRef toWS As Worksheet) As Long\n toWS.Cells(toRow + 6, toColumn).Value = fromWS.Cells(fromRow, 3).Value\n toWS.Cells(toRow + 6, toColumn + 1).Value = fromWS.Cells(fromRow, 5).Value\n NowCopyPaste = toRow + 1\nEnd Function\n\nPrivate Sub Entry_Point()\n '--- does something interesting?\nEnd Sub\n\nPrivate Sub Exit_Point()\n '--- does something interesting?\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T18:11:44.737",
"Id": "426088",
"Score": "0",
"body": "Wow, thank you for your complete feedback. I will learn your answer and try to apply to my module tomorrow. I am getting back to you for the final result. Thanks again. I really appreciate your time to refine my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T14:31:51.177",
"Id": "220512",
"ParentId": "220410",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T12:50:32.703",
"Id": "220410",
"Score": "4",
"Tags": [
"beginner",
"vba",
"excel"
],
"Title": "Copy paste from one sheet to another"
} | 220410 |
<p>Following up from <a href="https://codereview.stackexchange.com/questions/220235/simple-wiki-with-php">part one</a>, I've attempted to convert the largest part of my project into an MVC pattern as per suggestions from the accepted answer. I've managed to split the original <code>edit.php</code> file into a template and the business logic part, but there's still a lot of repetition going on. I feel like there has to be a better way to handle cutting down on the repetition without introducing tons of new variables and if statements all over the place.</p>
<p><strong><code>edit.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code><?php
require_once "bootstrap.php";
$message = $_SESSION["message"] ?? "";
unset($_SESSION["message"]);
const MAX_LENGTH_TITLE = 32;
const MAX_LENGTH_BODY = 10000;
$errors = [];
$title = htmlspecialchars($_GET["title"] ?? "");
$slug = "";
if ($title !== slugify($title)) {
$slug = slugify($title);
} else {
$slug = $title;
}
$stmt = $pdo->prepare("SELECT id, title, slug, body FROM articles WHERE slug = ?");
$stmt->execute([$slug]);
$article = $stmt->fetch();
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (!empty($_POST["edit-article"])) {
$title = $_POST["title"];
$body = $_POST["body"];
$slug = slugify($title);
if (empty(trim($title))) {
$errors[] = "No title. Please enter a title.";
} elseif (strlen($title) > MAX_LENGTH_TITLE) {
$errors[] = "Title too long. Please enter a title less than or equal to " . MAX_LENGTH_TITLE . " characters.";
} elseif (slugify($title) !== $article["slug"]) {
$errors[] = "Title may only change in capitalization or by having additional symbols added.";
}
if (strlen($body) > MAX_LENGTH_BODY) {
$errors[] = "Body too long. Please enter a body less than or equal to " . MAX_LENGTH_BODY . " characters.";
}
if (empty($errors)) {
$stmt = $pdo->prepare("UPDATE articles SET title = ?, body = ? WHERE id = ?");
$stmt->execute([$title, $body, $article["id"]]);
$_SESSION["message"] = "Article successfully updated.";
header("Location: /wiki.php?title=" . $article["slug"]);
exit();
}
} elseif (!empty($_POST["create-article"])) {
$title = $_POST["title"];
$body = $_POST["body"];
$slug = slugify($title);
if (empty(trim($title))) {
$errors[] = "No title. Please enter a title.";
} elseif (strlen($title) > MAX_LENGTH_TITLE) {
$errors[] = "Title too long. Please enter a title less than or equal to " . MAX_LENGTH_TITLE . " characters.";
}
$stmt = $pdo->prepare("SELECT title, slug FROM articles WHERE title = ? OR slug = ?");
$stmt->execute([$title, $slug]);
$article_exists = $stmt->fetch();
if ($article_exists) {
$errors[] = "An article by that title already exists. Please choose a different title.";
}
if (strlen($body) > MAX_LENGTH_BODY) {
$errors[] = "Body too long. Please enter a body less than or equal to " . MAX_LENGTH_BODY . " characters.";
}
if (empty($errors)) {
$stmt = $pdo->prepare("INSERT INTO articles (title, slug, body) VALUES (?, ?, ?)");
$stmt->execute([$title, $slug, $body]);
$_SESSION["message"] = "Article successfully created.";
header("Location: /wiki.php?title=" . $slug);
exit();
}
}
}
$title = $article["title"] ?? $title;
$template = "edit.php";
require_once "templates/layout.php";
</code></pre>
<p><strong><code>templates/edit.php</code></strong></p>
<pre class="lang-php prettyprint-override"><code><?php if (!empty($errors)): ?>
<ul>
<?php foreach ($errors as $error): ?>
<li><?= $error; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php if ($article): ?>
<form action="/edit.php?title=<?= $article["title"]; ?>" method="post" name="form-edit-article">
<div><label for="title">Title</label></div>
<div><input type="text" name="title" id="title" size="40" value="<?= htmlspecialchars($article["title"]); ?>" required></div>
<div><label for="body">Body</label></div>
<div><textarea name="body" id="body" rows="30" cols="120" maxlength="10000"><?= htmlspecialchars($article["body"]); ?></textarea></div>
<div><span id="character-counter"></span></div>
<div><input type="submit" name="edit-article" value="Edit Article"></div>
</form>
<?php else: ?>
<form action="/edit.php" method="post" name="form-create-article">
<div><label for="title">Title</label></div>
<div><input type="text" name="title" id="title" size="40" value="<?= htmlspecialchars($title); ?>" required></div>
<div><label for="body">Body</label></div>
<div><textarea name="body" id="body" rows="30" cols="120" maxlength="10000"><?= htmlspecialchars($_POST["body"] ?? ""); ?></textarea></div>
<div><span id="character-counter"></span></div>
<div><input type="submit" name="create-article" value="Create Article"></div>
</form>
<?php endif; ?>
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>I recommend that you not store <code>htmlspecialchars()</code> values as a general practice. Of course you can if you wish, but I prefer to keep raw values in the db as a base representation of the data and then only manipulate the value when needed and in the manner required for the given task.</p></li>\n<li><p>You are (conditionally) calling <code>slugify()</code> twice on the <code>$_GET[\"title\"]</code> value; this is in breach of DRY coding practices. You should calling it once at most. If this were my project, I don't think that I would allow the call of <code>slugify()</code> (or the trip the database for that matter) at all if the <code>title</code> is empty. I don't know if the identical title-slug check is necessary to perform -- it looks like extra work. If you want to validate the title and check if it is a slug... rather than running the multiple <code>preg_replace()</code> calls in that custom function and comparing the return value to the input, just make a single <code>preg_match()</code> call to make sure it contains only valid letters and complies with your length requirements.</p></li>\n<li><p>Because I believe you can rely on the existence of <code>$_POST[\"title\"]</code>, <code>empty(trim($title)</code> can be written as <code>!trim($title)</code> for the same effect with one less function call.</p></li>\n<li><p>Again, to espouse DRY coding practices, don't call <code>strlen($title)</code> twice, cache the value and check the variable.</p></li>\n<li><p>All string validations should pass before making any trips to the db for best performance. You are check the body length too late. You should write it before the SELECT query.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T19:52:49.617",
"Id": "220524",
"ParentId": "220413",
"Score": "2"
}
},
{
"body": "<p>Well, I just moved the part of code, which literally duplicates in both branches, above the condition. That's all. for the rest, I don't think there is anything significant could be made in the current paradigm. </p>\n\n<pre><code>if ($_SERVER[\"REQUEST_METHOD\"] === \"POST\")\n{\n $title = $_POST[\"title\"];\n $body = $_POST[\"body\"];\n $slug = slugify($title);\n\n if (empty(trim($title))) {\n $errors[] = \"No title. Please enter a title.\";\n } elseif (strlen($title) > MAX_LENGTH_TITLE) {\n $errors[] = \"Title too long. Please enter a title less than or equal to \" . MAX_LENGTH_TITLE . \" characters.\";\n }\n if (strlen($body) > MAX_LENGTH_BODY) {\n $errors[] = \"Body too long. Please enter a body less than or equal to \" . MAX_LENGTH_BODY . \" characters.\";\n }\n\n if (!empty($_POST[\"edit-article\"]))\n {\n if (slugify($title) !== $article[\"slug\"]) {\n $errors[] = \"Title may only change in capitalization or by having additional symbols added.\";\n }\n if (empty($errors)) {\n $stmt = $pdo->prepare(\"UPDATE articles SET title = ?, body = ? WHERE id = ?\");\n $stmt->execute([$title, $body, $article[\"id\"]]);\n $_SESSION[\"message\"] = \"Article successfully updated.\";\n header(\"Location: /wiki.php?title=\" . $article[\"slug\"]);\n exit();\n }\n } elseif (!empty($_POST[\"create-article\"])) {\n\n $stmt = $pdo->prepare(\"SELECT title, slug FROM articles WHERE title = ? OR slug = ?\");\n $stmt->execute([$title, $slug]);\n $article_exists = $stmt->fetch();\n\n if ($article_exists) {\n $errors[] = \"An article by that title already exists. Please choose a different title.\";\n }\n if (empty($errors)) {\n $stmt = $pdo->prepare(\"INSERT INTO articles (title, slug, body) VALUES (?, ?, ?)\");\n $stmt->execute([$title, $slug, $body]);\n $_SESSION[\"message\"] = \"Article successfully created.\";\n header(\"Location: /wiki.php?title=\" . $slug);\n exit();\n }\n }\n}\n$title = $article[\"title\"] ?? $title;\n$template = \"edit.php\";\nrequire_once \"templates/layout.php\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T08:12:11.940",
"Id": "220547",
"ParentId": "220413",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220524",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:25:16.490",
"Id": "220413",
"Score": "4",
"Tags": [
"performance",
"php",
"mvc"
],
"Title": "Simple wiki with PHP, part two"
} | 220413 |
<p>I'm just doing a small hobby project to solve a little problem I have and I'm using it as a learning exercise for ASP.Net MVC 5, .Net Core 2 and Bootstrap.</p>
<p>I'm using a nuget package that handles interaction with a 3rd party api (EveStandard), I make the api calls that I need, spin up a view model which holds the data I want to present to my view.</p>
<p>I'm posting to ask 2 things. </p>
<ol>
<li>Have I applied MVC correctly here?</li>
<li>The IMemoryCache (for now) only has a lookup, populated by the controller for id's to their human-readable name. I want this to be an application-wide cache and I don't understand why I have to inject it into the controller. All I want to do is apply a transform in the view layer to a data item on my model. As far as I understand it I would have to do this transformation in the controller and supply an extra piece of data added to the model everytime. I just want a static helper method that I would have somewhere to do the lookup in an adhoc manner as the project grows.</li>
</ol>
<h2>Model:</h2>
<pre><code>public class BookmarkViewModel
{
public BookmarkViewModel(BookmarkSection personalBookmarks, BookmarkSection corpBookmarks)
{
PersonalBookmarks = personalBookmarks;
CorpBookmarks = corpBookmarks;
}
public Dictionary<int, UniverseIdsToNames> UniverseMapping { get; set; }
public BookmarkSection PersonalBookmarks { get; set; }
public BookmarkSection CorpBookmarks { get; set; }
}
public class BookmarkSection
{
public BookmarkSection(List<BookmarkFolder> folders, List<Bookmark> bookmarks)
{
BookmarkFolders = folders;
Bookmarks = bookmarks;
}
public List<BookmarkFolder> BookmarkFolders { get; set; }
public List<Bookmark> Bookmarks { get; set; }
}
</code></pre>
<h2>View Index.cshtml:</h2>
<pre><code>@using EVEStandard.Models
@model BookmarkViewModel
@{
ViewData["Title"] = "Bookmark";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@if (!User.Identity.IsAuthenticated)
{
<h1>Bookmarks are available once you have logged in.</h1>
}
else
{
<nav>
<div class="nav nav-tabs" id="nav-tab" role="tablist">
<a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab" aria-controls="nav-home" aria-selected="true">Personal</a>
<a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab" aria-controls="nav-profile" aria-selected="false">Corp</a>
</div>
</nav>
<div class="tab-content" id="nav-tabContent">
<div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
@await Html.PartialAsync("_BookmarkView", Model.PersonalBookmarks)
</div>
<div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
@await Html.PartialAsync("_BookmarkView", Model.CorpBookmarks)
</div>
</div>
}
</code></pre>
<h3>BookmarkView (partial)</h3>
<pre><code>@model BookmarkSection
@*
For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
*@
@functions {
/// <summary>
/// Converts an universe ID into the human readable version by checking the application
/// memory cache
/// </summary>
/// <param name="id">Universe ID</param>
/// <returns>Unknown or the real name</returns>
private string GetHumanReadable(int id)
{
var name = "Unknown";
//var cache = MemoryCache.Default;
//if (Model.UniverseMapping.ContainsKey(id))
//{
// name = Model.UniverseMapping[id].Name;
//}
return name;
}
}
@if (Model.Bookmarks.Any() == false)
{
<h2>You don't have any bookmarks in this section.</h2>
}
else
{
var accordionId = $"accordion{Model.Bookmarks.First().BookmarkId}";
var accordionDataParent = $"#{accordionId}";
<div class="accordion" id="@accordionId">
@foreach (var folder in Model.BookmarkFolders)
{
<div class="card">
@{
var headingId = "heading" + folder.FolderId;
var collapseId = "collapse" + folder.FolderId;
var collapseDataTarget = "#collapse" + folder.FolderId;
}
<div class="card-header" id=@headingId>
<h2 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="@collapseDataTarget" aria-expanded="false" aria-controls="@collapseId">
@folder.Name
</button>
</h2>
</div>
<div id="@collapseId" class="collapse show" aria-labelledby=@headingId data-parent="@accordionDataParent">
<div class="card-body">
<table class="table .table-hover">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">System</th>
<th scope="col">Created</th>
<th scope="col">Owner</th>
<th scope="col">Notes</th>
</tr>
</thead>
<tbody>
@foreach (var bookmark in Model.Bookmarks.Where(x => x.FolderId == folder.FolderId))
{
<tr>
<td> @bookmark.Label </td>
<td>
@{
var locationName = GetHumanReadable((int) bookmark.LocationId);
}
@*Todo: Make this open the system on dotlan.*@
@locationName
</td>
<td> @bookmark.Created </td>
<td>
@{
var charName = GetHumanReadable((int) bookmark.CreatorId);
}
@charName
</td>
<td> @bookmark.Notes </td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
}
</div>
}
</code></pre>
<h2>Controller:</h2>
<pre><code>public class BookmarkController : Controller
{
private readonly EVEStandardAPI _api;
private readonly IMemoryCache _memoryCache;
public BookmarkController(EVEStandardAPI api, IMemoryCache memoryCache)
{
_api = api;
_memoryCache = memoryCache;
}
public async Task<IActionResult> Index()
{
AuthDTO auth;
try
{
auth = User.EsiAuth();
}
catch (UnauthorizedAccessException)
{
return Content("You must auth with eve online.");
}
//Grab bookmarks
var personalBookmarkSection = await GetPersonalBookmarkSection();
List<int> universeIds = GetIdsForCaching(personalBookmarkSection);
var corporationBookmarkSection = await GetCorporationBookmarkSection();
universeIds.AddRange(GetIdsForCaching(corporationBookmarkSection));
//Query ESI for real name
var universeMapping = await ConvertIdToName(_memoryCache, universeIds);
var viewModel = new BookmarkViewModel(
personalBookmarkSection,
corporationBookmarkSection);// {UniverseMapping = universeMapping};
return View(viewModel);
}
private static List<int> GetIdsForCaching(BookmarkSection section)
{
//Grab the id's we want to find out the real name for
var universeIds = section.Bookmarks.DistinctBy(x => x.CreatorId).Select(x => x.CreatorId).ToList();
universeIds.AddRange(section.Bookmarks.DistinctBy(x => x.LocationId).Select(x => x.LocationId));
return universeIds;
}
private async Task<BookmarkSection> GetPersonalBookmarkSection()
{
var bookmarks = await _api.Bookmarks.ListBookmarksV2Async(User.EsiAuth());
var folders = await _api.Bookmarks.ListBookmarkFoldersV2Async(User.EsiAuth());
var section = new BookmarkSection(folders.Model, bookmarks.Model);
return section;
}
private async Task<BookmarkSection> GetCorporationBookmarkSection()
{
var auth = User.EsiAuth();
var charInfo = await _api.Character.GetCharacterPublicInfoV4Async(auth.CharacterId);
var bookmarks = await _api.Bookmarks.ListCorporationBookmarksV1Async(auth, charInfo.Model.CorporationId);
var folders = await _api.Bookmarks.ListCorporationBookmarkFoldersV1Async(auth, charInfo.Model.CorporationId);
var section = new BookmarkSection(folders.Model, bookmarks.Model);
return section;
}
/// <summary>
/// Pair Id's and their real name
/// </summary>
/// <param name="memoryCache"></param>
/// <param name="universeIds"></param>
/// <returns></returns>
private async Task<Dictionary<int, UniverseIdsToNames>> ConvertIdToName(IMemoryCache memoryCache, List<int> universeIds)
{
if (!memoryCache.TryGetValue(MemoryCacheKeys.UniverseMapping, out Dictionary<int, UniverseIdsToNames> universeMapping))
{
universeMapping = new Dictionary<int, UniverseIdsToNames>();
memoryCache.Set(MemoryCacheKeys.UniverseMapping, universeMapping, new MemoryCacheEntryOptions
{
Priority = CacheItemPriority.NeverRemove
});
}
foreach (var id in universeIds)
{
if (universeMapping.ContainsKey(id) == false)
{
universeMapping.Add(id, null);
}
}
var idsToQuery = new List<int>();
if (universeMapping.Any(x => x.Value == null))
{
foreach (var kvp in universeMapping)
{
if (kvp.Value == null)
{
idsToQuery.Add(kvp.Key);
}
}
}
if (idsToQuery.Count > 0)
{
var affiliation = await _api.Universe.GetNamesAndCategoriesFromIdsV3Async(idsToQuery);
foreach (var mapping in affiliation.Model)
{
universeMapping[mapping.Id] = mapping;
}
}
return universeMapping;
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:28:26.223",
"Id": "220415",
"Score": "1",
"Tags": [
"c#",
"asp.net",
"cache",
"asp.net-mvc-5"
],
"Title": "Bookmark controller with IMemoryCache"
} | 220415 |
<p>You are given a square matrix <span class="math-container">\$A \in \mathbb{ N}^{n,n}\$</span>, this number contains integers from <span class="math-container">\$1\$</span> to <span class="math-container">\$n^2\$</span>. The task is to compute the minimal cost, to change this square into a perfect square. A perfect square is a Matrix, such that every row, column and (full) diagonal add up to a magic number. The Matrix is limited by containing each number from <span class="math-container">\$1\$</span> to <span class="math-container">\$n^2\$</span>
<strong><em>exactly</em></strong> once. </p>
<p>E.g.: </p>
<p><span class="math-container">$$M = \begin{bmatrix}4\,\, 9\,\, 2 \\ 3 \,\,5\,\,7 \\ 8 \,\,1\,\,6\end{bmatrix}$$</span></p>
<p><span class="math-container">\$M\$</span> is a perfect square.</p>
<p>To change <span class="math-container">\$A\$</span> into a perfect square, you are allowed to change every number freely. However this increases the cost by <span class="math-container">\$c_{n+1} = c_{n} + |m_{i,j} - a|\$</span>, where <span class="math-container">\$a\$</span> is the new number.</p>
<p>It turns out, by the way, that the magic number is always:</p>
<p><span class="math-container">$$m = \frac{n\cdot (n^2+1)}{2}$$</span></p>
<p>Example of computing the cost:</p>
<p><span class="math-container">$$f(\begin{bmatrix}3\,\, 7\,\, 6 \\
9\,\, 5\,\, 1 \\
4\,\, 3\,\, 8\end{bmatrix}) = 1$$</span> If we change s[1][1] to 2 and s[1][3] to 6, we get a perfect square. The cost is 2-1 = 1;</p>
<p><strong>Compute the minimal cost for n = 3:</strong></p>
<p>This implementation solves the problem, but I have needed to realize that there are only 8 perfect squares for n = 3. </p>
<pre><code>int formingMagicSquare(size_t s_rows, const int** s) {
long long cost = -1;
if(s_rows == 3){
cost = LLONG_MAX;
const int perfect_squares[8][3][3] = {
{{2,7,6},{9,5,1},{4,3,8}},
{{4,3,8},{9,5,1},{2,7,6}},
{{6,1,8},{7,5,3},{2,9,4}},
{{2,9,4},{7,5,3},{6,1,8}},
{{8,3,4},{1,5,9},{6,7,2}},
{{6,7,2},{1,5,9},{8,3,4}},
{{4,9,2},{3,5,7},{8,1,6}},
{{8,1,6},{3,5,7},{4,9,2}}
};
for(int k = 0; k < 8; k++){
long long cost4_this_operation = 0;
for(int i = 0; i < 3;i++){
for(int j = 0; j < 3; j++){
long long diff = perfect_squares[k][i][j] - s[i][j];
cost4_this_operation += ((diff < 0) ? -diff : diff);
}
}
if(cost4_this_operation < cost)cost = cost4_this_operation;
}
}
return cost;
}
</code></pre>
<p>I have more questions about this code and I am not sure if I am allowed to ask them here because they ask for better ways to do this.
However, I have specific questions:</p>
<ol>
<li>How do you return properly if the program cannot solve a certain case?</li>
<li><p>Can you calculate the absolute amount better than:</p>
<pre><code>long long diff = perfect_squares[k][i][j] - s[i][j];
cost4_this_operation += ((diff < 0) ? -diff : diff);
</code></pre></li>
<li>The for-Looping seems not to be proper. How would you do that?</li>
</ol>
<p>Thank you.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T14:33:55.603",
"Id": "425885",
"Score": "1",
"body": "Please include the language you're using in the tags. Looks like C?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T15:11:59.223",
"Id": "425889",
"Score": "0",
"body": "You have put the full text of the problem requiring a solution in the question, is there a link that you can provide to the question (is this a programming challenge of some sort)? **The specific question questions may put this question off-topic, especially specific questions 1 and 3.**"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T15:19:52.327",
"Id": "425890",
"Score": "0",
"body": "I delete question 3. I think question 1 is fine, since this only a sidenote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T15:55:37.947",
"Id": "425891",
"Score": "0",
"body": "Your example looks wrong - it already has `6` in the right place. Should it be `2`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:00:48.743",
"Id": "425892",
"Score": "0",
"body": "yes. Thank you."
}
] | [
{
"body": "<ul>\n<li><p>Since the function is hardwired to 3x3 matrices, it would make sense to pass a 3x3 matrix as an argument:</p>\n\n<pre><code>int formingMagicSquare(const int s[3][3])\n</code></pre>\n\n<p>This way you will not worry about what to do if <code>s_rows != 3</code>.</p></li>\n<li><p><code>stdlib</code> provides <code>int abs(int)</code>.</p></li>\n<li><p>The line</p>\n\n<pre><code> if(cost4_this_operation < cost)cost = cost4_this_operation;\n</code></pre>\n\n<p>better be split into</p>\n\n<pre><code> if(cost4_this_operation < cost) {\n cost = cost4_this_operation;\n }\n</code></pre>\n\n<p>Even better, make a <code>static inline int min(int, int)</code> function.</p></li>\n<li><p>I see nothing wrong with the loops.</p></li>\n<li><p>Of course, the solution is not scalable for larger dimensions. </p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:18:21.780",
"Id": "425910",
"Score": "0",
"body": "is not that inline C++? why should I split?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:28:27.777",
"Id": "425912",
"Score": "1",
"body": "@TVSuchty `inline` is C, see 6.7.4 Function Specifiers part of the Standard. Split because long lines are hard to read and maintain."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:06:44.747",
"Id": "220423",
"ParentId": "220416",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220423",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T13:59:55.070",
"Id": "220416",
"Score": "2",
"Tags": [
"performance",
"c",
"combinatorics"
],
"Title": "Computing the cost for creating a perfect square (with N = 3)"
} | 220416 |
<p><strong>The task</strong>
is taken from <a href="https://leetcode.com/problems/min-stack/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Design a stack that supports push, pop, top, and retrieving the
minimum element in constant time.</p>
<p>push(x) -- Push element x onto stack.</p>
<p>pop() -- Removes the element on top of the stack.</p>
<p>top() -- Get the top element.</p>
<p>getMin() -- Retrieve the minimum element in the stack.</p>
<p><strong>Example</strong>:</p>
<p>MinStack minStack = new MinStack();</p>
<p>minStack.push(-2);</p>
<p>minStack.push(0);</p>
<p>minStack.push(-3);</p>
<p>minStack.getMin(); --> Returns -3.</p>
<p>minStack.pop();</p>
<p>minStack.top(); --> Returns 0.</p>
<p>minStack.getMin(); --> Returns -2.</p>
</blockquote>
<p><strong>My first solution</strong></p>
<pre><code>/**
* initialize your data structure here.
*/
var MinStack = function() {
this.repo = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if (!isNaN(x)) {
this.repo.push(x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
return this.repo.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.repo[this.repo.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
if (this.repo) {
const copy = this.repo.slice(0);
return copy.sort((a,b) => a - b)[0];
}
};
</code></pre>
<p><strong>My second solution</strong></p>
<pre><code>/**
* initialize your data structure here.
*/
var MinStack = function() {
this.repo = [];
this.minRepo = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
if (!isNaN(x)) {
if (!this.minRepo.length || x <= this.minRepo[0]) {
this.minRepo.unshift(x);
}
this.repo.push(x);
}
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
if (this.repo.pop() === this.minRepo[0]) {
this.minRepo.shift();
}
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.repo[this.repo.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
if (this.minRepo.length) {
return this.minRepo[0];
}
};
</code></pre>
<p>For the second solution I was thinking of adding the numbers not from the back (with <code>push</code>) but instead from the front (with <code>unshift</code>). The advantage is that I would need less operation inside the method top (<code>return this.repo[0]</code> would be sufficient - no need for calculating the last element with <code>this.repo.length - 1</code>). But I don't whether this would be "weird" and would mean too much "mental mapping" (the function is called <code>push</code> but I use a <code>shift</code> inside). </p>
| [] | [
{
"body": "<p>The <code>getMin</code> function is not constant. You need to keep track of the minimum value whenever you push or pop.</p>\n\n<p>Furthermore you should name your functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T18:30:17.377",
"Id": "425902",
"Score": "0",
"body": "In the first solution you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:08:03.590",
"Id": "425904",
"Score": "0",
"body": "In the second solution I keep track of the minimum value with every push and pop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T23:40:14.563",
"Id": "425925",
"Score": "0",
"body": "Yes, I meant in the first anser."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T18:27:52.917",
"Id": "220430",
"ParentId": "220419",
"Score": "3"
}
},
{
"body": "<h3>Inconsistent style</h3>\n\n<p>The <code>getMin</code> function checks if the stack is empty, and the <code>top</code> function doesn't.\nThis inconsistency is confusing.\nI'm not sure which way is better, but it's good to be consistent.</p>\n\n<h3>Unnecessary and over-eager input validation</h3>\n\n<p><code>push</code> checks if the parameter is a number, and quietly does nothing if it isn't.\nIf non-numbers should not be allowed, then it would be better to throw an exception than quietly ignore.\nIn any case, this check is not required by the exercise.</p>\n\n<h3>Naming</h3>\n\n<p>Instead of <code>repo</code>, it would be more natural to call it <code>stack</code>.\nWith the <code>push</code> and <code>pop</code> methods of JavaScript arrays,\nthe illusion is perfect.</p>\n\n<h3>Building from common building blocks</h3>\n\n<p>The second solution builds a secondary storage with the minimum values,\nand makes some effort to avoid duplicates.\nI'm not sure the extra effort is worth the added complexity.\nIt would be simpler to not try to avoid duplicates,\nand simply add the pair of current and minimum values on every push.\nThen, it becomes easy to see that an implementation is possible without reimplementing a stack: under the hood you can use a stack,\nand the public methods simply encapsulate the transformations necessary for the underlying storage of value pairs.</p>\n\n<pre><code>var MinStack = function() {\n this.stack = [];\n};\n\nMinStack.prototype.push = function(x) {\n const min = this.stack.length ? Math.min(this.getMin(), x) : x;\n this.stack.push([x, min]); \n};\n\nMinStack.prototype.pop = function() {\n this.stack.pop()[0];\n};\n\nMinStack.prototype.top = function() {\n return this.stack[this.stack.length - 1][0];\n};\n\nMinStack.prototype.getMin = function() {\n return this.stack[this.stack.length - 1][1];\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T06:26:21.517",
"Id": "425943",
"Score": "0",
"body": "Your solution requires more space, doesn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T08:24:01.353",
"Id": "425949",
"Score": "0",
"body": "@thadeuszlay it's on the same order of space complexity as yours (\\$O(n)\\$), but yes, on average it will use more space."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:26:50.420",
"Id": "220437",
"ParentId": "220419",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "220437",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T15:20:15.767",
"Id": "220419",
"Score": "5",
"Tags": [
"javascript",
"programming-challenge",
"comparative-review",
"ecmascript-6",
"stack"
],
"Title": "Create a min stack"
} | 220419 |
<p>The code below retrieves data from database. </p>
<p>Before the data is retrieved, a wait message is displayed. Once the data is retrieved, the message should be removed.</p>
<p>What would be the best place to execute the <code>remove_wait_message</code> function?</p>
<p>Currently it sits in <code>do_stuff_to_data</code>, but it does not seem logical, as those two functions are not in any way correlated.</p>
<pre><code> function main() {
function get_data() {
let url = 'http://localhost:8000/query_database'
fetch(url)
.then(response => response.json())
.then(json => do_stuff_to_data(json))
}
function do_stuff_to_data(json) {
remove_wait_message()
console.log(json)
}
function remove_wait_message() {
let wait_msg = document.getElementById('wait_message')
document.body.removeChild(wait_message)
}
get_data()
}
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T20:02:04.433",
"Id": "425997",
"Score": "0",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T07:13:53.323",
"Id": "426129",
"Score": "0",
"body": "@Edward: To be honest, I don't know what is wrong with my question then: the code is fully functional, I am only asking for help in refactoring it (moving function execution somewhere else)."
}
] | [
{
"body": "<p>In most cases, the line that's invoking the function call is the code that knows about the UI. So it's logical that it's done at the call site rather than elsewhere. For example:</p>\n\n<pre><code>// Define functionality in inert functions.\nconst getData = () => fetch(...).then(res => res.json())\n\nconst processData = () => { ... }\n\nconst showWaitMessage = () => { ... }\n\nchost hideWaitMessage = () => { ... }\n\n// When you actually want to do stuff, just call them. \nshowWaitMessage()\n\ngetData() \n .then(data => {\n hideWaitMessage()\n processData(data)\n })\n</code></pre>\n\n<p>In more structured frameworks like Angular, you'll have greater separation between UI code and logic code. You don't want to call UI functions in places that have no business with the UI at all.</p>\n\n<pre><code>// A class housing all the data fetching logic.\n// In this code, you'll have no (official/non-hacky) way to reach the UI.\n@Injectable({ ... })\nclass DataService {\n constructor(someHttpClient){\n this.someHttpClient = someHttpClient\n }\n getData(){\n return this.someHttpClient.fetch().then(r => r.json())\n }\n}\n\n// A class that handles the UI.\n@Component({ ... })\nclass YourComponent {\n constructor(dataService) {\n this.dataService = dataService\n }\n showWaitMessage() {\n ...\n }\n hideWaitMessage() {\n ...\n }\n processData() {\n ...\n }\n async doSomething(){\n this.showWaitMessage()\n const data = this.dataService.getData()\n this.hideWaitMessage()\n this.processData(data) \n }\n}\n</code></pre>\n\n<p>You can read more about this by researching on <a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Inversion of Control</a>. In a gist, you write small independent functions. Then some \"glue code\" just calls into these functions to compose a larger functionality. In the example above, <code>doSomething()</code> glues together <code>showWaitMessage</code>, <code>getData</code>, <code>hideWaitMessage</code> and <code>processData</code> while all four functions are unaware of each other.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:18:02.350",
"Id": "220424",
"ParentId": "220420",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220424",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T15:26:36.383",
"Id": "220420",
"Score": "-1",
"Tags": [
"javascript"
],
"Title": "Fetch API - how to perform an action once data is retrieved, but before doing anything with the data?"
} | 220420 |
<p>This script is a subset of a larger script where I have the output of many test simulations in the form of CSVs. Each file starts with the model name and includes the number of elements in my file. For example, <code>edge_16elem_out.csv</code> would be a first-order model (edge) with 16 elements. Another example would be <code>edge3_1024elem_out.csv</code>. I have created several helper functions and am curious if there are ways to improve this code. I am using Python 2.7.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import numpy as np
import glob
import os
import re
def k(x, q=1200, g=1, l=11, k=3, t0=300):
"""Analytic Computation - Equation can be found in ./heat_source_bar.i"""
return ((q - np.exp(-g * l) * x * q * g - np.exp(-g * x) * q) / (k * g)) + t0
def slope(x, y):
"""Computes slope in log-log terms"""
return (y.diff() / x.diff()).fillna(0)
def compute_error(analytic, simulation):
"""Error Computation - calculates a percentage from simulated answer to analytical answer"""
return np.log10(np.abs((analytic - simulation) / analytic))
def get_basename(fp):
"""Fetches basename of a given file path w/ file extension truncated"""
return os.path.splitext(os.path.basename(fp))[0]
def get_model_num(fp):
"""Extracts number of radial elements from given file path
(Ex. edge3_16elem_out.csv will return 16)"""
var = str(get_basename(fp).split('_')[1])
return int(re.search(r'\d+', var).group(0))
def get_model_type(fp, prefix):
"""Helper function to be able to get different model
types by determining model type from file path prefix"""
return filter(lambda x: get_basename(x).startswith(prefix), fp)
def read_assign(fp, model_id):
"""Read in csv and create column assigning model number as column"""
return pd.read_csv(fp).assign(model_id=model_id)
def main():
working_dir = os.path.abspath('.')
file_paths = glob.glob(os.path.join(working_dir, '*_out.csv'))
edge_files = get_model_type(file_paths, 'edge_')
edge_ids = map(get_model_num, edge_files)
edge_sol = (pd.concat(map(read_assign, edge_files, edge_ids))
.sort_values('model_id')
.query('time == 1')
.assign(points = [5.5 for x in range(11)])
.assign(t_sol = lambda x: k(x.points)))
edge_err = (edge_sol
.assign(t_err = compute_error(edge_sol.t_sol, edge_sol.point),
log_model_id = np.log10(1/edge_sol.model_id))
.assign(slope = lambda x: slope(x.log_model_id, x.t_err)))
edge_err.to_csv('edge_err.csv')
if __name__ == '__main__':
main()
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:47:50.097",
"Id": "220427",
"Score": "4",
"Tags": [
"python",
"python-2.x",
"file-system",
"csv",
"pandas"
],
"Title": "Combining CSV files of simulation results"
} | 220427 |
<p>I've developed a program in Python that calculates the lowest possible costing path between two points in a matrix, including the values contained in the start and finish cells. The code is below. Once the matrix gets larger than 4×4, it becomes very slow. Are there any obvious problems with my code (recursive method). I'm wondering if this can be improved before looking at other non-recursive approaches.</p>
<pre><code>def legal_moves(rows,cols,path, start):
list_moves = []
row_start = start[0]
col_start = start[1]
if col_start < cols:
if col_start == 0:
new_col_start = [col_start+1, col_start]
else:
new_col_start = [col_start+1, col_start-1, col_start]
else:
new_col_start = [col_start-1, col_start]
if row_start < rows:
if row_start == 0:
new_row_start = [row_start+1,row_start]
else:
new_row_start = [row_start+1, row_start-1, row_start]
else:
new_row_start = [row_start-1, row_start]
for row in new_row_start:
for col in new_col_start:
if row == row_start and col == col_start:
next
else:
if [row,col] not in path:
list_moves.append([row,col])
return list_moves
def min_path (rows,cols,path, start, end, path_sum=0):
if path == None:
path = [start]
else:
path = path [:] + [start]
row_index = start[0]
col_index = start[1]
if start == [0,1] and path_sum == 18:
print ("",end="")
path_sum += matrix[row_index][col_index]
if start == end:
list_paths.append(path)
list_sum.append (path_sum)
return
list_moves = legal_moves(rows,cols,path,start)
for move in list_moves:
min_path (rows,cols,path, move, end, path_sum)
matrix = [[1,4,6,7],
[3,5,7,8],
[19,2,12,11]]
cols = len(matrix[0]) - 1
rows = len(matrix) - 1
start = [2,3]
end = [0,0]
list_paths = []
list_sum = []
path = None
min_path(rows,cols,path,start,end)
print (f'From: {start} to {end} with a cost of: {min(list_sum)}')
print (f'They are: {list_paths[list_sum.index(min(list_sum))]}')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T21:01:51.127",
"Id": "425916",
"Score": "2",
"body": "You should have a look at [Dijkstra's algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T16:58:15.720",
"Id": "220428",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"matrix",
"pathfinding"
],
"Title": "Lowest cost path through elements in a matrix"
} | 220428 |
<p>For a homework assignment, I was asked to do <a href="https://www.codestepbystep.com/problem/view/java/arrays/2d/matrixSum" rel="nofollow noreferrer">this problem</a>. It worked, but it looks messy in my opinion. I want to know if this is the best way to accomplish this task, and if there can be any improvements made to this code, such as efficiency and code compactness. The assignment is explained below:</p>
<blockquote>
<p>Write a method named matrixSum that accepts as parameters two 2D
arrays of integers, treats the arrays as 2D matrices and adds them,
returning the result. The sum of two matrices A and B is a matrix C
where for every row i and column j, Cij = Aij + Bij. You may assume
that the arrays passed as parameters have the same dimensions.</p>
<p>A = { { 1, 2, 3 }, { 4, 4, 4 } }</p>
<p>B = { { 5, 5, 6 }, { 0, -1, 2 } }</p>
<p>maxtrixSum(a, b)
=> { { 6, 7, 9 }, { 4, 3, 6 } }</p>
</blockquote>
<p><strong>My Solution</strong></p>
<pre><code>public int[][] matrixSum(int[][] a, int[][] b) {
if(a.length == 0 || b.length == 0) { return new int[0][0]; }
int[][] sum = new int[a.length][a[0].length];
//Can use just `a` for length because a & b have the same dimensions
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[0].length; j++) {
sum[i][j] = a[i][j] + b[i][j];
}
}
return sum;
}
</code></pre>
| [] | [
{
"body": "<p>Your code is pretty much a straightforward textbook solution. Good job on handling the zero-size matrix case, so that <code>a[0].length</code> doesn't cause a crash.</p>\n\n<p>It's more conventional to put a space after flow-control keywords like <code>if</code> and <code>for</code>, so that they look less like function calls:</p>\n\n<pre><code>for (int i = 0; i < a.length; i++) {\n …\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:21:47.343",
"Id": "220434",
"ParentId": "220429",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "220434",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T18:25:27.290",
"Id": "220429",
"Score": "2",
"Tags": [
"java",
"matrix",
"homework"
],
"Title": "Sum of Two Matrices"
} | 220429 |
<p>Here is my <code>std::vector</code> implementation so far. It's not yet complete (it's missing the constructors), but I hope you can leave some feedback!</p>
<pre><code>#pragma once
#include <memory>
#include <utility>
#include <type_traits>
#include <stdexcept>
#include "kmemory.h"
namespace kstd
{
namespace detail
{
template<typename T, typename = void>
struct allocator_base
{
public:
T get_allocator() const noexcept
{
return allocator_;
}
protected:
T& allocator() noexcept
{
return allocator_;
}
const T& allocator() const noexcept
{
return allocator_;
}
private:
T allocator_;
};
template<typename T>
struct allocator_base<T, std::enable_if_t<!std::is_final_v<T>>> : T
{
public:
T get_allocator() const noexcept
{
return allocator();
}
protected:
T& allocator() noexcept
{
return *static_cast<T*>(this);
}
const T& allocator() const noexcept
{
return *static_cast<T*>(this);
}
};
}
template<typename T, typename Allocator = std::allocator<T>>
class vector : public detail::allocator_base<Allocator>
{
public:
// typedefs
using value_type = T;
using allocator_type = Allocator;
using pointer = typename std::allocator_traits<Allocator>::pointer;
using const_pointer = typename std::allocator_traits<Allocator>::const_pointer;
using reference = value_type&;
using const_reference = const value_type&;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using iterator = pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// constructors
// iterators
iterator begin() noexcept
{
return data_;
}
const_iterator begin() const noexcept
{
return data_;
}
iterator end() noexcept
{
return data_ + size_;
}
const_iterator end() const noexcept
{
return data_ + size_;
}
reverse_iterator rbegin() noexcept
{
return data_ + size_;
}
const_reverse_iterator rbegin() const noexcept
{
return data_ + size_;
}
reverse_iterator rend() noexcept
{
return data_;
}
const_reverse_iterator rend() const noexcept
{
return data_;
}
const_iterator cbegin() const noexcept
{
return data_;
}
const_iterator cend() const noexcept
{
return data_ + size_;
}
const_reverse_iterator crbegin() const noexcept
{
return data_ + size_;
}
const_reverse_iterator crend() const noexcept
{
return data_;
}
// capacity
bool empty() const noexcept
{
return !size_;
}
size_type size() const noexcept
{
return size_;
}
size_type capactiy() const noexcept
{
return capacity_;
}
void resize(size_type sz)
{
}
void resize(size_type sz, const T& value)
{
}
void reserve(size_type cap)
{
reserve_offset(cap, size_, 0);
}
void shrink_to_fit()
{
return;
}
// element access
reference operator[](size_type n)
{
return data_[n];
}
const_reference operator[](size_type n) const
{
return data_[n];
}
reference at(size_type n)
{
if (n >= size_)
throw std::out_of_range("n is out of range");
return data_[n];
}
const_reference at(size_type n) const
{
return at(n);
}
reference front()
{
return *data_;
}
const_reference front() const
{
return *data_;
}
reference back()
{
return data_[size_ - 1];
}
const_reference back() const
{
return data_[size_ - 1];
}
// data access
T* data() noexcept
{
return data_;
}
const T* data() const noexcept
{
return data_;
}
// modifiers
template<typename... Args>
reference emplace_back(Args&&... args)
{
return *emplace(end(), std::forward<Args>(args)...);
}
void push_back(const T& value)
{
emplace_back(value);
}
void push_back(T&& value)
{
emplace_back(std::move(value));
}
void pop_back()
{
if (!std::is_trivially_destructible_v<T>)
back().~T();
--size_;
}
template<typename... Args>
iterator emplace(const_iterator pos, Args&&... args)
{
size_type emplaced_pos = pos - begin();
if (!shift_elements_right(emplaced_pos, 1) && emplaced_pos < size_)
*(data_ + emplaced_pos) = T(std::forward<Args>(args)...);
else
new (data_ + emplaced_pos) T(std::forward<Args>(args)...);
++size_;
return data_ + emplaced_pos;
}
iterator insert(const_iterator pos, const T& value)
{
return emplace(pos, value);
}
iterator insert(const_iterator pos, T&& value)
{
return emplace(pos, std::move(value));
}
iterator insert(const_iterator pos, size_type count, const T& value)
{
size_type emplaced_pos = pos - begin();
if (!shift_elements_right(emplaced_pos, count))
{
size_type uninit_to_copy = std::clamp((emplaced_pos + count) - size_, size_type(0), count);
detail::fill_range_optimal(data_ + emplaced_pos, data_ + emplaced_pos + count - uninit_to_copy, value);
detail::uninitialized_fill_range_optimal(data_ + emplaced_pos + count - uninit_to_copy, data_ + emplaced_pos + count, value);
}
else
{
detail::uninitialized_fill_range_optimal(data_ + emplaced_pos, data_ + emplaced_pos + count, value);
}
size_ += count;
return data_ + emplaced_pos;
}
template<typename InputIt>
iterator insert(const_iterator pos, InputIt first, InputIt last)
{
size_type emplaced_pos = pos - begin();
size_type count = last - first;
if (!shift_elements_right(emplaced_pos, count))
{
size_type uninit_to_copy = std::clamp((emplaced_pos + count) - size_, size_type(0), count);
detail::copy_range_optimal(first, last - uninit_to_copy, data_ + emplaced_pos);
detail::uninitialized_copy_range_optimal(last - uninit_to_copy, last, data_ + emplaced_pos + count - uninit_to_copy);
}
else
{
detail::uninitialized_copy_range_optimal(first, last, data_ + emplaced_pos);
}
size_ += count;
return data_ + emplaced_pos;
}
iterator insert(const_iterator pos, std::initializer_list<T> list)
{
return insert(pos, list.begin(), list.end());
}
iterator erase(const_iterator first, const_iterator last)
{
size_type count = last - first;
size_type pos = first - begin();
detail::move_range_optimal(data_ + pos + count, data_ + size_, data_ + pos);
std::destroy(data_ + size_ - count, data_ + size_);
size_ -= count;
return data_ + pos + 1;
}
iterator erase(const_iterator pos)
{
return erase(pos, pos + 1);
}
void clear() noexcept
{
erase(begin(), end());
}
private:
bool shift_elements_right(size_type pos, size_type count)
{
bool realloc = reserve_offset(size_ + count, pos, count);
if (!realloc)
{
size_type uninit_to_move = std::clamp(size_ - pos, size_type(0), count);
detail::uninitialized_move_range_optimal(data_ + size_ - uninit_to_move, data_ + size_, data_ + size_ + count - uninit_to_move);
detail::move_range_optimal_backward(data_ + pos, data_ + size_ - uninit_to_move, data_ + pos + count);
}
return realloc;
}
bool reserve_offset(size_type cap, size_type pos, size_type count)
{
if (cap <= capacity_)
return false;
if (data_ != nullptr)
{
pointer new_data = std::allocator_traits<Allocator>::allocate(allocator(), cap);
detail::uninitialized_move_range_optimal(data_, data_ + pos, new_data);
detail::uninitialized_move_range_optimal(data_ + pos, data_ + size_, new_data + pos + count);
if constexpr (!std::is_trivial_v<T>)
std::destroy(data_, data_ + size_);
std::allocator_traits<Allocator>::deallocate(allocator(), data_, capacity_);
data_ = new_data;
}
else
{
data_ = std::allocator_traits<Allocator>::allocate(allocator(), cap);
}
capacity_ = cap;
return true;
}
using detail::allocator_base<Allocator>::allocator;
pointer data_ = nullptr;
size_type size_ = 0;
size_type capacity_ = 0;
};
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:23:46.377",
"Id": "425906",
"Score": "2",
"body": "Why don't you complete the constructors before asking for a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:26:52.180",
"Id": "425907",
"Score": "0",
"body": "@200_sucess because the constructors are trivial to the implementation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:37:11.680",
"Id": "425908",
"Score": "2",
"body": "Then why don't you include them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:40:38.447",
"Id": "425909",
"Score": "0",
"body": "@200_sucess because as mentioned previously, it's not complete"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T05:19:25.743",
"Id": "425935",
"Score": "0",
"body": "What's `\"kmemory.h\"`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T05:21:32.553",
"Id": "425936",
"Score": "0",
"body": "@L.F. it just contains all the move range algorithms"
}
] | [
{
"body": "<p>Wow, this is a large amount of code. I appreciate your work. I can't provide a complete review by now, so this answer will be updated gradually.</p>\n\n<p>I assume C++17. I use <a href=\"https://timsong-cpp.github.io/cppwp/n4659/\" rel=\"nofollow noreferrer\">N4659</a> as a reference.</p>\n\n<p>You don't provide your code for <code>\"kmemory.h\"</code>. In a <a href=\"https://codereview.stackexchange.com/questions/220433/stdvector-implementation?noredirect=1#comment425936_220433\">comment</a>, you mentioned that it just contains the move range algorithms. I can't review it, so I will assume that it is correct.</p>\n\n<h1>Bugs</h1>\n\n<ol>\n<li><p><code>pointer</code> (i.e., <code>typename std::allocator_traits<Allocator>::pointer</code>) may not be a random-access iterator. I would suggest directly using <code>T*</code> for <code>iterator</code>. Similarly for <code>const_iterator</code>.</p>\n\n<pre><code>using iterator = T*;\nusing const_iterator = const T*;\n</code></pre></li>\n<li><p>You did not implement constructors. You say they are trivial to the implementation and they are not complete, but implementing some of them are actually quite a challenge (for example, the copy and move operations with 100% conforming behavior) ;-)</p></li>\n<li><p>Your <code>const</code> version of <code>at</code> is an infinite loop.</p>\n\n<pre><code>const_reference at(size_type n) const\n{\n return at(n);\n}\n</code></pre></li>\n</ol>\n\n<h1>Suggestions</h1>\n\n<ol>\n<li><p>Your <code>allocator_base</code> attempts to implement the empty-base optimization for derivable-from allocators. This is a good idea.</p>\n\n<p>For me, the deriving version makes more sense as the primary template because most allocators should sensibly be derivable from. Moreover, you use <code>enable_if</code> for dispatch. That's a bit overkill. I would change your code to:</p>\n\n<pre><code>// deriving version\ntemplate <typename T, bool>\nstruct allocator_base { /* ... */ };\n\n// non-deriving version\ntemplate <typename T>\nstruct allocator_base<T, std::is_final_v<T>> { /* ... */ };\n</code></pre></li>\n<li><p><code>shrink_to_fit</code> is a non-binding request, but is it really a good idea to make it a no-op? ;-) It is actually trivial to implement.</p></li>\n<li><p>In <code>pop_back</code>, you use a runtime <code>if</code> to determine the trivial destructibility of the element type. Why not decide it at compile time with the help of <code>if constexpr</code>?</p>\n\n<pre><code>if constexpr (!std::is_trivially_destructible_v<T>)\n back().~T();\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T05:46:57.437",
"Id": "425938",
"Score": "0",
"body": "Thank you for the suggestion!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T05:49:19.090",
"Id": "425939",
"Score": "0",
"body": "Also, good idea with the allocator_base suggestion :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T23:38:31.730",
"Id": "426018",
"Score": "0",
"body": "Hm, better avoid deriving if either final or not empty."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T05:40:32.630",
"Id": "220448",
"ParentId": "220433",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T19:08:25.790",
"Id": "220433",
"Score": "2",
"Tags": [
"c++"
],
"Title": "std::vector implementation"
} | 220433 |
<p>There is a big Pull Request in <a href="https://github.com/sabricot/django-elasticsearch-dsl/pull/136" rel="nofollow noreferrer">django-elasticsearch-dsl</a>. Can anyone take some time and review the pull request?
We are changing from python <code>MetaClass</code> to a decorator <code>@registry.register_document</code>. Will it be a good approach?</p>
<p>It will be something like this</p>
<pre><code> @registry.register_document
class CarDocumentDSlBaseField(DocType):
position = GeoPoint()
class Django:
model = Car
fields = ['name', 'price']
class Index:
name = 'car_index'
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T20:00:24.960",
"Id": "425996",
"Score": "1",
"body": "Welcome to Code Review! Unfortunately your question is off-topic as of now, as the code to be reviewed must be [present in the question.](//codereview.meta.stackexchange.com/q/1308) Please add the code you want reviewed in your question. Thanks!"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:23:31.017",
"Id": "220436",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"django",
"elasticsearch"
],
"Title": "Python Elasticserch DSL integration with Django"
} | 220436 |
<p>So i took even more suggestions and improved the code from <a href="https://codereview.stackexchange.com/questions/220360/improved-snake-game-in-sfml-c">this question</a>.
Some of the suggestions i wasn't able to implement simply because of my "newbieness" in c++ programming</p>
<h1>main.cpp</h1>
<pre><code>#include "app.h"
int main() {
// Window aspect ratio is always 4:3, so it only takes
// a value that is then used as the screen width.
// The screen height is calculated in the Game::app class constructor.
Game::app game(800, L"Test");
game.start();
}
</code></pre>
<h1>app.h</h1>
<pre><code>#pragma once
#include <SFML/Graphics.hpp>
#include "Board.h"
namespace Game {
class app : public sf::Drawable {
public:
app(int windowWidth, const wchar_t* name);
~app() = default;
// Runs the app
void start();
void end();
private:
// MEMBER VARIABLES
const float common_divisor;
bool m_iscrashed;
Board board;
sf::RenderWindow window;
sf::Font arial;
// MEMBER FUNCTIONS
void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
void handleEvents();
void updateWindow();
};
}
</code></pre>
<h1>app.cpp</h1>
<pre><code>#include "app.h"
#include <iostream>
#include <thread>
#include <chrono>
Game::app::app(int windowWidth, const wchar_t* name)
: common_divisor{ static_cast<float>(windowWidth / Board::width) }, m_iscrashed{ false } {
const int windowHeight = windowWidth * 3 / 4;
if (windowHeight % 3 != 0)
std::wcout << L"Error! the window aspect ratio isn't 4:3.\n";
const char* font_path{ "res/fonts/arial.ttf" };
// Had to make it a normal string because
// the loadFromFile() func doesn't accept wide strings.
if (!arial.loadFromFile(font_path)) {
std::cout << "[ERROR]: Couldn't load font\nFile Path: " << font_path << '\n\n';
}
window.create(sf::VideoMode(windowWidth, windowHeight), name);
window.setFramerateLimit(5);
}
void Game::app::handleEvents() {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::TextEntered:
board.changeDirection(static_cast<char>(event.text.unicode));
}
}
}
void Game::app::draw(sf::RenderTarget& target, sf::RenderStates states) const {
for (size_t i = 0, h = Board::height; i < h; ++i) {
for (size_t j = 0, w = Board::width; j < w; ++j) {
Coord here{ j, i };
sf::RectangleShape rect;
rect.setSize({ common_divisor, common_divisor });
rect.setPosition({ common_divisor * j, common_divisor * i });
switch (board.at(here)) {
case Board::WALL:
target.draw(rect, states);
break;
case Board::SNAKE:
rect.setFillColor(sf::Color::Green);
target.draw(rect, states);
break;
case Board::FOOD:
rect.setFillColor(sf::Color::Red);
target.draw(rect, states);
}
}
}
// Draws the game score
sf::Text text;
text.setFont(arial);
text.setCharacterSize(static_cast<unsigned int>(common_divisor));
text.setPosition({ 0.0f, 0.0f });
text.setString("Score: " + std::to_string(board.score()));
text.setFillColor(sf::Color::Black);
target.draw(text, states);
}
// Updates the render window
void Game::app::updateWindow() {
if (m_iscrashed)
window.close();
window.clear(sf::Color::Black);
window.draw(*this);
window.display();
}
// Starts the app
void Game::app::start() {
while (window.isOpen()) {
handleEvents();
board.update(&m_iscrashed);
updateWindow();
}
end();
}
void Game::app::end() {
std::wcout << L"Game over!\nScore: " << board.score() << L'\n';
std::this_thread::sleep_for((std::chrono::milliseconds)3000);
}
</code></pre>
<h1>Board.h</h1>
<pre><code>#pragma once
#include "Snake.h"
class Board {
public:
Board();
~Board() = default;
void update(bool* iscrashed);
void changeDirection(char input);
char operator[](int i) const;
int score() const;
int at(Coord coord) const;
static constexpr int width = 20;
static constexpr int height = 15;
static enum Tile {
OPEN = 1,
WALL = 2,
SNAKE = 3,
FOOD = 4
};
private:
// MEMBER VARIABLES
Snake snake;
std::string map;
int m_score = 0;
// MEMBER FUNCTIONS
Coord openRandom(); // Finds a random open cell
bool place(Coord coord, Tile item); // Sets a cell a certain value
bool isEmpty(Coord coord) const;
};
</code></pre>
<h1>Board.cpp</h1>
<pre><code>#include "Board.h"
#include <random>
Board::Board()
: map(static_cast<size_t>(width * height), static_cast<char>(OPEN)) {
// Sets top and bottom walls
for (size_t i = 0; i < width; ++i) {
place({ i, 0 }, WALL);
place({ i, height - 1 }, WALL);
}
// Sets side walls
for (size_t j = 1; j < height - 1; ++j) {
place({ 0, j }, WALL);
place({ width - 1, j }, WALL);
}
place(snake.headLocation(), SNAKE);
place(snake.add(), SNAKE);
place(openRandom(), FOOD);
}
int Board::at(Coord coord) const {
return map[coord.y * width + coord.x];
}
bool Board::isEmpty(Coord coord) const {
return at(coord) == OPEN;
}
// Sets a cell a certain value
bool Board::place(Coord coord, Tile item) {
if (item != OPEN && !isEmpty(coord))
return false;
map[coord.y * width + coord.x] = item;
return true;
}
Coord Board::openRandom() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<unsigned int> disX(1, width - 2);
std::uniform_int_distribution<unsigned int> disY(1, height - 2);
Coord coord = { disX(gen), disY(gen) };
while (!isEmpty(coord)) {
coord = { disX(gen), disY(gen) };
}
return coord;
}
void Board::update(bool* iscrashed) {
auto newHead{ snake.moveHead() };
place(snake.follow(), OPEN);
switch (at(snake.headLocation())) {
case WALL:
case SNAKE:
*iscrashed = true;
break;
case FOOD:
place(snake.headLocation(), OPEN);
place(snake.add(), SNAKE);
m_score += 100;
place(openRandom(), FOOD);
}
place(newHead, SNAKE);
}
void Board::changeDirection(char input) {
snake.changeDirection(input);
}
char Board::operator[](int i) const { return map[i]; }
int Board::score() const { return m_score; }
</code></pre>
<h1>Snake.h</h1>
<pre><code>#pragma once
#include <vector>
#include "Coord.h"
class Snake {
public:
Snake();
~Snake() = default;
// Changes the dir value based on the input
void changeDirection(char input);
// Adds a piece to the snake and returns its location
Coord add();
size_t size();
/* Moves all pieces and returns
the previous position of last piece */
Coord follow();
Coord moveHead(); // Moves and returns position of new head
Coord headLocation() const;
private:
// MEMBER VARIABLES
struct Snake_segment
{
Coord current, previous;
};
enum direction {
UP = 0,
RIGHT,
DOWN,
LEFT
};
std::vector<Snake_segment> snakeContainer;
direction dir;
};
</code></pre>
<h1>Snake.cpp</h1>
<pre><code>#include "Snake.h"
// Initializes a two-piece snake
Snake::Snake()
: dir { RIGHT } {
Snake_segment head{ {10, 7}, {9, 7} };
snakeContainer.push_back(head);
--head.current.x;
snakeContainer.push_back(head);
}
Coord Snake::add() {
snakeContainer.push_back({
snakeContainer.back().previous,
snakeContainer.back().previous
});
return snakeContainer.back().current;
}
size_t Snake::size() {
return snakeContainer.size();
}
// Changes the direction based on input (BUGGED)
void Snake::changeDirection(char input) {
switch (input) {
case 'w':
if (dir != DOWN) dir = UP;
break;
case 'd':
if (dir != LEFT) dir = RIGHT;
break;
case 's':
if (dir != UP) dir = DOWN;
break;
case 'a':
if (dir != RIGHT) dir = LEFT;
}
}
// All the pieces follow the head
Coord Snake::follow() {
auto it = snakeContainer.begin();
for (auto prev = it++; it != snakeContainer.end(); ++it, ++prev) {
it->previous = it->current;
it->current = prev->previous;
}
return snakeContainer.back().previous;
}
Coord Snake::moveHead() {
snakeContainer[0].previous = snakeContainer[0].current;
switch (dir) {
case UP:
--snakeContainer.front().current.y;
break;
case RIGHT:
++snakeContainer.front().current.x;
break;
case DOWN:
++snakeContainer.front().current.y;
break;
case LEFT:
--snakeContainer.front().current.x;
}
return snakeContainer.front().current;
}
Coord Snake::headLocation() const { return snakeContainer.front().current; }
</code></pre>
<h1>Coord.h</h1>
<pre><code>#pragma once
struct Coord {
unsigned int x, y;
};
</code></pre>
| [] | [
{
"body": "<p><strong>Don't Ignore Warning Messages</strong><br>\nPlease compile using the -Wall compiler switch that provides all warning messages.</p>\n\n<p>This code in Board.h generates a warning message:</p>\n\n<pre><code>static enum Tile {\n OPEN = 1,\n WALL = 2,\n SNAKE = 3,\n FOOD = 4\n};\n</code></pre>\n\n<p>The keyword <code>static</code> is ignored in this case, why are you trying to make an enum static?</p>\n\n<p><strong>Style and How it Effects Maintainability</strong><br>\nChanging the coding style can improve readability and maintainability of the code.</p>\n\n<p><em>Suggested Style Change 1</em><br>\nPut open braces (<code>{</code>) on a new line. This improves readability by clearly showing where a code block starts and ends.</p>\n\n<p>Example 1:\nCurrently the function <code>app::draw()</code> looks like this:</p>\n\n<pre><code>void Game::app::draw(sf::RenderTarget& target, sf::RenderStates states) const {\n\n for (size_t i = 0, h = Board::height; i < h; ++i) {\n for (size_t j = 0, w = Board::width; j < w; ++j) {\n\n Coord here{ j, i };\n sf::RectangleShape rect;\n rect.setSize({ common_divisor, common_divisor });\n rect.setPosition({ common_divisor * j, common_divisor * i });\n\n switch (board.at(here)) {\n case Board::WALL:\n target.draw(rect, states);\n break;\n\n case Board::SNAKE:\n rect.setFillColor(sf::Color::Green);\n target.draw(rect, states);\n break;\n\n case Board::FOOD:\n rect.setFillColor(sf::Color::Red);\n target.draw(rect, states);\n\n }\n\n }\n }\n\n // Draws the game score\n sf::Text text;\n text.setFont(arial);\n text.setCharacterSize(static_cast<unsigned int>(common_divisor));\n text.setPosition({ 0.0f, 0.0f });\n text.setString(\"Score: \" + std::to_string(board.score()));\n text.setFillColor(sf::Color::Black);\n\n target.draw(text, states);\n}\n</code></pre>\n\n<p>The code might be more readable for others if the code looked like this:</p>\n\n<pre><code>void Game::app::draw(sf::RenderTarget& target, sf::RenderStates states) const\n{\n for (size_t i = 0; i < Board::height; ++i)\n {\n for (size_t j = 0; j < Board::width; ++j)\n {\n Coord here{ j, i };\n sf::RectangleShape rect;\n rect.setSize({ common_divisor, common_divisor });\n rect.setPosition({ common_divisor * j, common_divisor * i });\n\n switch (board.at(here)) {\n case Board::WALL:\n target.draw(rect, states);\n break;\n\n case Board::SNAKE:\n rect.setFillColor(sf::Color::Green);\n target.draw(rect, states);\n break;\n\n case Board::FOOD:\n rect.setFillColor(sf::Color::Red);\n target.draw(rect, states);\n } \n }\n }\n\n // Draws the game score\n sf::Text text;\n text.setFont(arial);\n text.setCharacterSize(static_cast<unsigned int>(common_divisor));\n text.setPosition({ 0.0f, 0.0f });\n text.setString(\"Score: \" + std::to_string(board.score()));\n text.setFillColor(sf::Color::Black);\n\n target.draw(text, states);\n}\n</code></pre>\n\n<p>Due to the fact that the code leaves a blank line after each open brace this doesn't change the vertical spacing very much, anyone that reads the code can find the matching braces and knows the extent of each code block.</p>\n\n<p><em>Please Note that in the suggested version h = Board:height and w = Board:width are removed from the nest for loops, to improve readability as well, they are not necessary and they are confusing. It is better to avoid single character variable names. It might also be better to rename <code>i</code> and <code>j</code> as <code>x(Point)</code> and <code>y(Point)</code> or <code>h(eight)</code> and <code>w(idth)</code> to show that they are coordinates.</em></p>\n\n<p><em>Suggested Style Change 2</em><br>\nPut variable declarations on separate lines, it is easier to find variables and to add or delete them when a variable declared on a separate line.</p>\n\n<pre><code>struct Coord {\n unsigned int x, y;\n};\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>struct Coord {\n unsigned int x;\n unsigned int y;\n};\n</code></pre>\n\n<p>and</p>\n\n<pre><code> struct Snake_segment\n {\n Coord current, previous;\n };\n\nversus \n\n struct Snake_segment\n {\n Coord current;\n Coord previous;\n };\n</code></pre>\n\n<p><em>Suggested Style Change 3</em><br>\nPut braces (<code>{</code> and <code>}</code>) around all <code>then</code> clauses and <code>else</code> clauses. Quite often maintenance requires additional statements in either the <code>then</code> or <code>else</code> clauses. If the braces are not there then it is very easy to insert bugs into code by adding a statement.</p>\n\n<pre><code>void Game::app::updateWindow() {\n if (m_iscrashed)\n window.close();\n\n window.clear(sf::Color::Black);\n window.draw(*this);\n window.display();\n}\n</code></pre>\n\n<p>Versus</p>\n\n<pre><code>void Game::app::updateWindow()\n{\n if (m_iscrashed)\n {\n window.close();\n }\n\n window.clear(sf::Color::Black);\n window.draw(*this);\n window.display();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T12:30:33.930",
"Id": "220561",
"ParentId": "220438",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:28:14.420",
"Id": "220438",
"Score": "2",
"Tags": [
"c++",
"beginner",
"snake-game",
"sfml"
],
"Title": "Improved snake game in sfml (C++) #2"
} | 220438 |
<p><strong>My Code:
Connectivity(php)</strong></p>
<pre><code><?php
$conn=mysqli_connect("localhost","root","","webchat_data");
//if($conn)
//{
// echo "hi";
//}
if(!$conn){
die("CONNECTION FAILED" .mysqli_connect_error());
}
?>
</code></pre>
<p><strong>Signup</strong></p>
<pre><code><?php
include 'connectivity.php';
$uname=($_POST['uname']);
$email=($_POST['Email']);
$pass=($_POST['Password']);
$sql = "INSERT INTO `sign-up`(USERNAME,EMAIL_ID,PASSWORD) VALUES('$uname','$email','$pass')";
//$result=$conn->query($sql);
$result = mysqli_query($conn, $sql);
//$query=mysqli_query($conn,$sql);
header("Location:index.php");
?>
</code></pre>
<p>Someone told me that my query is good for a learner, but not for real world applications. Please make some recommendations to make this code more suitable for real world scenarios.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:57:28.073",
"Id": "425915",
"Score": "8",
"body": "Two words: [SQL injection](https://en.wikipedia.org/wiki/SQL_injection)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T21:02:48.177",
"Id": "425917",
"Score": "2",
"body": "Based on the size of the code this isn't really a question for code review, but there are 28 answers to this question at https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php. As @Glorfindel indicated this is wide open for a SQL Injection attack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T00:45:40.897",
"Id": "425926",
"Score": "0",
"body": "There's so many bad practices at play here that I don't even know where to start. You may want to learn more about PHP before working with real user data. Start with the [most common PHP questions](https://stackoverflow.com/questions/tagged/php?tab=Frequent) at [so]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T04:13:30.823",
"Id": "425932",
"Score": "0",
"body": "I would NOT like to register an account with the site that is using the posted code."
}
] | [
{
"body": "<p>The most important points:</p>\n\n<p>Never use User-Input in unsecured queries. Use prepared statements!</p>\n\n<p>Never save passwords in cleartext. A common form is hashing.</p>\n\n<p>Unfortunately, these topics would exceed this format. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T05:15:15.203",
"Id": "221522",
"ParentId": "220439",
"Score": "-1"
}
},
{
"body": "<p>Like it was said in the comments, this code needs not a review but just some basic practices. That said, good basic practices are a rare specimen in the wild, so you cannot be blamed, given the number of awful tutorials out there. Luckily I am the renowned collector of good practices and here you are</p>\n\n<h1>Connectivity</h1>\n\n<p>There ate many things that could be improved in your connectivity file. To name a few</p>\n\n<ul>\n<li>the connection character set must be configured to avoid issues with characters</li>\n<li>the proper error reporting mode for mysqli must be set</li>\n<li>the connection error smust be not bluntly echoed out</li>\n</ul>\n\n<p>All these issues are covered in my article <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">How to connect properly using mysqli</a>: so let's take the code from there:</p>\n\n<pre><code>$host = '127.0.0.1';\n$db = 'webchat_data';\n$user = 'root';\n$pass = '';\n$charset = 'utf8mb4';\n\nmysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\ntry {\n $conn = new mysqli($host, $user, $pass, $db);\n $conn->set_charset($charset);\n} catch (\\mysqli_sql_exception $e) {\n throw new \\mysqli_sql_exception($e->getMessage(), $e->getCode());\n}\n</code></pre>\n\n<h1>Password hashing</h1>\n\n<p>In two words, never store passwords in plain text. Use password_hash() function instead. This topic is thoroughly explained in the question: <a href=\"https://stackoverflow.com/questions/1581610/how-can-i-store-my-users-passwords-safely\">https://stackoverflow.com/questions/1581610/how-can-i-store-my-users-passwords-safely</a> </p>\n\n<h1>Prepared statements</h1>\n\n<p>Just never add a variable to SQL query directly, but mark its place with a question mark instead. Then bind the actual variable and finally call execute()</p>\n\n<p>In detail this matter is explained in this question: <a href=\"https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php\">https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php</a></p>\n\n<p>So here is your signup code reviewed</p>\n\n<pre><code><?php\ninclude 'connectivity.php';\n\n$uname = $_POST['uname'];\n$email = $_POST['Email'];\n$pass = password_hash($_POST['Password'], PASSWORD_DEFAULT);\n\n$sql = \"INSERT INTO `sign-up`(USERNAME,EMAIL_ID,PASSWORD) VALUES(?,?,?)\";\n$stmt = $conn->prepare($sql);\n$stmt->bind_param(\"sss\", $uname,$email,$pass);\n$stmt->execute();\n\nheader(\"Location:index.php\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-02T09:22:00.350",
"Id": "221529",
"ParentId": "220439",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:56:00.693",
"Id": "220439",
"Score": "1",
"Tags": [
"beginner",
"php",
"mysqli"
],
"Title": "Inserting a user sign-up record using mysqli"
} | 220439 |
<p><a href="https://leetcode.com/problems/implement-trie-prefix-tree/" rel="nofollow noreferrer">https://leetcode.com/problems/implement-trie-prefix-tree/</a></p>
<p>Please comment about performance and style.</p>
<blockquote>
<p>Implement a trie with insert, search, and startsWith methods.</p>
<p>Example:</p>
<pre><code>Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
</code></pre>
<p>Note:</p>
<p>You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.</p>
</blockquote>
<pre><code>using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TrieQuestions
{
/// <summary>
/// https://leetcode.com/problems/implement-trie-prefix-tree/
/// </summary>
[TestClass]
public class TrieTreeImplementation
{
[TestMethod]
public void TrieInsertTest()
{
Trie trie = new Trie();
trie.Insert("cat");
Assert.IsTrue(trie.Search("cat"));
}
[TestMethod]
public void TriePrefixSearchTest()
{
Trie trie = new Trie();
trie.Insert("cats");
Assert.IsTrue(trie.StartsWith("cat"));
}
[TestMethod]
public void OneLetterEdgeCaseTest()
{
Trie trie = new Trie();
trie.Insert("a");
Assert.IsTrue(trie.Search("a"));
Assert.IsTrue(trie.StartsWith("a"));
}
}
public class Trie
{
public TrieNode Head { get; set; }
/** Initialize your data structure here. */
public Trie()
{
Head = new TrieNode();
}
/** Inserts a word into the trie. */
public void Insert(string word)
{
var current = Head;
for (int i = 0; i < word.Length; i++)
{
if (!current.Edges.ContainsKey(word[i]))
{
current.Edges.Add(word[i], new TrieNode());
}
current = current.Edges[word[i]];
}
current.IsTerminal = true;
}
/** Returns if the word is in the trie. */
public bool Search(string word)
{
var current = Head;
for (int i = 0; i < word.Length; i++)
{
if (!current.Edges.ContainsKey(word[i]))
{
return false;
}
current = current.Edges[word[i]];
}
return current.IsTerminal == true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public bool StartsWith(string prefix)
{
var current = Head;
for (int i = 0; i < prefix.Length; i++)
{
if (!current.Edges.ContainsKey(prefix[i]))
{
return false;
}
current = current.Edges[prefix[i]];
}
return true;
}
}
public class TrieNode
{
public Dictionary<char, TrieNode> Edges { get; set; }
public bool IsTerminal { get; set; }
public TrieNode()
{
Edges = new Dictionary<char, TrieNode>();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T21:55:55.653",
"Id": "425919",
"Score": "0",
"body": "@wolfy no you can't. Why is it better? Maybe I can create a singleton or something close to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T23:33:49.543",
"Id": "425923",
"Score": "0",
"body": "@Wolfy: C# is a managed language, so I'm not sure what you're getting at?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T23:35:09.960",
"Id": "425924",
"Score": "0",
"body": "@PieterWitvoet ahh okay then nevermind, sorry I never used C# before..."
}
] | [
{
"body": "<p>In terms of data structures and algorithms this all looks pretty straightforward - not much to say about that.</p>\n\n<h3>Performance</h3>\n\n<ul>\n<li><code>Edges.ContainsKey</code> and <code>Edges[...]</code> each perform a lookup. <code>Edges.TryGetValue</code> lets you achieve the same with just a single lookup.</li>\n</ul>\n\n<h3>Design</h3>\n\n<ul>\n<li>I see no reason why <code>Trie.Head</code> should be public, and certainly not why it should have a public setter. That's poor encapsulation. Likewise, <code>TrieNode.Edges</code> should be get-only: you don't want outside code to be able to do <code>Edges = null;</code>.</li>\n<li><code>Search</code> and <code>StartsWith</code> do exactly the same thing, except for the final check. I'd move the duplicate code to a <code>TrieNode FindNode(string prefix)</code> helper method.</li>\n<li><code>TrieNode</code> is only used internally within <code>Trie</code>, so it makes sense to make it a private inner class.</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>You can remove <code>Trie</code>'s constructor if you initialize <code>Head</code> directly: <code>TrieNode Head { get; } = new TrieNode();</code>. The same goes for <code>TrieNode</code> and <code>Edges</code>.</li>\n<li>I'd replace those <code>for</code> loops with <code>foreach</code> loops, for clarity's sake.</li>\n<li>Comparing a boolean against <code>true</code> is unnecessary. Just do <code>return current.IsTerminal;</code></li>\n<li>I'd replace those default LeetCode comments with C#-specific xml comments.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T06:09:52.627",
"Id": "425941",
"Score": "0",
"body": "Thanks a lot. I didn't notice those"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T01:03:20.270",
"Id": "220442",
"ParentId": "220440",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "220442",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T20:56:59.223",
"Id": "220440",
"Score": "2",
"Tags": [
"c#",
"programming-challenge",
"trie"
],
"Title": "LeetCode: Trie Tree implementation, Search, Insert, startWith C#"
} | 220440 |
<p>I made a simple matrix program that prints some data..I want to know how to reduce amount of lines with some functions or whatever, because there is so much if-s,and for loops.</p>
<p>Tried to make functions but almost every for loop is different, so that did not work.</p>
<pre><code>#include <stdio.h>
main()
{
int i,j,m,n,sMain,sAnti,sCol,sMainUp,sMainDown,sAntiUp,sAntiDown;
int arr[30][30];
printf("What dimensions of matrix you want?(1 number) ");
scanf("%d",&m);
n = m;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
printf("Type elements: ");
printf("Element[%d,%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
printf("%d ",arr[i][j]);
}
printf("\n");
}
sMain = 0;
sAnti = 0;
sMainUp = 0;
sMainDown = 0;
sAntiUp = 0;
sAntiDown = 0;
for(i = 0; i < m; i++){
for(j = 0; j < n; j++){
if(i == j){
sMain += arr[i][j];
}
if((i + j) == (n - 1)){
sAnti += arr[i][j];
}
if(i < j){
sMainUp += arr[i][j];
}
if(i > j){
sMainDown += arr[i][j];
}
if((i + j) < (n - 1)){
sAntiUp += arr[i][j];
}
if((i + j) > (n - 1)){
sAntiDown += arr[i][j];
}
}
}
sCol = 0;
printf("Sum of what column you want? ");
scanf("%d",&j);
for(i = 0; i < m; i++){
sCol += arr[i][j];
}
printf("Sum of main diagonal: %d.\n",sMain);
printf("Sum of anti(counter) diagonal: %d.\n",sAnti);
printf("Sum above main diagonal: %d.\n",sMainUp);
printf("Sum under main diagonal: %d.\n",sMainDown);
printf("Sum above anti diagonal: %d.\n",sAntiUp);
printf("Sum under anti diagonal: %d.\n",sAntiDown);
printf("Sum of %d. column is: %d.",j,sCol);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T22:38:18.617",
"Id": "425921",
"Score": "0",
"body": "Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"."
}
] | [
{
"body": "<p><strong>Use Symbolic Constants Rather Than Numeric Constants</strong><br>\nIn most programming languages there is a way to define symbolic constants for numbers which makes the code more readable and easier to maintain. When raw numbers are used in code they are sometimes called Magic Numbers. Using Magic Numbers is generally considered a poor programming practice as discussed in <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">this stackoverflow question</a>. </p>\n\n<p>While the number 30 isn't quite a magic number since it is used as the maximum dimensions for the arrays in the matrix, it would be beneficial to anyone that needs to read or maintain the code to define symbolic constants for it. This would allow anyone who needs to edit the code to change the maximum dimensions to change 1 number in 1 place.</p>\n\n<p>In C this would be:</p>\n\n<pre><code>#define MAXIMUM_MATRIX_DIMENSION 30\n</code></pre>\n\n<p>and in C++ this would be:</p>\n\n<pre><code>const int MAXIMUM_MATRIX_DIMENSION = 30;\n</code></pre>\n\n<p>Then the integer array <code>arr</code> could be declared as:</p>\n\n<pre><code>int arr[MAXIMUM_MATRIX_DIMENSION][MAXIMUM_MATRIX_DIMENSION];\n</code></pre>\n\n<p>It then becomes very easy to change the maximum size of the matrix by only changing one line.</p>\n\n<p><strong>Meaningful Variable Names</strong><br>\nThe code might be easier to read if the variables <code>m</code> and <code>n</code> had more meaningful names, <code>m</code> could be <code>matrixDimension</code>. It's not really clear what <code>n</code> since it could also be `matrixDimension.</p>\n\n<p>The code might also be more readable if the variable <code>arr</code> had a more meaningful name, perhaps <code>baseMatrix</code>.</p>\n\n<p><strong>Declare Variables as Needed</strong><br>\nThe C programming language now allows variables to be created where they are needed, for instance the variables <code>i</code> and <code>j</code> could be created within the for loops</p>\n\n<pre><code> for(int i = 0; i < m; i++){\n for(int j = 0; j < n; j++){\n printf(\"Type elements: \");\n printf(\"Element[%d,%d]: \",i,j);\n scanf(\"%d\",&arr[i][j]);\n }\n }\n</code></pre>\n\n<p>The variables used to contain the sums should also be declared where they are initialized.</p>\n\n<p><strong>Error Checking on Input</strong><br>\nIt is always better to check user input before using it to perform actions in the code. For example checking the size of the dimensions before using it as a control value in the previous loop. If the user enters a number less than 1 or greater than 29 the program will experience undefined behavior and may crash. If the number is 0 or less the loops will never execute and if the number is greater than 29 matrix values will be written to memory that hasn't been allocated to the arrays.</p>\n\n<pre><code> m = -1;\n while (m < 1 or m >= MAXIMUM_MATRIX_DIMENSION)\n {\n printf(\"What dimensions of matrix you want?(1 integer number greater than 0 and less than %d) \", MAXIMUM_MATRIX_DIMENSION);\n scanf(\"%d\",&m);\n }\n</code></pre>\n\n<p><strong>Complexity</strong><br>\nThe function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n\n<p>There is also a programming principle called the Single Responsibility Principe that applies here. <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">The Single Responsibility Principle states</a>:</p>\n\n<blockquote>\n <p>Every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n\n<p>There are at least 4 possible functions in <code>main()</code> and possibly more. Each of the outer for loops is a good candidate for a function. The possible functions are: </p>\n\n<ul>\n<li>Get the dimensions of the matrix </li>\n<li>Get the individual values of the matrix </li>\n<li>Print the matrix </li>\n<li>Calculate and report the sums of the matrix columns, rows and diagonals (this could be 2 functions).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T16:01:33.977",
"Id": "220473",
"ParentId": "220441",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-17T22:19:23.027",
"Id": "220441",
"Score": "3",
"Tags": [
"c",
"matrix"
],
"Title": "Sums of columns and diagonals of a matrix"
} | 220441 |
<p>I have multiple distinct processes that need to access external resources that are rate limited. The processes are all async in nature and run in different applications. In times past I would just use SemaphoreSlim this design doesn't allow for that.</p>
<p>I've found several samples that seem to be half complete, or cut and paste into their code. This was derived from an existing post, but heavily modified to encompass the additional methods and to honor the cancellation token.</p>
<p>Any feedback would be appreciated.</p>
<pre><code>public sealed class SemaphoreAsync : IDisposable
{
Semaphore _semaphore;
private SemaphoreAsync(Semaphore sem) => _semaphore = sem;
public SemaphoreAsync(int initialCount, int maximumCount) => _semaphore = new Semaphore(initialCount, maximumCount);
public SemaphoreAsync(int initialCount, int maximumCount, string name) => _semaphore = new Semaphore(initialCount, maximumCount, name);
public SemaphoreAsync(int initialCount, int maximumCount, string name, out bool createdNew, SemaphoreSecurity semaphoreSecurity) => _semaphore = new Semaphore(initialCount, maximumCount, name, out createdNew, semaphoreSecurity);
public static SemaphoreAsync OpenExisting(string name)
{
return new SemaphoreAsync(Semaphore.OpenExisting(name));
}
public static SemaphoreAsync OpenExisting(string name, SemaphoreRights rights)
{
return new SemaphoreAsync(Semaphore.OpenExisting(name, rights));
}
public static bool TryOpenExisting(string name, out SemaphoreAsync result)
{
if (Semaphore.TryOpenExisting(name, out Semaphore semaphore))
{
result = new SemaphoreAsync(semaphore);
return true;
}
result = null;
return false;
}
public static bool TryOpenExisting(string name, SemaphoreRights rights, out SemaphoreAsync result)
{
if (Semaphore.TryOpenExisting(name, rights, out Semaphore semaphore))
{
result = new SemaphoreAsync(semaphore);
return true;
}
result = null;
return false;
}
public async Task<bool> WaitOne(TimeSpan timeout, CancellationToken ct)
{
DateTime start = DateTime.UtcNow;
while (!_semaphore.WaitOne(0))
{
ct.ThrowIfCancellationRequested();
if (DateTime.UtcNow < start.Add(timeout))
return false;
await Task.Delay(100, ct);
}
return true;
}
public async Task<bool> WaitOne(int millisecondsTimeout, CancellationToken ct)
{
DateTime start = DateTime.UtcNow;
while (!_semaphore.WaitOne(0))
{
ct.ThrowIfCancellationRequested();
if (millisecondsTimeout > 0)
{
if (DateTime.UtcNow < start.AddMilliseconds(millisecondsTimeout))
return false;
}
await Task.Delay(100, ct);
}
return true;
}
public async Task<bool> WaitOne(CancellationToken ct)
{
while (!_semaphore.WaitOne(0))
{
ct.ThrowIfCancellationRequested();
await Task.Delay(100, ct);
}
return true;
}
public SemaphoreSecurity GetAccessControl()
{
return _semaphore.GetAccessControl();
}
public int Release()
{
return _semaphore.Release();
}
public int Release(int releaseCount)
{
return _semaphore.Release(releaseCount);
}
public void SetAccessControl(SemaphoreSecurity semaphoreSecurity)
{
_semaphore.SetAccessControl(semaphoreSecurity);
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
if (_semaphore != null)
{
_semaphore.Dispose();
_semaphore = null;
}
}
disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-22T09:51:57.993",
"Id": "426429",
"Score": "0",
"body": "You could simply use a `ConcurrentDictionary` to store `SemaphoreSlim`s.\n`SemaphoreSlim` already supports async operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-23T16:13:40.780",
"Id": "426742",
"Score": "0",
"body": "The challenge is that SemaphoreSlim is limited to only a single application, we're specifically looking for async locking wrapper for the Semaphore class across multiple applications using a named semaphore (which SemaphoreSlim can't do)."
}
] | [
{
"body": "<p>You could use <a href=\"https://docs.microsoft.com/de-de/dotnet/api/system.threading.threadpool.registerwaitforsingleobject?view=netframework-4.7.1\" rel=\"nofollow noreferrer\"><code>ThreadPool.RegisterWaitForSingleObject</code></a> to register a callback when a the <code>WaitHandle</code> (<code>Semaphore</code> extends <code>WaitHandle</code>) is signaled.</p>\n\n<p>Together with a <code>TaskCompletionSource</code> you could completely remove all your wait loops.</p>\n\n<p>Example:</p>\n\n<pre><code>private async Task Run()\n{\n var semaphore = new Semaphore(0, 1);\n await AwaitWaitHandle(semaphore, CancellationToken.None, TimeSpan.FromMilliseconds(-1));\n}\n\nprivate Task AwaitWaitHandle(WaitHandle handle, CancellationToken cancellationToken, TimeSpan timeout)\n{\n var taskCompletionSource = new TaskCompletionSource<bool>();\n\n var reg = ThreadPool.RegisterWaitForSingleObject(handle,\n (state, timedOut) =>\n {\n // Handle timeout\n if (timedOut)\n taskCompletionSource.TrySetCanceled();\n\n taskCompletionSource.TrySetResult(true);\n }, null, timeout, true);\n\n // Handle cancellation\n cancellationToken.Register(() =>\n {\n reg.Unregister(handle);\n taskCompletionSource.TrySetCanceled();\n });\n\n return taskCompletionSource.Task;\n}\n</code></pre>\n\n<p>You could use <code>AwaitWaitHandle</code> in your <code>SemaphoreAsync</code> implementation to await the Semaphore.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T18:14:42.407",
"Id": "428030",
"Score": "0",
"body": "This is an interesting approach. I'm going to try this and the other method presented here. At first I thought there would be issues with multiple calls on the same CancellationToken but I noticed that you're unregistered it on the actual event."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-17T19:03:19.077",
"Id": "489156",
"Score": "0",
"body": "The `Unregister` should probably be given `null` parameter (we do not want ot signal anything upon cancellation). The `CancellationTokenRegistration` should be probably disposed on successful wait."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-14T13:33:25.630",
"Id": "533119",
"Score": "0",
"body": "`TimeSpan.FromMilliseconds(-1)` can be replaced with `Timeout.Infinite`. `CancellationToken.None` can be replaced with `default`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T14:37:57.037",
"Id": "221121",
"ParentId": "220444",
"Score": "4"
}
},
{
"body": "<p>Perhaps you could rewrite the wait operations to await both the semaphore or cancellation token.</p>\n\n<blockquote>\n<pre><code>public async Task<bool> WaitOne(TimeSpan timeout, CancellationToken ct)\n {\n DateTime start = DateTime.UtcNow;\n while (!_semaphore.WaitOne(0))\n {\n ct.ThrowIfCancellationRequested();\n if (DateTime.UtcNow < start.Add(timeout))\n return false;\n await Task.Delay(100, ct);\n }\n return true;\n }\n</code></pre>\n</blockquote>\n\n<pre><code> public async Task<bool> WaitOne(TimeSpan timeout, CancellationToken ct)\n {\n var success = await Task.Run(() =>\n {\n return WaitHandle.WaitTimeout\n != WaitHandle.WaitAny(new[] { _semaphore, ct.WaitHandle }, timeout);\n });\n ct.ThrowIfCancellationRequested();\n return success;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T15:04:37.803",
"Id": "221125",
"ParentId": "220444",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T03:13:06.070",
"Id": "220444",
"Score": "4",
"Tags": [
"c#",
"async-await"
],
"Title": "Named Semaphore with async calls"
} | 220444 |
<p>I have an API which I can't modify. I have to use data as it is.</p>
<p>I want to join data from two separate requests where the second request is based on data from the first one. </p>
<p>I have a working solution already but the code quality, in my opinion, is low so I want to know your opinion (and if you can provide: better, more reactive solution).</p>
<p>So, I have an <strong>order</strong> API that's receiving data:</p>
<p><code>/orders</code> response: </p>
<pre><code>[
{
id: 1,
clientId: 201,
// other data
},
{
id: 2,
clientId: 201,
},
{
id: 3,
clientId: 11,
}
]
</code></pre>
<p>In this response, I don't have data about the client name, so I have a second API where I can pass IDs of clients and then I got back:</p>
<p><code>/clientsData?ids=201,11</code> response: </p>
<pre><code>[
{
id:201,
name: "Jon Doe"
},
{
id: 11,
name: "Jack Sparrow"
}
]
</code></pre>
<p>So, now I have a working code but as mentioned, in the beginning, I'm feeling it can be done in a better way. Please, note that the request should be done in the correct order because I need clients IDs before I make a second API call.</p>
<p>Also, want to avoid making multiple (more than two [orders+clients]) requests to check client data.</p>
<p>Working code:</p>
<pre><code>
// API Call to get orders:
const result$ = this.http.get('/orders').pipe(
mergeMap(
orders => {
const ids = orders
.map(item => item.clientId)
.filter((v, i, a) => a.indexOf(v) === i) // remove duplicates
.join(','); // get client ids into one string
// Client IDs: 1,2,99,201
// API call to check IDs:
return this.http.get(`/clientsData?ids=${ids}`).pipe(
mergeMap(clientsData => {
// map over each client
clientsData.forEach(client => {
// then map over each order
orders.forEach(order => {
// and assign client name to order
if (order.clientId === client.id) {
order.clientName = client.name;
}
});
});
return of(orders); // observable
})
);
}
)
);
result$.subscribe(console.log);
</code></pre>
<p>I expect to get back Observable with merged data:</p>
<pre><code>[
{
id: 1,
clientId: 201,
name: "Jon Doe"
// other data
},
{
id: 2,
clientId: 201,
name: "Jon Doe"
},
{
id: 3,
clientId: 11,
name: "Jack Sparrow"
}
]
</code></pre>
<p>I want to avoid nested subscriptions and achieve the result in a reactive way.</p>
| [] | [
{
"body": "<p>Looks good. Yeah, sometimes APIs are hard to work with.</p>\n\n<p>Instead of the loop <code>clientsData.forEach</code>, you might want to reduce the client data down to an object, where the keys are the client id (ie. index on the id). Then, map through your orders, and use this object to add in the client name. This will be O(N) vs. O(N^2) </p>\n\n<p>I'd also probably use a different object for orders vs. the orders with the name... just to avoid mutation, which I didn't expect... This is obviously more a style question, though. I favor immutable code, especially when it's more functional like this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-01T21:49:44.537",
"Id": "221510",
"ParentId": "220446",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T04:59:38.163",
"Id": "220446",
"Score": "5",
"Tags": [
"javascript",
"angular-2+",
"join",
"rxjs",
"reactive-programming"
],
"Title": "Merging client names into orders using RxJS"
} | 220446 |
<p><strong>Forward</strong></p>
<p>This is a continuation of my work in progress and the last iteration that I posted can be found <a href="https://codereview.stackexchange.com/q/219774/130733">here</a>. I have designed a compact class template that uses SFINAE with constructor delegation to reduce the amount of code duplication, and to keep this as generic and portable as possible. </p>
<p>I even added in a few functions that works on these registers. </p>
<p>One is an internal method that will retain the same internal value, but will adjust the <code>bitset</code> from one endian to another: Note: I'm only currently supporting <code>Little Endian</code> and <code>Big Endian</code> representations. Currently I do not have any internal members to act as a flag to tell what the current state of the endian is in but I may add this in later and I may add it by either an enumeration, by a bool flag, or by both(one to indicate which it is and the other to indicate if there was a change). </p>
<p>I also have a function that will reverse the order of all of the bits, for example: <code>0x00110101</code> after being reversed will become: <code>0x10101100</code> and the value will change in this case. Some cases the bit's are perfect mirror representations so the value will stay the same as there is no effect on the bit pattern as in: <code>0x01011010</code>. This will be the same in either version, but the endian view may change. My reverse function has a second bool parameter which is false by default and will modify the contents internally, if true is passed it will create a copy and return by that copy.</p>
<p>I am able to construct Any of the Four Register types from Any of the Four basic unsigned integral types, or from any of the other Four Register types. All of the types are assumed to be a multiple of bytes such that: </p>
<blockquote>
<ul>
<li><code>u8 = 8bits = 1 byte</code></li>
<li><code>u16 = 16bits = 2 bytes</code></li>
<li><code>u32 = 32bits = 4bytes</code></li>
<li><code>u64 = 64bits = 8bytes</code></li>
</ul>
</blockquote>
<hr>
<p><strong>Design</strong></p>
<p>There are three cases or ways my constructors work and they follow this set of design rules:</p>
<blockquote>
<p><strong>Overall structure of class:</strong></p>
<ul>
<li><p>In the first case it is constructing a smaller size from a larger size and can extract a byte, word, or dword from a word, dword or qword by the index value.
If the index value is out of range, then assert.</p></li>
<li><p>In the second case it is constructing a larger size from a smaller size and
can set a byte word or dword into word, dword or qword at that index location.
If the index value is out of range, then assert.</p></li>
<li><p>In the third case (default) case it is a 1 to 1 mapping so no calculations nor assertions need to be performed, just save the contents, and the index parameter if passed will have no effect.</p></li>
</ul>
</blockquote>
<hr>
<p><strong>Implementation</strong></p>
<p>Here is my class declaration:</p>
<pre><code>#pragma once
#include <algorithm>
#include <assert.h>
#include <bitset>
#include <cstdint>
#include <iostream>
#include <iomanip>
#include <limits>
#include <string>
#include <type_traits>
namespace vpc {
using u8 = std::uint8_t;
using u16 = std::uint16_t;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
template<typename T>
struct Register {
T data;
T value;
std::bitset<sizeof(T)* CHAR_BIT> bits;
Register() : data{ 0 }, value{ 0 }, bits{ 0 } {}
template<typename P, std::enable_if_t<(sizeof(P) > sizeof(T))>* = nullptr>
explicit Register(const P val, const u8 idx = 0) :
data{ static_cast<T>((val >> std::size(bits) * idx) &
std::numeric_limits<std::make_unsigned_t<T>>::max()) },
value{ data },
bits{ data }
{
constexpr u16 sizeT = sizeof(T);
constexpr u16 sizeP = sizeof(P);
assert((idx >= 0) && (idx <= ((sizeP / sizeT) - 1)) );
}
template<typename P, std::enable_if_t<(sizeof(P) < sizeof(T))>* = nullptr>
explicit Register(const P val, const u8 idx = 0) :
data{ static_cast<T>((static_cast<T>(val) << sizeof(P)*CHAR_BIT*idx) &
std::numeric_limits<std::make_unsigned_t<T>>::max()) },
value{ data },
bits{ data }
{
constexpr u16 sizeT = sizeof(T);
constexpr u16 sizeP = sizeof(P);
assert((idx >= 0) && (idx <= ((sizeT / sizeP) - 1)) );
}
template<typename P, std::enable_if_t<(sizeof(P) == sizeof(T))>* = nullptr>
explicit Register(const P val, const u8 idx = 0) :
data{ static_cast<T>( val ) }, value{ data }, bits{ data }
{}
template<typename P>
explicit Register(const Register<P>& reg, const u8 idx = 0) : Register(reg.data, idx) {}
void changeEndian() {
T tmp = data;
char* const p = reinterpret_cast<char*>(&tmp);
for (size_t i = 0; i < sizeof(T) / 2; ++i)
std::swap(p[i], p[sizeof(T) - i - 1]);
bits = tmp;
}
};
using Reg8 = Register<u8>;
using Reg16 = Register<u16>;
using Reg32 = Register<u32>;
using Reg64 = Register<u64>;
template<typename T>
std::ostream& operator<<(std::ostream& os, const Register<T>& r) {
return os << "Reg" << std::size(r.bits) << '(' << +r.data << ")\nhex: 0x"
<< std::uppercase << std::setfill('0') << std::setw(sizeof(T) * 2) << std::hex
<< +r.bits.to_ullong() << std::dec << "\nbin: "
<< r.bits << "\n\n";
}
// this is a universal template class to change the endian on any value
template<typename T>
T changeEndian(T in) {
char* const p = reinterpret_cast<char*>(&in);
for (size_t i = 0; i < sizeof(T) / 2; ++i)
std::swap(p[i], p[sizeof(T) - i - 1]);
return in;
}
template<typename T>
Register<T> reverseBitOrder(Register<T>& reg, bool copy = false) {
static constexpr u16 BitCount = sizeof(T) * CHAR_BIT;
auto str = reg.bits.to_string();
std::reverse(str.begin(), str.end());
if (copy) { // return a copy
Register<T> cpy;
cpy.bits = std::bitset<BitCount>(str);
cpy.data = static_cast<T>(cpy.bits.to_ullong());
return cpy;
}
else {
reg.bits = std::bitset<BitCount>(str);
reg.data = static_cast<T>(reg.bits.to_ullong());
return {};
}
}
} // namespace vpc
</code></pre>
<hr>
<p><strong>Example</strong></p>
<p>And here is an example of it in use:</p>
<pre><code>#include "Register.h"
int main() {
using namespace vpc;
Reg8 r8{ 0xEF };
Reg16 r16{ 0xABCD };
Reg32 r32{ 0x23456789 };
Reg64 r64{ 0x0123456789ABCDEF };
std::cout << "Default Constructors by value\n";
std::cout << r8 << r16 << r32 << r64 << '\n';
std::cout << "Showing opposite endian of original values\n";
r8.changeEndian();
r16.changeEndian();
r32.changeEndian();
r64.changeEndian();
std::cout << r8 << r16 << r32 << r64;
std::cout << "Reversing the bit representation\n";
reverseBitOrder( r8 );
reverseBitOrder( r16 );
reverseBitOrder( r32 );
reverseBitOrder( r64 );
std::cout << r8 << r16 << r32 << r64 << '\n';
std::cout << "Showing opposite endian of the reversed bit order\n";
r8.changeEndian();
r16.changeEndian();
r32.changeEndian();
r64.changeEndian();
std::cout << r8 << r16 << r32 << r64;
// I'm only going to show a couple for demonstration instead of
// showing every possible combination
std::cout << "Constructing from larger types:\n";
Reg8 r8a0{ r32, 0 }; // sets r8 to what is in r32 at 0
Reg8 r8a1{ r32, 1 }; // sets r8 to what is in r32 at 1
Reg8 r8a2{ r32, 2 }; // sets r8 to what is in r32 at 2
Reg8 r8a3{ r32, 3 }; // sets r8 to what is in r32 at 3
// Reg8 r8a4{ r32, 4 }; // uncomment -> assertion failure index out of range
std::cout << r8a0 << r8a1 << r8a1 << r8a2 << '\n';
// This also works not just by Register<T> but also from types:
Reg8 r8b0{ u32(0x01234567), 0 }; // r8a0 = 0x67
Reg8 r8b1{ u32(0x01234567), 1 }; // r8a1 = 0x45
std::cout << r8b0 << r8b1 << '\n';
Reg64 r64a0{ r32, 0 };
Reg64 r64a1{ r32, 1 };
// Reg64 r64a2{ r32, 2 }; // uncomment -> assertion failure index out of range
std::cout << r64a0 << r64a1 << '\n';
// Just for fun:
r64a0.changeEndian();
r64a1.changeEndian();
std::cout << r64a0 << r64a1 << '\n';
reverseBitOrder( r64a0 );
reverseBitOrder( r64a1 );
std::cout << r64a0 << r64a1 << '\n';
r64a0.changeEndian();
r64a1.changeEndian();
std::cout << r64a0 << r64a1 << '\n';
std::cout << "Constructing from smaller types\n";
Reg32 r32a { r8, 0 };
Reg32 r32b { r8, 1 };
Reg32 r32c { r8, 2 };
Reg32 r32d { r8, 3 };
// Reg32 r32e{ r8, 4 }; // uncomment -> assertion failure index out of range
std::cout << r32a << r32b << r32c << r32d << '\n';
// This also works not just by Register<T> but also from types:
Reg32 r32b0{ u16(0x4567), 0 }; // r32a0 = 0x00004567
Reg32 r32b1{ u16(0x4567), 1 }; // r32a1 = 0x45670000
std::cout << r32b0 << r32b1 << '\n';
// Third case constructor
Reg8 r8x(r8);
Reg8 r8x2(r8,2); // 2 has no effect due to same size
std::cout << r8x << r8x2 << '\n';
Reg16 r16x(r16);
Reg16 r16x3( u16(0xABCD), 3 ); // 3 has no effect due to same size
std::cout << r16x << r16x3 << '\n';
return EXIT_SUCCESS;
}
</code></pre>
<hr>
<p><strong>Output</strong></p>
<p>And here is the output: it matches expected values!</p>
<pre><code>Default Constructors by value
Reg8(239)
hex: 0xEF
bin: 11101111
Reg16(43981)
hex: 0xABCD
bin: 1010101111001101
Reg32(591751049)
hex: 0x23456789
bin: 00100011010001010110011110001001
Reg64(81985529216486895)
hex: 0x0123456789ABCDEF
bin: 0000000100100011010001010110011110001001101010111100110111101111
Showing opposite endian of original values
Reg8(239)
hex: 0xEF
bin: 11101111
Reg16(43981)
hex: 0xCDAB
bin: 1100110110101011
Reg32(591751049)
hex: 0x89674523
bin: 10001001011001110100010100100011
Reg64(81985529216486895)
hex: 0xEFCDAB8967452301
bin: 1110111111001101101010111000100101100111010001010010001100000001
Reversing the bit representation
Reg8(247)
hex: 0xF7
bin: 11110111
Reg16(54707)
hex: 0xD5B3
bin: 1101010110110011
Reg32(3299010193)
hex: 0xC4A2E691
bin: 11000100101000101110011010010001
Reg64(9278720243462943735)
hex: 0x80C4A2E691D5B3F7
bin: 1000000011000100101000101110011010010001110101011011001111110111
Showing opposite endian of the reversed bit order
Reg8(247)
hex: 0xF7
bin: 11110111
Reg16(54707)
hex: 0xB3D5
bin: 1011001111010101
Reg32(3299010193)
hex: 0x91E6A2C4
bin: 10010001111001101010001011000100
Reg64(9278720243462943735)
hex: 0xF7B3D591E6A2C480
bin: 1111011110110011110101011001000111100110101000101100010010000000
Constructing from larger types:
Reg8(145)
hex: 0x91
bin: 10010001
Reg8(230)
hex: 0xE6
bin: 11100110
Reg8(230)
hex: 0xE6
bin: 11100110
Reg8(162)
hex: 0xA2
bin: 10100010
Reg8(103)
hex: 0x67
bin: 01100111
Reg8(69)
hex: 0x45
bin: 01000101
Reg64(3299010193)
hex: 0x00000000C4A2E691
bin: 0000000000000000000000000000000011000100101000101110011010010001
Reg64(14169140888105648128)
hex: 0xC4A2E69100000000
bin: 1100010010100010111001101001000100000000000000000000000000000000
Reg64(3299010193)
hex: 0x91E6A2C400000000
bin: 1001000111100110101000101100010000000000000000000000000000000000
Reg64(14169140888105648128)
hex: 0x0000000091E6A2C4
bin: 0000000000000000000000000000000010010001111001101010001011000100
Reg64(591751049)
hex: 0x0000000023456789
bin: 0000000000000000000000000000000000100011010001010110011110001001
Reg64(2541551402828693504)
hex: 0x2345678900000000
bin: 0010001101000101011001111000100100000000000000000000000000000000
Reg64(591751049)
hex: 0x8967452300000000
bin: 1000100101100111010001010010001100000000000000000000000000000000
Reg64(2541551402828693504)
hex: 0x0000000089674523
bin: 0000000000000000000000000000000010001001011001110100010100100011
Constructing from smaller types
Reg32(247)
hex: 0x000000F7
bin: 00000000000000000000000011110111
Reg32(63232)
hex: 0x0000F700
bin: 00000000000000001111011100000000
Reg32(16187392)
hex: 0x00F70000
bin: 00000000111101110000000000000000
Reg32(4143972352)
hex: 0xF7000000
bin: 11110111000000000000000000000000
Reg32(17767)
hex: 0x00004567
bin: 00000000000000000100010101100111
Reg32(1164378112)
hex: 0x45670000
bin: 01000101011001110000000000000000
Reg8(247)
hex: 0xF7
bin: 11110111
Reg8(247)
hex: 0xF7
bin: 11110111
Reg16(54707)
hex: 0xB3D5
bin: 1011001111010101
Reg16(43981)
hex: 0xABCD
bin: 1010101111001101
</code></pre>
<hr>
<p><strong>Objectives</strong></p>
<p>My class above is not complete yet as this is just a public interface. Eventually I'm thinking about turning it into a class and encapsulating the internal members. There are a few more constructors that I would like to add and that is constructing a larger <code>Register<T></code> from several smaller <code>Register<T></code> objects. </p>
<p>Pseudo Example: </p>
<pre><code> Reg8 r8a{ 0xAB };
Reg8 r8b{ 0xFE };
Reg16 r16{ r8a, r8b }; // would yield 0xFEAB
// remember that first index 0 is to the right
// so our first passed in parameter would be
// set to index 0 and the next would be index 1
</code></pre>
<p>Possible future additions:</p>
<blockquote>
<ul>
<li><p>If I do plan on encapsulating the members by making then private and adding accessing and modifying functions, then I'll need to add them. Other than that this is the bulk of my class design. </p></li>
<li><p>I may even add <code>operator<<=()</code> and <code>operator>>=()</code> that would push and pop information from one register to another, streaming the bits. The same thing as you would see in assembly languages when you shift the registers.</p></li>
<li><p>Eventually I'll add in the arithmetic and comparison operators that you would commonly see done in assembly language on registers. Addition, Subtraction, Negation, Comparison etc. I'll even include the <code>operator[]</code> to get the individual bit at a specific index through the use of <code>bitset</code>. </p></li>
<li><p>I'll even have a function to get a byte, word, or dword from a word, dword or qword by index similar to the constructors, and one to extract them as well. </p></li>
<li><p>Maybe a few house keeping functions</p></li>
<li><p>As of now I have a <code>data</code> and <code>value</code> variables and the <code>value</code> isn't being used. I plan on changing <code>data</code> to <code>value</code> and rename <code>value</code> to <code>previousValue</code>, then if the value of the internal register changes, both its value and its <code>bitset</code> bit pattern changes and it will retain a history of the last value. It'll do this by saving <code>value</code> into <code>previousValue</code> before applying the changes. </p>
<ul>
<li>I think this would be a nice feature so that when working with the CPU class and you are moving in and out of registers or adding in place by immediate values, etc. you may not have to construct another temp <code>Register<T></code> object since you can do the operation on its history, then the calculation on that register can be done in place. </li>
</ul></li>
</ul>
</blockquote>
<hr>
<p>Objectives I'd like to fulfill:</p>
<blockquote>
<ul>
<li>Keep the bulk of the work done during compile time and let the compiler optimize away all it needs to. </li>
<li>Allowing it to be fast and efficient. </li>
<li>Making it to be generic, portable and reusable. </li>
<li>Making it readable and expressive enough. </li>
<li>Not sure if this is thread safe or not: it is something I'd like to keep in mind.
<ul>
<li>Let's say one builds a virtual CPU that is a quad core. They may want to have each core in its own thread. Then all of the registers belong to each of the individual cores of the CPU would have to be thread safe.</li>
<li>Even in a single core environment, one might want to construct their CPU that has multithreading capabilities and the registers again should be thread safe.</li>
</ul></li>
<li>Finally, the one thing I like about it the most is a combination of its ease of use, and its dynamic ability to be created from the four common basic unsigned types as well as the four templates of Register types. I also like the fact that you can construct a smaller register from a larger and vise versa and that you can index into which byte, word or dword you want to save or write to.</li>
</ul>
</blockquote>
<hr>
<p><strong>Summary</strong></p>
<p>I like to consider this a very versatile multipurpose register class with a good amount of flexibility, code reuse, easy to use, and being generic and portable with great readability while keeping thread safety in mind. </p>
<hr>
<p><strong>Conclusion</strong></p>
<p>Other things I'd like to commit to this project in the future after finishing with the operators and methods, would be to extend this to <code>signed</code> types as well as <code>floating</code> types, but that's tomorrows challenge. Then I plan to use it in my emulator projects where I plan on emulating an 8080 and a 6502 CPUs. I plan on using the 8080 to emulate arcade games that ran on the 8080 such as Space Invaders, and the 6502 such as an NES emulator.</p>
<hr>
<p><strong>Feedback: Questions & Concerns</strong></p>
<p>Remember these will be used to create a virtual CPU or virtual machine so think of these as you would an actual register within a CPU. Let me know what you think of my universal multipurpose virtual Register class. I want to hear all different kinds of feedback; pros and cons, where improvements can be made, any corner cases I may have missed, etc. </p>
| [] | [
{
"body": "<p>Here are some thoughts on how to further improve your program.</p>\n\n<h2>Use all required <code>#include</code>s</h2>\n\n<p>The program refers to <code>CHAR_BIT</code> which is defined in <code><climits></code> but only <code><limits></code> is currently included. Similarly, <code>std::size</code> is defined in <code><iterator></code>.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>The <code>idx</code> is sometimes used and sometimes ignored. My thought is that allowing a parameter that is silently ignored is not as good as simply throwing a compile-time error. For that reason, I'd remove <code>idx</code> from those calls.</p>\n\n<h2>Use the C++ version of <code>#include</code> files</h2>\n\n<p>Instead of <code><assert.h></code> a C++ program should include <code><cassert></code> to avoid polluting the global namespace.</p>\n\n<h2>Reconsider the use of templates</h2>\n\n<p>The current code allows me to do this:</p>\n\n<pre><code>Register<std::string> stringreg{};\nRegister<std::ostream> streamreg{};\nRegister<double> doublereg{3.141};\nauto madness{stringreg};\n</code></pre>\n\n<p>The only complaint from the compiler is about a narrowing conversion with <code>doublereg</code>. It's hard to imagine that these \"Register\" types would be useful, with the possible exception of a <code>double</code> register. For that reason, I'd suggest either using the four concrete sizes without templates or adding further restrictions via <code>std::enable_if</code>.</p>\n\n<h2>Consider a more efficient data structure</h2>\n\n<p>Processors, either real or simulated, don't typically do that much bit reversal. Also endianness, on processors where it can be changed, is typically a global value and not a per-register value. For all of those reasons, I would suggest that using native types such as <code>uint_fast8_t</code> or <code>uint_least8_t</code> (depending on whether speed or size is important to your program) might be a better choice. Reversals and bit manipulation on integral types is not that hard. Operations such as mask-and-shift are likely to be much more important than bit reversals. </p>\n\n<p>My typical approach with things like this is to actually write sample code <em>first</em>, as though I had already created the <code>Register</code> class and then let the proposed uses guide the design.</p>\n\n<h2>Consider automating tests</h2>\n\n<p>There are a number of ways to automate testing. The code you've presented has a good start at exercising the options, but what it doesn't have is a way to automatically verify the results. I often use <a href=\"https://freedesktop.org/wiki/Software/cppunit/\" rel=\"nofollow noreferrer\"><code>cppunit</code></a> for unit tests like this, but there are other unit test frameworks as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:08:54.020",
"Id": "426005",
"Score": "0",
"body": "About `idx` sometimes not being used. This is not true, in fact it is always used. If you pass in different times and omit it, then it is the same as passing in `0`. It is also a crucial part of the structure and for doing the calculations in extracting or setting the words at that `idx` upon construction. The only time that the `idx` has no effect or acts as a no op is when both `T` and `P` have the same size, so in this case it doesn't matter if you pass in 0, 1, 4 etc. because there is no calculation for it as it is a 1-1 mapping of bits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:08:58.710",
"Id": "426006",
"Score": "0",
"body": "You also mentioned about not having templates and just going with the 4 basic types non-template. Well I've tried this already, and when I started to put my registers into containers via smart pointers I was having issues being able to call the class's member functions. So I decided to use a single template structure. My main goal is the 4 basic types, as for floats; that can always be done in software. But I do appreciate your feed back as this is a great learning experience for me. This is my first time trying to write an emulator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:11:39.283",
"Id": "426007",
"Score": "0",
"body": "If the passed `idx` variable has no effect, and is not referenced in the code for some functions *that is the definition of unused*, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:13:21.863",
"Id": "426008",
"Score": "0",
"body": "More like ignored in that specific case. This was the easiest way to have a single class declaration through templates to achieve what I was after. I had to use SFINAE with constructor delegation to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:14:34.527",
"Id": "426010",
"Score": "0",
"body": "I did however fixed all of the includes that you mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:19:53.067",
"Id": "426011",
"Score": "0",
"body": "About the endian feature. This isn't really used for the internal parts of the virtual cpu its, this is more for use of the user or designer. They can use this if they are writing their own logger or debugger. It just gives them a quick way to write the bytes in either little or big endian either to the console or to a file. This is more of a reference or utility function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:21:30.170",
"Id": "426012",
"Score": "0",
"body": "Well back the `idx` where it's not being used; I could simply assert if it is not `0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T21:21:36.887",
"Id": "426013",
"Score": "1",
"body": "For an alternative approach to simulation, see https://codereview.stackexchange.com/questions/115118/mac1-simulator-debugger"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T12:58:52.177",
"Id": "426059",
"Score": "1",
"body": "\"`std::size` is defined in `<iterator>`.\" In fact, per [[iterator.range]/1](https://timsong-cpp.github.io/cppwp/n4659/iterator.range#1), `#include <string>` suffices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T14:09:57.850",
"Id": "426066",
"Score": "0",
"body": "@L.F. I'd have to agree there are many functions in the std library that are commonly used that are each defined in their own specific header file, but many times you can include any of the basic containers such as string, vector map etc. and there is no need to include the underlying headers because those containers rely on them. Now things such as smart pointers you need `<memory>` and for time components `<chrono>`, etc. However, as some have stated it all depends on the compiler too because each compiler will issue their own version of those headers. So you do need to be careful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T14:12:06.173",
"Id": "426067",
"Score": "0",
"body": "I think I will enforce more stipulations with `std::enable_if` to ensure that the types are `unsigned and integral types`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T14:15:15.873",
"Id": "426068",
"Score": "0",
"body": "@L.F. You're right about `std::size` also being in `<string>`. That's a change that was made in C++17. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T06:49:00.827",
"Id": "426125",
"Score": "0",
"body": "@Edward `std::size` itself is introduced in C++17."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T15:27:03.427",
"Id": "220469",
"ParentId": "220447",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T05:29:21.097",
"Id": "220447",
"Score": "5",
"Tags": [
"c++",
"template",
"c++17",
"bitset",
"sfinae"
],
"Title": "Emulating Virtual Registers Part 3"
} | 220447 |
<p>Here is what a knapsack/rucksack problem means (taken from <a href="https://en.wikipedia.org/wiki/Knapsack_problem" rel="nofollow noreferrer">Wikipedia</a>):</p>
<blockquote>
<p><em>Given a set of items, each with a weight and a value, determine the
number of each item to include in a collection so that the total
weight is less than or equal to a given limit and the total value is
as large as possible. It derives its name from the problem faced by
someone who is constrained by a fixed-size knapsack and must fill it
with the most valuable items.</em></p>
</blockquote>
<p>With reference to - <a href="https://en.wikipedia.org/wiki/Knapsack_problem" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Knapsack_problem</a> - this is the definition of a 0-1 knapsack or a 0-1 rucksack problem:</p>
<p><a href="https://i.stack.imgur.com/AE5KL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AE5KL.png" alt="Knapsack problem"></a></p>
<p>Here is my version of the "0-1 knapsack problem" in python:</p>
<pre><code>def knapsack(capacity, items, weights, values):
grid = [[0] * (capacity + 1)]
for item in range(items):
grid.append(grid[item].copy())
for k in range(weights[item], capacity + 1):
grid[item + 1][k] = max(grid[item][k], grid[item][k -weights[item]] + values[item])
solution_value = grid[items][capacity]
solution_weight = 0
taken = []
k = capacity
for item in range(items, 0, -1):
if grid[item][k] != grid[item - 1][k]:
taken.append(item - 1)
k -= weights[item - 1]
solution_weight += weights[item - 1]
return solution_value, solution_weight, taken
</code></pre>
<p>NOTES - The total weight of the taken items <strong>cannot</strong> exceed the capacity of the knapsack. The total weight of the items in the knapsack is called “solution weight”, and their total value is the “solution value”.</p>
<p>Here are some example input values,</p>
<pre><code>values = [60, 100, 120]
weights = [10, 20, 30]
capacity = 50
items = len(values)
print(knapsack(capacity, items, weights, values))
print('knapsack() Time: ' + str(timeit.timeit('knapsack(capacity, items, weights, values)', setup = 'from __main__ import knapsack, capacity, items, weights, values')))
</code></pre>
<p>where my budget ($<code>50</code>) is the sack’s <code>capacity</code>, the shares are the <code>items</code> to be packed, the current prices are the <code>weights</code> and the price estimates are the <code>values</code>.</p>
<p>Here is an example output,</p>
<pre><code>(220, 50, [2, 1])
knapsack() Time: 54.669268087000006
</code></pre>
<p>NOTE - <code>knapsack() Time</code> is in milliseconds.</p>
<p>So I would like to know whether I could make this code shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [] | [
{
"body": "<p>The code is well written in terms of style and readability, there is only a few things we could improve there.</p>\n\n<p>The algorithm is also optimal for runtime, but the memory usage/allocation could be improved a little which could speed things up.</p>\n\n<h2>Readability</h2>\n\n<ul>\n<li><p>Variable naming: some of the variables are not very descriptive:</p>\n\n<ul>\n<li><p><code>grid</code> which represents the dynamic-programming array, it needs a comment \neither way but maybe <code>best_value</code> is better.</p></li>\n<li><p><code>items</code> usually means the actual array, since it represents the count, it's \nbetter to name it <code>items_count</code>. Actually, this variable is not needed since \nthe function could use <code>len(weights)</code> or <code>len(values)</code></p></li>\n</ul></li>\n<li><p>You could use a named-tuple (or just tuple) to group the item weights and values.</p></li>\n</ul>\n\n<h2>Algorithm</h2>\n\n<ul>\n<li>You can reduce the 2d array to a 1d array saving the values for the current iteration. For this to work, we have to iterate capacity (inner for-loop)\nin the opposite direction so we that we don't use the values that were updated in the same iteration (you can try the other way and see what goes wrong).</li>\n</ul>\n\n<p>Incorporating these changes we get the following code:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from collections import namedtuple\nfrom timeit import timeit\n\nItem = namedtuple('Item', ['value', 'weight'])\n\ndef knapsack(capacity, items):\n # A DP array for the best-value that could be achieved for each weight.\n best_value = [0] * (capacity + 1)\n # The previous item used to achieve the best-value for each weight.\n previous_item = [None] * (capacity + 1)\n for item in items:\n for w in range(capacity, item.weight - 1, -1):\n value = best_value[w - item.weight] + item.value\n if value > best_value[w]:\n best_value[w] = value\n previous_item[w] = item\n\n cur_weight = capacity\n taken = []\n while cur_weight > 0:\n taken.append(previous_item[cur_weight])\n cur_weight -= previous_item[cur_weight].weight\n\n return best_value[capacity], taken\n\nitems = [Item(60, 10), Item(100, 20), Item(120, 30)]\ncapacity = 50\n\nprint(knapsack(capacity, items))\nprint('knapsack() Time: ' + str(\n timeit('knapsack(capacity, items)', \n setup = 'from __main__ import knapsack, capacity, items')))\n</code></pre>\n\n<p>This change resulted in a good improvement in runtime. On my machine, it decreased the execution time (1,000,000 iterations) from 37s to 24s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T05:11:26.457",
"Id": "426029",
"Score": "1",
"body": "Upvoted! I tested it and it worked perfectly. Definitely more efficient than my code above :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T04:44:04.383",
"Id": "220499",
"ParentId": "220450",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "220499",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T05:58:19.813",
"Id": "220450",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"dynamic-programming",
"knapsack-problem"
],
"Title": "Python program for \"0-1 knapsack problem\""
} | 220450 |
<p>Was too bored in holidays...here's a code which finds the day of the week using the algorithm in <a href="https://www.youtube.com/watch?v=714LTMNJy5M" rel="nofollow noreferrer">this video</a>. Please give a logical date in the correct format cause I didn't account for improper inputs cause I'm too lazy. My code is short and sweet.</p>
<pre><code>day=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"] #some database numbers and strings
mdoom=[3,28,14,4,9,6,11,8,5,10,7,12]
while True:
entry=input('\nEnter a date in DD/MM/YYYY format:') #Input date in a specified format
date,month,year = map(int,entry.split('/')) #Get the date,month and year
centdoom=[3,2,0,5]
a=centdoom[((year//100)%4)-3]
b=(year%100)//12
c=(year%100)%12
d=c//4 #Random calculations for doomsday :)
e=a+b+c+d
if (year%4==0) and ((year%100!=0) or (year%400==0)): #Checks for leap year
mdoom[0],mdoom[1]=4,29
ddoom=e%7 #finds a date in the 1st week which has the same day as the doomsday
r=mdoom[month-1] #Gives the doomsdate in the input month
r=r%7
r=ddoom-r
date=date%7 #finds a date in the 1st week which has the same day as the input date
print('\n',day[(r+date)%7]) #prints the output
k=input('\nTry again?(y/n)')
if k=='y':
continue
else:
break
</code></pre>
<p>And any suggestions or improvements are welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T13:07:12.943",
"Id": "425961",
"Score": "1",
"body": "I would slightly improve on leap year (https://en.wikipedia.org/wiki/Leap_year#Algorithm)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T17:48:33.210",
"Id": "425986",
"Score": "0",
"body": "can you please send the edited part of the leap year condition...cause I can't plug in the 2 new conditions according to Wiki in my code.....I'm a complete noob :( ...thanks in advance"
}
] | [
{
"body": "<p>Your code is hard to understand, even after watching the video.</p>\n\n<ol>\n<li>Make some functions. <code>years_doomsday</code> would help move some of the hard to understand information to be self-contained.</li>\n<li>If you need to floor divide and get the remainder use <code>divmod</code>.</li>\n<li>You can check the leap year using <code>calendar.isleap</code>.</li>\n<li>You have a bug, if you ever enter a leap year then the non-leap years will return incorrect values for January and February.</li>\n<li>You should make a function that calls <code>years_doomsday</code>, and returns the weekday.</li>\n<li>You should make <code>centdoom</code> a global constant.</li>\n<li>By rotating <code>centdoom</code> once you can remove the need for the <code>-3</code>.</li>\n</ol>\n\n<pre><code>import calendar\n\nWEEKDAYS = [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"]\nMDOOMSDAY = [3, 28, 14, 4, 9, 6, 11, 8, 5, 10, 7, 12]\nMDOOMSDAY_LEAP = list(MDOOMSDAY)\nMDOOMSDAY_LEAP[:2] = [4, 29]\nCDOOMSDAY = [2, 0, 5, 3]\n\n\ndef years_doomsday(year):\n a, b = divmod(year, 100)\n c, d = divmod(b, 12)\n e = d // 4\n return (CDOOMSDAY[a % 4] + c + d + e) % 7\n\n\ndef doomsday(year, month, day):\n y_doomsday = years_doomsday(year)\n mdoomsday = MDOOMSDAY_LEAP if calendar.isleap(year) else MDOOMSDAY\n return WEEKDAYS[(day - mdoomsday[month-1] + y_doomsday) % 7]\n\n\nif __name__ == '__main__':\n tests = [\n (2305, 7, 13, 'Thursday'),\n (1776, 7, 4, 'Thursday'),\n (1969, 7, 20, 'Sunday'),\n (1984, 1, 6, 'Friday'),\n (1902, 10, 19, 'Sunday'),\n ]\n for test in tests:\n if doomsday(*test[:3]) != test[-1]:\n print('Broken for', test)\n</code></pre>\n\n<p>If you don't want any fun, you can replace your code with <code>datetime.date.isoweekday</code>.</p>\n\n<pre><code>import datetime\n\nfor test in tests:\n if WEEKDAYS[datetime.date(*test[:3]).isoweekday()%7] != test[-1]:\n print('Broken for', test)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T13:22:36.230",
"Id": "430132",
"Score": "0",
"body": "Nice answer! +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T13:25:56.807",
"Id": "430135",
"Score": "0",
"body": "why not do `tests = [(2705, 7, 13), \"Thursday\",...]` or even making it a dict, and then `for date, answer in tests:if doormsday(*date) != answer:print(...)`; and I find your way of assembling `MDOOMSDAY_LEAP` rather strange"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T13:28:50.287",
"Id": "430137",
"Score": "1",
"body": "@MaartenFabré Because I find `((1, 2, 3), 'd')` is more annoying to type then `(1, 2, 3, 'd')`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T13:29:28.483",
"Id": "430138",
"Score": "0",
"body": "it is 2 more brackets to type, yes, but a lot more clearer when using the test"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T13:29:54.920",
"Id": "430140",
"Score": "1",
"body": "@MaartenFabré And I was testing this in IDLE where I kept having to write the same stuff over and over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T18:15:19.860",
"Id": "430189",
"Score": "0",
"body": "1.Thanks for the neater version of the code...2.divmod method is pretty awesome..3.I want to keep the sanity of my code (i don't want to add modules like calender)...that's why the leap year was found using simple 3 conditions..4.my code doesn't have a bug,if u read my code..I find the leap year and rectify of Jan and feb...5.thanks for the shorter code..just lovely..."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T13:21:24.807",
"Id": "222284",
"ParentId": "220455",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T09:24:34.240",
"Id": "220455",
"Score": "6",
"Tags": [
"python",
"algorithm",
"python-3.x",
"datetime",
"reinventing-the-wheel"
],
"Title": "Calculate the day when Date is given as input using the Doomsday algorithm"
} | 220455 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.