body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I am writing an app that is supposed to simulate load on our web api and NServiceBus(particular) service. This is the first time I am writing an application like this. It appears to run ok, however it takes a few seconds before anything shows up in the console window. Is there a better way to do this?</p>
<pre><code>class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press any key to start...");
Console.ReadKey();
Console.WriteLine();
RunLoad(100);
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static void RunLoad(int loadSize)
{
Parallel.For(0, loadSize, i =>
{
RunTasks();
});
}
public static async Task RunTasks()
{
var tasks = new List<Task>
{
GetLoanByLoanId("7000002050"),
GetEnvelopesForLoan("7000002077"),
GetLoanDataByLoanId("7000002072")
};
await Task.WhenAll(tasks);
}
private static async Task GetLoanByLoanId(string loanNumber)
{
await Task.Run(() => {
var svc = new WebApiService();
var msg1 = svc.GetLoanByLoanId(loanNumber);
if (string.IsNullOrWhiteSpace(msg1)) return;
Console.WriteLine($"GL {loanNumber}: {msg1.Length}");
});
}
private static async Task GetLoanDataByLoanId(string loanNumber)
{
await Task.Run(() => {
var svc = new WebApiService();
var msg1 = svc.GetLoanDataByLoanId(loanNumber);
if (string.IsNullOrWhiteSpace(msg1)) return;
Console.WriteLine($"GLD {loanNumber}: {msg1.Length}");
});
}
private static async Task GetEnvelopesForLoan(string loanNumber)
{
await Task.Run(() => {
var svc = new WebApiService();
var msg1 = svc.GetEnvelopesForLoan(loanNumber);
if (string.IsNullOrWhiteSpace(msg1)) return;
Console.WriteLine($"GEFL {loanNumber}: {msg1.Length}");
});
}
}
}
</code></pre>
<p>I am trying to mimic the number to users hitting the system through the RunLoad method.</p>
<p>Also this is running in .Net Framework 4.8..</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T07:14:22.087",
"Id": "481195",
"Score": "0",
"body": "Do I understand correctly that your `RunLoad` method tries to mimic several clients? Are you concerning about ramp-up time? Do I understand correctly that your `GetXYZ` are independent? Does ordering of these API calls matter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T11:12:51.587",
"Id": "481225",
"Score": "0",
"body": "Yes RunLoad is supposed to mimic the number of clients.All the Get... are independent and no the order of the API calls do not matter..."
}
] |
[
{
"body": "<p>There are several improvement areas. Let's review them one-by-one from bottom up:</p>\n<h3>GetXYZ</h3>\n<pre><code>private static async Task GetXYZ(string parameter)\n{\n await Task.Run(() => {\n var svc = new WebApiService();\n var msg1 = svc.GeXYZ(parameter);\n if (string.IsNullOrWhiteSpace(parameter)) return;\n Console.WriteLine($"XYZ {parameter}");\n });\n}\n</code></pre>\n<p>A <code>Task</code> can represent either an asynchronous work or a parallel work. An async work can be considered as <strong>non-blocking I/O operation</strong>. Whereas the parallel work can be treated as <strong>(blocking) CPU operation</strong>. (It is oversimplified but it works for us now)</p>\n<p>In the above code the <code>Task.Run</code> tells to .NET runtime that this piece of code should run a dedicated thread (in reality this is not as simple as this, but let me simplify the model now). It means that the passed delegate should run a dedicated CPU core.</p>\n<p>But inside your delegate you are making a <strong>blocking I/O operation</strong>. So you have created a delegate, you have moved that code to a dedicated core, which will <strong>block</strong> and do nothing until the network driver will finish the I/O operation.</p>\n<p>You are just wasting a lot of valuable resources. A better alternative would look like this:</p>\n<pre><code>private static async Task GetXYZ(string parameter)\n{\n var svc = new WebApiService();\n var msg1 = await svc.GeXYZAsync(parameter);\n if (string.IsNullOrWhiteSpace(parameter)) return;\n Console.WriteLine($"XYZ {parameter}");\n}\n</code></pre>\n<p>Here you are making a non-blocking I/O operation. The network driver fires of a network call asynchronously and returns immediately. When it completes it will notify the ThreadPool. (Because here we are calling <code>await</code> against an asynchronous work that's why we are not blocking the caller Thread.)</p>\n<p>In short: Network driver can do let's say 1000 concurrent network operations at the same time. While the CPU can perform as many operations in parallel as many cores it has.</p>\n<h3>RunTasks</h3>\n<p>(I guess you can find a better name for this.)</p>\n<p>Here with the <code>Task.WhenAll</code> you are already asking the .NET runtime to run them in parallel. If they are asynchronous operations then the network driver will take care of them and try to run them in parallel. In case of parallel work CPU tries to schedule them on different cores but there is no guarantee that they will run in parallel. They might run only concurrently (with context-switches).</p>\n<h3>RunLoad</h3>\n<p>(I guess you can find a better name for this.)</p>\n<p>Here with the <code>Parallel.For</code> you try to create as many blocking parallel task as many the <code>loadSize</code> value. If you have 100 Tasks for 8 CPU cores then it is inevitable to have context-switches. Again your current implementation is highly CPU-bound even though you try to perform massive I/O operations.</p>\n<p>A better alternative:</p>\n<pre><code>private static async Task RunLoad(int loadSize)\n{\n var clients = new List<Task>();\n for (int j = 0; j < loadSize; j++)\n {\n clients.Add(RunTasks());\n }\n\n await Task.WhenAll(clients);\n}\n</code></pre>\n<p>In this way all your client's all requests might run in parallel if your network driver supports that many outgoing requests.</p>\n<p>This <code>WhenAll</code> will be finished when all operation has finished. If you want to monitor them in "real-time" when any of them finished then you can rewrite your method in the following way:</p>\n<pre><code>static async Task Main(string[] args)\n{\n Console.WriteLine("Press any key to start...");\n Console.ReadKey();\n Console.WriteLine();\n \n await foreach (var test in RunTests(10))\n {\n //NOOP\n }\n\n Console.WriteLine("Press any key to exit...");\n Console.ReadKey();\n}\n\n\nprivate static async IAsyncEnumerable<Task> RunTests(int loadSize)\n{\n var requests = new List<Task>();\n for (int j = 0; j < loadSize; j++)\n {\n requests.Add(GetLoanByLoanId("7000002050"));\n requests.Add(GetEnvelopesForLoan("7000002077"));\n requests.Add(GetLoanDataByLoanId("7000002072"));\n }\n\n while (requests.Any())\n {\n var finishedRequest = await Task.WhenAny(requests);\n requests.Remove(finishedRequest);\n yield return finishedRequest;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T13:18:52.380",
"Id": "481236",
"Score": "1",
"body": "Thank you, yeah naming is not my strong point..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:07:31.947",
"Id": "481245",
"Score": "0",
"body": "In your alternative RunLoad you have a list of tasks (RunTasks) waiting on the WhenAll, but RunTasks has the same sort of flow waiting on whenall of Getxxx methods to complete. Is a good idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:38:29.080",
"Id": "481253",
"Score": "0",
"body": "@Kixoka `RunTasks` waits to finish all requests from a given client. `RunLoad` waits to finish all clients' all requests. It depends how you want to manage the relationships between requests and clients. If there is no particular relationship (just a bunch of requests with different origin) then the the `RunTests` makes sense, because it does not wait for any group of tasks to finish. If one finishes then it `yield`s that back. Does it make sense for you?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T12:44:43.863",
"Id": "245076",
"ParentId": "244943",
"Score": "3"
}
},
{
"body": "<p>Overall, the code is quite clean and easy to understand. You did a good job of subdividing the work into small and easily digestible submethods.</p>\n<p>I did notice a few other things though, which I'll list below.</p>\n<hr />\n<p><strong>Tasks vs threads</strong></p>\n<p>Right now, it seems you're using <code>Task.WhenAll</code> and <code>Task.Run</code> as an async wrapper to emulate different concurrent threads. That's not what asynchronous code is for. While asynchronous code often does use multiple cores/threads, that's not a guarantee. You can run asynchronous logic on a single-core machine with a single thread, where there's no possible way of executing logic concurrently.</p>\n<p>Do I think that you're working on a single-core machine with a single thread? No. But the point remains that you're currently conflating two different concepts that have <em>some</em> but not complete overlap.</p>\n<p>I'm not saying your way of doing it doesn't work right now, but to ensure that this code works on all machines I would suggest that you use threads for this, not tasks. That way, you enforce concurrent logic instead of hoping that it works out.</p>\n<p>Then again, if this is a small short-lived test app that will be discarded in the near future, it doesn't quite matter (but then a code review wouldn't really matter either, I guess).</p>\n<p><em>I would generally expect <code>WebApiService</code> to have async methods, which you could be using here. However, it's possible that <code>WebApiService</code> doesn't have async methods and that you are unable/unwilling to implement them on <code>WebApiService</code>, which would be fair enough since this test application isn't trying to redevelop the service implementation but rather test the existing one.</em></p>\n<p><strong>Constructor spam</strong></p>\n<p>Right now you're creating a <code>new WebApiService()</code> 300 times (100 loops, 3 tasks each). Is that by intention, or could this be done using a single service object?</p>\n<p>I suspect (though I cannot guarantee) you can reuse the same object without issues here, which means you could shift that instantiation outside of the loops and either pass it as a parameter or use an static variable (since everything else is static anyway).</p>\n<pre><code>private static WebApiService _svc = new WebApiService();\n\nprivate static async Task GetLoanByLoanId(string loanNumber)\n{\n await Task.Run(() => {\n var msg1 = _svc.GetLoanByLoanId(loanNumber);\n if (string.IsNullOrWhiteSpace(msg1)) return;\n Console.WriteLine($"GL {loanNumber}: {msg1.Length}");\n });\n}\n</code></pre>\n<p>The same goes for the other two tasks. If you instead wish to pass it as a method parameter, simply instantiate it in <code>Main()</code> and then thread it through your method calls all the way down to the <code>GetLoanByLoanId</code> method (and the other two tasks).</p>\n<p>Since everything here is static anyway, I'd use a static class field here because it's simpler and doesn't really cause any issues in your already exclusively static code.</p>\n<p><strong>If return</strong></p>\n<p>This is quite unidiomatic:</p>\n<pre><code>if (string.IsNullOrWhiteSpace(msg1)) return;\nConsole.WriteLine($"GEFL {loanNumber}: {msg1.Length}");\n// end of void method\n</code></pre>\n<p>You could simply invert the if instead of returning one line early:</p>\n<pre><code>if(!String.IsNullOrWhiteSpace(msg1))\n Console.WriteLine($"GEFL {loanNumber}: {msg1.Length}");\n</code></pre>\n<p>This way, you don't need an eary <code>return</code>. Early returns have their uses when they can skip a whole lot of performance-draining steps, but when that <code>if return</code> is the last block of the method body, there's no futher logic (i.e. after the <code>if</code>) to skip.</p>\n<p><strong>Logging</strong></p>\n<p>It's weird that you're choosing to not log a message when an empty result was retrieved. You already don't quite seem to care about the received message since you're only logging its length, so I surmise that you're using these messages as for progress tracking.</p>\n<p>I'm unsure why you're specifically not logging 0 length (or null) results. If the logging is to keep track of the progress, then those null-or-empty results are still progress and should be logged.</p>\n<p>If you wrote this check to avoid null reference exceptions, there's better ways of avoiding those, e.g. null propagation:</p>\n<pre><code>Console.WriteLine($"GEFL {loanNumber}: {msg1?.Length}");\n</code></pre>\n<p>This way, you always get a message, regardless of what <code>msg1</code> contains.</p>\n<p><strong>Reusable task logic</strong></p>\n<p>All three tasks have pretty much the exact same method body, except for two small differences:</p>\n<pre><code>private static async Task AnyTask(string loanNumber)\n{\n await Task.Run(() => {\n var svc = new WebApiService();\n var msg1 = svc.THISMETHODISDIFFERENT(loanNumber); // <- here\n if (string.IsNullOrWhiteSpace(msg1)) return;\n Console.WriteLine($"THISNAMEISDIFFERENT {loanNumber}: {msg1.Length}"); // <- here\n });\n}\n</code></pre>\n<p>But each of these methods you use always follows the same <code>string MyMethod(string)</code> pattern, and the log message is really just an arbitrary string value. You can therefore easily abstract this method call in a way that the rest of the task body can be reused:</p>\n<pre><code>private static async Task GetLoanByLoanId(string loanNumber)\n{\n PerformJob($"GL {loanNumber}", svc => svc.GetLoanByLoanId(loanNumber));\n}\n\nprivate static async Task GetLoanDataByLoanId(string loanNumber)\n{\n PerformJob($"GLD {loanNumber}", svc => svc.GetLoanDataByLoanId(loanNumber));\n}\n\nprivate static async Task GetEnvelopesForLoan(string loanNumber)\n{\n PerformJob($"GEFL {loanNumber}", svc => svc.GetEnvelopesForLoan(loanNumber));\n}\n\nprivate static async Task PerformJob(string jobName, Func<WebApiService, string> getMessage)\n{\n return Task.Run(() => {\n var svc = new WebApiService();\n var msg1 = getMessage(svc);\n if (string.IsNullOrWhiteSpace(msg1)) return; \n Console.WriteLine($"{jobName}: {msg1.Length}"); \n }); \n}\n</code></pre>\n<p>There are two things to remark here:</p>\n<ul>\n<li>The three job methods have become so trivial that you could arguably remove them and just call <code>PerformJob("xxx", svc => svc.xxx(loanNumber));</code> directly from the calling code. I think this is a subjective call whether you prefer to wrap it nicely or would rather avoid one liner methods.</li>\n<li>If you follow the improvements I suggested in earlier points, the method body of <code>PerformJob</code> becomes trivial as well. But I wouldn't suggest removing this method even though it's trivial, since that would force you to copy/paste the log message format all over the place.</li>\n</ul>\n\n<pre><code>private static async Task PerformJob(string jobName, Func<WebApiService, string> getMessage)\n{\n // Verbosely:\n var msg = getMessage(svc);\n Console.WriteLine($"{jobName}: {msg?.Length}");\n\n // Or as a one-liner:\n Console.WriteLine($"{jobName}: {getMessage(svc)?.Length}"); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T13:08:50.423",
"Id": "481235",
"Score": "0",
"body": "Ultimately I am trying to simulate greater than 100+ users hitting the webAPI at once to evaluate scalability and to pin point bottlenecks not only with the webAPI but the supporting Particular/NServiceBus service that handles queue routing. I have logging set up on the API and Service to spit out any contentions etc...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T14:09:40.610",
"Id": "481241",
"Score": "0",
"body": "Also thank you for the review. Very much appreciated!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T12:55:21.480",
"Id": "245077",
"ParentId": "244943",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245076",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T14:48:05.217",
"Id": "244943",
"Score": "4",
"Tags": [
"c#",
"task-parallel-library"
],
"Title": "Creating an app to simulate load"
}
|
244943
|
<p>I have implemented a graph based on theory, and I'd like some advice regarding best practice, and thoughts about what i didn't implement that would make it even more useful, along with ideas that are supposed to be in graphs, but i missed them. I have included documentation in the code, to explain what each function does, and hopefully that is enough to explain my doings.</p>
<pre><code># Unweighted Graph
import itertools
class Graph:
def __init__(self, array=None):
"""
initialises the graph, with all the nodes
keeps count on the number of nodes in graph
if array is included as an argument, it inserts all the nodes in the array.
"""
self.graph = dict()
self.num_of_nodes = 0
self.num_of_edges = 0
if array:
for val in array:
self.insert_node(val)
def __str__(self):
"""
Displays the graph in this FORMAT: (adjacency list)
node1 -> connected_nodes
node2 -> node1 node3 node4
"""
arr = list()
for node, connected_nodes in self.graph.items():
arr.append(f"{node} ---> {' '.join(list(map(str, connected_nodes)))}")
return "\n".join(arr)
def insert_node(self, value):
"""
inserts a node to the graph
"""
self.graph[value] = set()
self.num_of_nodes += 1
def check_node_exist(self, node):
"""
checks for the existence of a node in the graph
"""
if node in self.graph:
return True
raise Exception(f"Node {node} doesn't exist in the Graph")
def create_undirected_edge(self, node1, node2):
"""
creates an undirected edge between two nodes
"""
if self.check_node_exist(node1) and self.check_node_exist(node2):
self.graph[node1].add(node2)
self.graph[node2].add(node1)
self.num_of_edges += 1
def create_directed_edge(self, from_node, to_node):
"""
creates a directed edge from a node, to a node.
"""
if self.check_node_exist(from_node) and self.check_node_exist(to_node):
self.graph[from_node].add(to_node)
self.num_of_edges += 1
def connect_all_together(self):
"""
Connects all the nodes with undirected edges, meaning each pair of nodes are connected to each other
forms n(n+1)/2 edges in total
"""
nodes = self.graph.keys()
comb = itertools.combinations(nodes, 2)
for node1, node2 in comb:
self.create_undirected_edge(node1, node2)
def is_nodes_connected(self, node1, node2):
if self.check_node_exist(node1) and self.check_node_exist(node2):
if node1 in self.graph[node2] and node2 in self.graph[node1]:
return True
return False
def connections(self, node):
"""
returns the connected/adjacent nodes of a given node
"""
return self.graph[node] if self.check_node_exist(node) else None
def is_undirected_graph(self):
"""
checks whether every edge in the graph is undirected/ by checking every node and their connections
"""
for node, connections in self.graph.items():
for connected_node in connections:
if node not in self.graph[connected_node]:
return False
return True
def create_edge_list(self):
"""
creates and returns an edge list, with tuples representing the edges between the pair of nodes, in each tuple.
""" # makes sure that the graph is undirected
arr = set()
nodes = self.graph.keys()
for node in nodes:
for connected_node in self.graph[node]:
arr.add((node, connected_node))
return arr
def create_adjacency_list(self):
"""
creates and returns an adjacency list, in the format "node ---> connected_node1 connected_node2, etc"
"""
return self.__str__()
def create_adjacency_matrix(self):
"""
creates and returns an adjacency matrix
indexing dict, contains keys-value pairs in which indexes refer to their node
FORMAT: for nodes 1, 2, 3 in an undirected graph
{0: node1, 1: node2, 2: node3}
[(0, 1, 1), (1, 0, 1), (1, 1, 0)]
"""
nodes = list(self.graph.keys())
indexing_dict = {i: nodes[i] for i in range(len(nodes))}
adjacency_matrix = {tuple(1 if nodes[j] in self.graph[indexing_dict[i]] else 0 for j in range(self.num_of_nodes)) for i in range(self.num_of_nodes)}
return f"{indexing_dict}\n{adjacency_matrix}"
</code></pre>
|
[] |
[
{
"body": "<h2>Dict literals</h2>\n<pre><code> self.graph = dict()\n</code></pre>\n<p>can be</p>\n<pre><code> self.graph = {}\n</code></pre>\n<h2>Intermediate <code>list</code> before <code>join</code></h2>\n<pre><code> arr = list()\n for node, connected_nodes in self.graph.items():\n arr.append(f"{node} ---> {' '.join(list(map(str, connected_nodes)))}")\n return "\\n".join(arr)\n</code></pre>\n<p>can be</p>\n<pre><code>arr = (\n f"{node} ---> {' '.join(str(n) for n in connected_nodes)}"\n for node, connected_nodes in self.graph.items()\n)\nreturn "\\n".join(arr)\n</code></pre>\n<p>This will use a couple of generators directly instead of outer and inner lists.</p>\n<h2>True-or-exception</h2>\n<p>The return model for <code>check_node_exist</code> - either returning <code>True</code> or raising an exception - is curious. You should go "all or nothing": either return True/False - or "throw an exception or don't".</p>\n<h2>Direct return of boolean expressions</h2>\n<pre><code> if node1 in self.graph[node2] and node2 in self.graph[node1]:\n return True\n return False\n</code></pre>\n<p>can be</p>\n<pre><code>return node1 in self.graph[node2] and node2 in self.graph[node1]\n</code></pre>\n<h2>Set comprehension</h2>\n<pre><code> arr = set()\n nodes = self.graph.keys()\n for node in nodes:\n for connected_node in self.graph[node]:\n arr.add((node, connected_node))\n return arr\n</code></pre>\n<p>can be</p>\n<pre><code>return {\n (node, connected_node)\n for node in self.graph.keys()\n for connected_node in self.graph[node]\n}\n</code></pre>\n<h2>Calling dunder methods</h2>\n<pre><code>return self.__str__()\n</code></pre>\n<p>should be</p>\n<pre><code>return str(self)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T16:43:29.957",
"Id": "480957",
"Score": "0",
"body": "wow i had no idea you could do use formatted strings in comprehensions +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T15:30:03.193",
"Id": "244948",
"ParentId": "244945",
"Score": "6"
}
},
{
"body": "<p>I think create_edge_list/create_adjacency_list naming is a bit inconsistent, one returns a list as you would expect, the other returns a string representation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T11:30:57.950",
"Id": "481029",
"Score": "0",
"body": "that is true, perhaps i should make them both iterables"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:26:03.670",
"Id": "244960",
"ParentId": "244945",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "244948",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T15:02:51.630",
"Id": "244945",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"graph"
],
"Title": "My Graph Implementation In Python"
}
|
244945
|
<p>In my project I am using the ADR architecture, a branch of MVC.</p>
<p>In my actions (Controllers) I handle only data that comes from the request.</p>
<p>When there is a business rule that defines which status code I return, I do this treatment in my service.</p>
<p>Imagine this scenario:</p>
<p>When editing a user, I check if the user's email already exists, if it exists, I return an error informed to your message. This treatment is done in the service, and in these cases I get the error in it.</p>
<p>I would like to hear from you about my approach to, in some cases, the service layer returning the payload.</p>
<p>Action:</p>
<pre><code>class CreateUserAction extends Action
{
private $userService;
/**
* @param UserService $userService
*/
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
public function handle(Request $request) : JsonResponse
{
$data = $request->getData();
$payload = $this->userService->create($data, $user);
return response()->json($payload->body, $payload->statusCode);
}
}
</code></pre>
<p>Service:</p>
<pre><code>class UserService extends BaseService
{
private $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function create(array $data) : object
{
if ($this->userRepository->findByEmail($data['email'])) {
$this->setPayloadError(
__('messages.user.contributor_email_already_exists'),
Response::HTTP_BAD_REQUEST
);
return $this->getPayload();
}
$userCreated = $this->userRepository->create($data);
$this->setPayload($userCreated, Response::HTTP_CREATED);
return $this->getPayload();
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-17T17:02:35.160",
"Id": "482426",
"Score": "0",
"body": "I believe HTTP status code should be handled by the controller. In your case, an Action. The service layer should be independent from the HTTP part of the application, that's what controllers are for. So the service layer should just throw an exception if something goes up, and the controller/action should catch that and handle it by returning a proper status code in the request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-20T13:00:54.750",
"Id": "482690",
"Score": "0",
"body": "I thought about this scenario, but found 2 problems:\n\n\n1 - As it is something predictable in the business rule, I don't know if it would be interesting to return an exception in this case, in addition to being more costly, I understand that I would treat the exception as flow control.\n\n\n2 - When I need to return different types of status code, I would have to keep this in my trycacth, checking the type of that exception to set the status code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-20T13:01:20.283",
"Id": "482691",
"Score": "0",
"body": "I have seen in some designs, about having a layer where you pass an enum to it, it is responsible for forming the response.I decided to return the http code to avoid this other layer, in my view returning only the code does not leave it attached to the entire http layer. Since it is not formed by its codes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-20T13:12:23.993",
"Id": "482694",
"Score": "0",
"body": "Yeah using exceptions as flow control is kinda bad practice, so if your service layer could just return a object with a certain structure, containing an error like \"ACCESS_DENIED\" for example, the error can be understood by the controller without handling exceptions, and it would be decoupled from the HTTP status part."
}
] |
[
{
"body": "<blockquote>\n<p>In my actions (Controllers) I handle only data that comes from the request.</p>\n</blockquote>\n<p>If above is the case you might be better off handling validation before calling service class. In other words, prepare data into a format that business service classes can understand. Same applies about a decision on which HTTP Code to return.</p>\n<p>I am not sure why you have single responsibility controllers, a number of files would bloat very quickly in a larger application.</p>\n<p>Controller:</p>\n<pre><code>class CreateUserAction extends Action\n{ \n public function handle(UserCreateRequest $request): JsonResponse\n {\n return (new UserService)->create($request->validated(), $user);\n\n // OR\n $user = (new UserService)->create($request->validated(), $user);\n\n return response($user, Response::HTTP_CREATED);\n }\n}\n</code></pre>\n<p>I am not sure why you are using repository unless you are doing complex DB operation. Service should have all the business logic. This way service layer/business logic can be easier extracted and reused in other applications thanks to less dependencies.</p>\n<pre><code>use App/Models/User;\n\nclass UserService extends BaseService\n{ \n public function create(array $data): User\n { \n return (new userRepository)->create($data); \n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T07:54:04.677",
"Id": "244985",
"ParentId": "244946",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T15:19:23.777",
"Id": "244946",
"Score": "6",
"Tags": [
"php",
"design-patterns"
],
"Title": "Return payload in service layer"
}
|
244946
|
<p>I decided to make a password generator to get more familiar with Python.</p>
<p>I had to break up the code into two boxes due to weird Stack Exchange highlighting with the triple quotes.</p>
<p>How would you improve this program on the grounds of:</p>
<ul>
<li>Readability/cleanness,</li>
<li>Performance, and</li>
<li>Security.</li>
</ul>
<p>Feel free to include any other comments you have on it that may not fit into those three categories.</p>
<pre><code>import string
import random
import secrets
import argparse
import MyFormatter
alphaL = list(string.ascii_lowercase)
alphaU = list(string.ascii_uppercase)
numeric = list(string.digits)
special = list("!@#$%^&*")
special2 = list("""~`!@#$%^&*()+=_-{}[]\|:;"'?/<>,.""")
parser = argparse.ArgumentParser(
formatter_class=MyFormatter.MyFormatter,
description="Generates a password",
usage="",
)
parser.add_argument("-lc", "--lower", type=int, default=1, help="Minimum number of lowercase alpha characters")
parser.add_argument("-uc", "--upper", type=int, default=1, help="Minimum number of uppercase alpha characters")
parser.add_argument("-n", "--numeric", type=int, default=1, help="Minimum number of numeric characters")
parser.add_argument("-s", "--special", type=int, default=1, help="Minimum number of special characters")
parser.add_argument("-se", "--extended", action = 'store_const', default = False, const= True, help="Toggles the extendard special character subset. Passwords may not be accepted by all services")
parser.add_argument("-l", "--length", type=int, default=20, help="Length of the generated password")
args = parser.parse_args()
length = args.length
minimums = [
args.lower,
args.upper,
args.numeric,
args.special,
]
password = ""
for i in range(0, minimums[0]) :
password += secrets.choice(alphaL)
for i in range(0, minimums[1]) :
password += secrets.choice(alphaU)
for i in range(0, minimums[2]) :
password += secrets.choice(numeric)
if args.extended :
subset = alphaL + alphaU + numeric + special2
for i in range(0, minimums[3]) :
password += secrets.choice(special2)
elif minimums[3] :
subset = alphaL + alphaU + numeric + special
for i in range(0, minimums[3]) :
password += secrets.choice(special)
for i in range(0, 100) :
random.shuffle(subset)
for i in range(len(password), length) :
password += secrets.choice(subset)
for i in range(0, 100) :
password = ''.join(random.sample(password, len(password)))
print("Password: ", password)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:06:06.620",
"Id": "480959",
"Score": "2",
"body": "I cannot import MyFormatter, is it a module of yours? If so, please add it to the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T20:42:55.543",
"Id": "480990",
"Score": "0",
"body": "It is a module of mine, and I can add it if you'd like, but it just does some formatting for the help command and doesn't add anything to the program itself. I'll try to remember to replace \"MyFormater.MyFormater\" with \"HelpFormatter\""
}
] |
[
{
"body": "<h2>Redundant casts</h2>\n<pre><code>alphaL = list(string.ascii_lowercase)\nalphaU = list(string.ascii_uppercase)\nnumeric = list(string.digits)\nspecial = list("!@#$%^&*")\nspecial2 = list("""~`!@#$%^&*()+=_-{}[]\\|:;"'?/<>,.""")\n</code></pre>\n<p>Are you sure that casts to <code>list</code> are needed here? For example, <code>string.ascii_lowercase</code> is a <code>str</code>, which is already a sequence of strings (each one character). <code>secrets.choice</code> <a href=\"https://docs.python.org/3.8/library/secrets.html#secrets.choice\" rel=\"nofollow noreferrer\">says</a>:</p>\n<blockquote>\n<p>Return a randomly-chosen element from a non-empty sequence.</p>\n</blockquote>\n<p>So it will be able to handle the strings directly. Casting to a <code>list</code> is actually regressive, since <code>list</code> is mutable but these sequences should not be.</p>\n<h2>Latin</h2>\n<p>It's really pedantic, but <code>maximums</code> should be <code>maxima</code>.</p>\n<h2>Named arguments</h2>\n<p>There's no point to the <code>minimums</code> list. Every time you reference it, you reference one of its elements by index; so just reference the arguments from which it was initialized and get rid of the list.</p>\n<h2>Partially insecure entropy</h2>\n<p>Whereas you use <code>secrets</code> for some entropy, you use <code>random</code> in other cases, namely</p>\n<pre><code>random.shuffle(subset)\nrandom.sample(password, len(password))\n</code></pre>\n<p>This is not secure and needs to be replaced with <code>secrets</code> calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:09:33.213",
"Id": "480995",
"Score": "0",
"body": "Redundant casts: I didn't know python handled strings that way. Thank you\nLatin: Thank you\nRedundant predicate: If a user requests 0 special characters it would return false. But then that doesn't generate the subset currently which needs to be fixed\npartially insecure: To my knowledge, there's no shuffle and sample available within secrets and I see no documentation of such methods."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:14:27.137",
"Id": "480997",
"Score": "0",
"body": "I misinterpreted what you're doing with `minimums`; I've edited my answer to indicate that it shouldn't exist at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:15:33.740",
"Id": "480998",
"Score": "1",
"body": "_there's no shuffle and sample available within secrets_ - correct; you would need to implement equivalent behaviour from the primitives available in `secrets`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:46:39.787",
"Id": "244964",
"ParentId": "244949",
"Score": "3"
}
},
{
"body": "<h3>Possible bug</h3>\n<p>It looks like if <code>args.extended</code> is False (the default) and <code>args.special</code> is set to zero (using -s 0), then <code>subset</code> won't get defined and the subsequent call <code>random.shuffle(subset)</code> would throw an exception.</p>\n<h3>clarity</h3>\n<p>What is the benefit of the list <code>minimums</code>? <code>args.lower</code> is clearer than <code>minimums[0]</code>. Better yet, the <code>dest</code> argument to <code>parser.add_argument</code> lets you specify the a more descriptive name of the variable, like so:</p>\n<pre><code>parser.add_argument("-lc", "--lower", dest="min_lowercase",\n type=int, default=1, \n help="Minimum number of lowercase alpha characters")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:06:09.067",
"Id": "480994",
"Score": "0",
"body": "Possible Bug: Yes, that is an issue, thanks for pointing it out.\n\nClarity: It was from my original approach, which I decided against. Then when changing over to the current itteration I didn't think about it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:55:32.323",
"Id": "244965",
"ParentId": "244949",
"Score": "2"
}
},
{
"body": "<p>Already pointed out by other users</p>\n<ul>\n<li>There is no need to make lists from the strings as any sequence will do</li>\n<li><code>minimums</code> - you make bad names where the existing names were better</li>\n</ul>\n<h1>The if clause</h1>\n<pre><code>if args.extended :\n subset = alphaL + alphaU + numeric + special2\n for i in range(0, minimums[3]) :\n password += secrets.choice(special2)\nelif minimums[3] :\n subset = alphaL + alphaU + numeric + special\n for i in range(0, minimums[3]) :\n password += secrets.choice(special)\n</code></pre>\n<p>is erroneous. The check for <code>elif minimums[3]</code> shall be replaced by an <code>else:</code></p>\n<p>Also - just because you already switch on <code>args.extended</code> you are not required to pack all variation on that argument in there.\nYou prepare subset for the logically next function (choice from compound set) before even performing the current one (choice from special).\nThat results in less readability. There is nothing wrong in switching two times if required. However in this case you should simply switch</p>\n<pre><code>if args.extended:\n special = """~`!@#$%^&*()+=_-{}[]\\|:;"'?/<>,."""\nelse:\n special = "!@#$%^&*"\n</code></pre>\n<p>Then the choice from special/special2 collapses to the standard pattern.</p>\n<h1>Names</h1>\n<p>It was already mentioned that the minimum list is a name worse than the args attributes (which could be even more descriptive).\nAlso the names for your imports are bad and camel-cased. why not simply follow the existing naming scheme?</p>\n<pre><code>ascii_lowercase = string.ascii_lowercase\n</code></pre>\n<p>or even more straight</p>\n<pre><code>from string import ascii_lowercase\nfrom string import ascii_uppercase\nfrom string import digits\n</code></pre>\n<p>An extra bad name is <code>subset</code></p>\n<pre><code>subset = alphaL + alphaU + numeric + special\n</code></pre>\n<p>which is clearly a union or superset</p>\n<h1>The standard pattern</h1>\n<p>You do</p>\n<pre><code>for i in range(0, minimums[0]) :\n password += secrets.choice(alphaL)\n</code></pre>\n<p>the recommended way to character wise join a string is</p>\n<pre><code>password += "".join(secrets.choice(ascii_lowercase) for _ in range (0, args.lower)\n</code></pre>\n<h1>Cargo cult</h1>\n<p>You do</p>\n<pre><code>for i in range(0, 100) :\n random.shuffle(subset)\n</code></pre>\n<p>which is pointless. It is pointless to shuffle a 100 times. there is no extra quality in randomness compared to a single shuffle.\nIt is even more pointless to do that before apply <code>secrets.choice(subset)</code>. You could safely sort subset before choice().</p>\n<h1>Final shuffle</h1>\n<p>You do</p>\n<pre><code>for i in range(0, 100):\n print("Password: ", password)\n password = ''.join(random.sample(password, len(password)))\n</code></pre>\n<p>which I interpret as final shuffle to eliminate the order of the subsets <code>ascii_lowercase</code>, <code>ascii_uppercase</code>, ...</p>\n<p>Again you shuffle a 100 times which will not add any value compared to a single shuffle. To be cryptographically safe you should implement a shuffle based on <code>secrets.choice</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:18:25.977",
"Id": "480999",
"Score": "0",
"body": "If clause: I see how that is cleaner, thank you.\nNames: once again thank you.\nPattern: Fundamentally, why is this better? Behind the scenes, what's the difference? \nCargo Cult/Final shuffle: I assumed a few more shuffles (Since the program is still effectively instant) would be btter, which I was wrong. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:23:36.173",
"Id": "481000",
"Score": "1",
"body": "join is more efficient - see https://stackoverflow.com/questions/39312099/why-is-join-faster-than-in-python. that is neglible if joining two strings but makes a difference if joining in a loop."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T19:48:30.913",
"Id": "244973",
"ParentId": "244949",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T15:33:23.347",
"Id": "244949",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Password Generator Python"
}
|
244949
|
<p>In our project we use domain-driven design and our customer aggregate root is large. The unit tests for the aggregate root itself are simple (~50 or so tests), but I am struggling with the repository tests. Other aggregate roots in our system are not this large (number of fields), and the database table for this data is not normalized (around ~40-70 columns). The design of this table was done about 10 years ago and normalizing this table is not feasible right now.</p>
<p>Normally I would add a test for each separate field because I find that it provides better feedback when a bug occurs, code has changed, and the tests fail. It's really easy to find that test and fix that specific bug. In this case I have avoided that because of the number of fields and amount of setup code, and grouped the assertions together by the operation or scenario moreso than a unit.</p>
<p>What is not shown in this test either is that for <code>Add</code> there are still ~20-30 other columns in this table that must have default values, but I have chosen to not verify those due to test value assuming the database will default them. I'm not sure I am okay with that outcome because the database is not normalized. If it were, where some columns were on join tables or separate tables it would not be an issue at all.</p>
<p>How have you dealt with unit testing large aggregate roots like this? I thought about separating the factory for constructing <code>Customer</code> and unit testing that with tests for each field, and creating another factory or builder with the same intent for constructing <code>Data.Customer</code>. If I take that approach, the unit tests for the repository are straight forward given that they become just identity based verifications like <code>context.Verify(...Add...)</code> and ```builder.AddCustomerInfo(...)`.</p>
<p>Some of the code has <code>...</code> values that replace the actual values in our test code.</p>
<p><strong>Repository</strong></p>
<pre><code>namespace OurProduct.Core.Infrastructure
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Business;
using Data.Infrastructure;
/// <inheritdoc cref="ICustomerRepository" />
public class CustomerRepository : ICustomerRepository
{
private readonly IDateTime time;
/// <summary>
/// Initializes a new instance of the <see cref="CustomerRepository"/> class.
/// </summary>
/// <param name="database">The database context that will be used to access data.</param>
/// <param name="time">A time object that will be used to get system clock info.</param>
public CustomerRepository(IDataContext database, IDateTime time)
{
this.time = time;
Database = database;
Query = Database.Customers
.Include(p => p.Branch)
.Include(p => p.Branch.Bank)
.Include(p => p.CreditClassification)
.Include(p => p.LoanOfficer)
.Include(p => p.CustomerStatus)
.Include(p => p.CustomerType);
}
/// <summary>
/// Gets the database context that will be used to access data.
/// </summary>
public IDataContext Database
{
get;
}
/// <summary>
/// Gets the queryable expression that will be used to load customers.
/// </summary>
public IQueryable<Data.Customer> Query
{
get;
}
/// <inheritdoc />
public void Add(Customer customer)
{
var entity = new Data.Customer
{
CustomerId = customer.Id,
CustomerNumber = customer.Number,
CustomerFirstName = customer.FirstName,
CustomerMiddleName = customer.MiddleName,
CustomerLastName = customer.LastName,
CustomerName = customer.FullName,
BusinessName = customer.BusinessName,
TaxId = customer.TaxId,
PhoneFax = customer.ContactInfo.FaxNumber,
PhoneHome = customer.ContactInfo.HomeNumber,
PhoneMobile = customer.ContactInfo.MobileNumber,
PhoneWork = customer.ContactInfo.WorkNumber,
Email = customer.ContactInfo.Email,
Address1 = customer.ContactInfo.Address.Address1,
Address2 = customer.ContactInfo.Address.Address2,
City = customer.ContactInfo.Address.City,
State = customer.ContactInfo.Address.State,
ZipCode = customer.ContactInfo.Address.Zip,
...
ModifiedDate = time.Now,
BankId = ((ICustomer) customer).BankId,
CustomerBranchId = ((ICustomer) customer).BranchId,
CustomerTypeId = ((ICustomer) customer).TypeId,
CustomerStatusId = ((ICustomer) customer).StatusId,
ClassificationId = ((ICustomer) customer).RiskId,
CustomerOfficerId = ((ICustomer) customer).OfficerId,
};
Database.Add(entity);
}
/// <inheritdoc />
public IEnumerable<Customer> Find(IEnumerable<string> searchTerms, int? skip = 0, int? take = 25)
{
throw new NotImplementedException(@"Implement using full-text search in SQL using an indexed view.");
}
/// <inheritdoc />
public Customer FindById(Guid id)
{
Data.Customer entity;
try
{
entity = Query.Single(p => p.CustomerId == id);
}
catch (InvalidOperationException ex)
{
throw new ArgumentException(@"Identity does not exist", nameof(id), ex);
}
Customer customer = CustomerFactory.Create(entity);
return customer;
}
/// <inheritdoc />
public void Update(Customer customer)
{
var entity = Database.Find<Data.Customer>(customer.Id);
if (entity == null)
{
throw new ArgumentException(@"The specified customer does not exist in the repository.",
nameof(customer));
}
entity.CustomerFirstName = customer.FirstName;
entity.CustomerMiddleName = customer.MiddleName;
entity.CustomerLastName = customer.LastName;
entity.CustomerNumber = customer.FullName;
entity.BusinessName = customer.BusinessName;
entity.TaxId = customer.TaxId;
entity.PhoneFax = customer.ContactInfo.FaxNumber;
entity.PhoneHome = customer.ContactInfo.HomeNumber;
entity.PhoneMobile = customer.ContactInfo.MobileNumber;
entity.PhoneWork = customer.ContactInfo.WorkNumber;
entity.Email = customer.ContactInfo.Email;
entity.Address1 = customer.ContactInfo.Address.Address1;
entity.Address2 = customer.ContactInfo.Address.Address2;
entity.City = customer.ContactInfo.Address.City;
entity.State = customer.ContactInfo.Address.State;
entity.ZipCode = customer.ContactInfo.Address.Zip;
entity.ModifiedDate = time.Now;
entity.BankId = ((ICustomer) customer).BankId;
entity.CustomerBranchId = ((ICustomer) customer).BranchId;
entity.CustomerTypeId = ((ICustomer) customer).TypeId;
entity.CustomerStatusId = ((ICustomer) customer).StatusId;
entity.ClassificationId = ((ICustomer) customer).RiskId;
entity.CustomerOfficerId = ((ICustomer) customer).OfficerId;
}
/// <summary>
/// Factory class that creates new <see cref="Customer"/> instances.
/// </summary>
private static class CustomerFactory
{
/// <summary>
/// Creates a new customer from the specified data entity.
/// </summary>
/// <param name="entity">The <see cref="Data.Customer"/> data entity containing the data that will be used to create a new customer.</param>
/// <returns>Returns a new <see cref="Customer"/> instance.</returns>
public static Customer Create(Data.Customer entity)
{
var bank = new Bank(entity.Branch.Bank.BankId, entity.Branch.Bank.BankName);
var region = new Region(entity.Branch.RegionId, entity.Branch.Region.RegionName);
var branch = new Branch(entity.Branch.BranchId, entity.Branch.BranchName, bank, region);
var risk = new CustomerRisk(entity.CreditClassification.ClassificationId, entity.CreditClassification.ClassificationName);
var officer = new Officer(entity.LoanOfficer.OfficerId, entity.LoanOfficer.OfficerName, entity.LoanOfficer.OfficerTitle);
var status = new CustomerStatus(entity.CustomerStatus.CustomerStatusId, entity.CustomerStatus.CustomerStatusDescription, entity.CustomerStatus.IsActive);
var type = new CustomerType(entity.CustomerType.CustomerTypeId, entity.CustomerType.CustomerTypeDescription);
var customer = new Customer(entity.CustomerId,
entity.CustomerName,
entity.CustomerNumber,
type,
branch,
officer,
status,
risk)
{
FirstName = entity.CustomerFirstName,
MiddleName = entity.CustomerMiddleName,
LastName = entity.CustomerLastName,
BusinessName = entity.BusinessName,
TaxId = entity.TaxId
};
customer.ContactInfo.Email = entity.Email;
customer.ContactInfo.Address.Address1 = entity.Address1;
customer.ContactInfo.Address.Address2 = entity.Address2;
customer.ContactInfo.Address.City = entity.City;
customer.ContactInfo.Address.State = entity.State;
customer.ContactInfo.Address.Zip = entity.ZipCode;
customer.ContactInfo.FaxNumber = entity.PhoneFax;
customer.ContactInfo.HomeNumber = entity.PhoneHome;
customer.ContactInfo.WorkNumber = entity.PhoneWork;
customer.ContactInfo.MobileNumber = entity.PhoneMobile;
return customer;
}
}
}
}
</code></pre>
<p><strong>Unit Tests</strong></p>
<pre><code>namespace OurProduct.Core.Tests
{
using System;
using System.Linq;
using Business;
using Data;
using Data.Infrastructure;
using Infrastructure;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Bank = Business.Bank;
using Branch = Business.Branch;
using Customer = Business.Customer;
using CustomerStatus = Business.CustomerStatus;
using CustomerType = Business.CustomerType;
using Region = Business.Region;
[TestClass]
public class CustomerRepositoryTests
{
[TestMethod]
public void Add_CustomerIsNotNull_AddsCustomerToContext()
{
Guid customerId = Guid.Parse("{341E4B1C-EBA3-4587-B7A6-3C9641C39191}");
Guid bankId = Guid.Parse("{BE3590B5-F570-44B6-BAF1-86597CC404A6}");
Guid branchId = Guid.Parse("{2CA73ABE-0EFC-4C8F-9BD9-8D1F4E0E74DE}");
Guid regionId = Guid.Parse("{3C4D243F-47AF-4224-B805-55E2D8EB0DE0}");
Guid riskId = Guid.Parse("{DC0A5EF1-2376-4FA9-B09A-69CD1B28CEF5}");
Guid officerId = Guid.Parse("{8F02B1F8-1551-4124-B9B7-492FD18830DD}");
Guid statusId = Guid.Parse("{C53BE489-DDC5-4178-BA83-3422A58CC1D8}");
Guid typeId = Guid.Parse("{F2118364-64FB-44DC-8AC2-19223447A125}");
var bank = new Bank(bankId, "...");
var region = new Region(regionId, "West US");
var branch = new Branch(branchId, "...", bank, region);
var risk = new CustomerRisk(riskId, "Low Risk");
var officer = new Officer(officerId, "Bob Smith", "Senior Lender");
var status = new CustomerStatus(statusId, "Active", true);
var type = new CustomerType(typeId, "Consumer");
var customer = new Customer(customerId,
"John J Doe",
"CC001",
type,
branch,
officer,
status,
risk)
{
FirstName = "John",
MiddleName = "J",
LastName = "Doe",
BusinessName = "Local Shipping, Inc.",
TaxId = "123456789"
};
customer.ContactInfo.Email = "jjdoe@....net";
customer.ContactInfo.Address.Address1 = "...";
customer.ContactInfo.Address.Address2 = "";
customer.ContactInfo.Address.City = "...";
customer.ContactInfo.Address.State = "..";
customer.ContactInfo.Address.Zip = "...";
customer.ContactInfo.FaxNumber = "123 456 7890";
customer.ContactInfo.HomeNumber = "123 456 7891";
customer.ContactInfo.WorkNumber = "123 456 7892";
customer.ContactInfo.MobileNumber = "123 456 7893";
var context = new Mock<IDataContext>();
var time = new Mock<IDateTime>();
var repository = new CustomerRepository(context.Object, time.Object);
repository.Add(customer);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerId == customer.Id)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.BankId == ((ICustomer)customer).BankId)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerBranchId == ((ICustomer)customer).BranchId)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerTypeId == ((ICustomer)customer).TypeId)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerStatusId == ((ICustomer)customer).StatusId)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.ClassificationId == ((ICustomer)customer).RiskId)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerNumber == customer.Number)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerName == customer.FullName)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerFirstName == customer.FirstName)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerMiddleName == customer.MiddleName)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.CustomerLastName == customer.LastName)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.BusinessName == customer.BusinessName)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.TaxId == customer.TaxId)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.Email == customer.ContactInfo.Email)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.Address1 == customer.ContactInfo.Address.Address1)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.Address2 == customer.ContactInfo.Address.Address2)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.City == customer.ContactInfo.Address.City)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.State == customer.ContactInfo.Address.State)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.ZipCode == customer.ContactInfo.Address.Zip)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.PhoneHome == customer.ContactInfo.HomeNumber)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.PhoneFax == customer.ContactInfo.FaxNumber)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.PhoneWork == customer.ContactInfo.WorkNumber)), Times.Once);
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.PhoneMobile == customer.ContactInfo.MobileNumber)), Times.Once);
...
context.Verify(p => p.Add(It.Is<Data.Customer>(q => q.ModifiedDate == time.Object.Now)), Times.Once);
}
[TestMethod]
public void FindById_IdentityExists_ReturnsCustomer()
{
var entity = new Data.Customer
{
CustomerId = Guid.Parse("{E9B6F735-7984-4746-92CF-3EEA9E742209}"),
CustomerNumber = "CC001",
CustomerName = "John J Smith",
CustomerFirstName = "John",
CustomerMiddleName = "J",
CustomerLastName = "Smith",
Email = "johnjsmith@....net",
Address1 = "...",
Address2 = "",
City = "...",
State = "..",
ZipCode = "...",
PhoneFax = "123 456 7890",
PhoneWork = "123 456 7891",
PhoneMobile = "123 456 7892",
PhoneHome = "123 456 7893",
BusinessName = "Local Shipping, Inc.",
TaxId = "123456789",
CreditClassification = new CreditClassification
{
ClassificationId = Guid.Parse("{C31C1C79-5181-4D06-86EA-7AEDECDB8A01}"),
ClassificationName = "Low Risk"
},
CustomerType = new Data.CustomerType
{
CustomerTypeId = Guid.Parse("{3C1236F0-145D-4258-AC54-3EF1331B0B66}"),
CustomerTypeDescription = "Consumer"
},
CustomerStatus = new Data.CustomerStatus
{
CustomerStatusId = Guid.Parse("{0567B8ED-F947-4BF5-936F-630AB3677095}"),
CustomerStatusDescription = "Active"
},
LoanOfficer = new LoanOfficer
{
OfficerId = Guid.Parse("{58DEB0AD-3830-437E-B22D-04376AB5296C}"),
OfficerName = "Bob Doe",
OfficerTitle = "Senior Lender"
},
Branch = new Data.Branch
{
BranchId = Guid.Parse("{003ED79C-938E-4DB8-9A3C-2AA35E64DAEB}"),
BranchName = "...",
Region = new Data.Region
{
RegionId = Guid.Parse("{F2992F17-B94A-4CE5-83D1-B3E6A2AC31A7}"),
RegionName = "West US"
},
Bank = new Data.Bank
{
BankId = Guid.Parse("{11D291A4-3F93-443B-93C8-88621F25891A}"),
BankName = "..."
}
}
};
var context = new Mock<IDataContext>();
context.Setup(p => p.Customers).Returns(new[] {entity}.AsQueryable);
var repository = new CustomerRepository(context.Object, Mock.Of<IDateTime>());
Customer customer = repository.FindById(entity.CustomerId);
Assert.AreEqual("{e9b6f735-7984-4746-92cf-3eea9e742209}", customer.Id.ToString("B"));
Assert.AreEqual("{11d291a4-3f93-443b-93c8-88621f25891a}", ((ICustomer)customer).BankId.ToString("B"));
Assert.AreEqual("{003ed79c-938e-4db8-9a3c-2aa35e64daeb}", ((ICustomer)customer).BranchId.ToString("B"));
Assert.AreEqual("{3c1236f0-145d-4258-ac54-3ef1331b0b66}", ((ICustomer)customer).TypeId.ToString("B"));
Assert.AreEqual("{0567b8ed-f947-4bf5-936f-630ab3677095}", ((ICustomer)customer).StatusId.ToString("B"));
Assert.AreEqual("{c31c1c79-5181-4d06-86ea-7aedecdb8a01}", ((ICustomer)customer).RiskId.ToString("B"));
Assert.AreEqual("CC001", customer.Number);
Assert.AreEqual("John J Smith", customer.FullName);
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("J", customer.MiddleName);
Assert.AreEqual("Smith", customer.LastName);
Assert.AreEqual("johnjsmith@....net", customer.ContactInfo.Email);
Assert.AreEqual("...", customer.ContactInfo.Address.Address1);
Assert.AreEqual("", customer.ContactInfo.Address.Address2);
Assert.AreEqual("...", customer.ContactInfo.Address.City);
Assert.AreEqual("...", customer.ContactInfo.Address.State);
Assert.AreEqual("81003", customer.ContactInfo.Address.Zip);
Assert.AreEqual("123 456 7890", customer.ContactInfo.FaxNumber);
Assert.AreEqual("123 456 7893", customer.ContactInfo.HomeNumber);
Assert.AreEqual("123 456 7892", customer.ContactInfo.MobileNumber);
Assert.AreEqual("123 456 7891", customer.ContactInfo.WorkNumber);
Assert.AreEqual("Low Risk", customer.Risk);
Assert.AreEqual("Consumer", customer.Type);
Assert.AreEqual("Active", customer.Status);
Assert.AreEqual("...", customer.Branch);
Assert.AreEqual("...", customer.Bank);
Assert.AreEqual("Bob Doe", customer.Officer);
Assert.AreEqual("Local Shipping, Inc.", customer.BusinessName);
Assert.AreEqual("123456789", customer.TaxId);
}
[TestMethod]
public void FindById_IdentityDoesNotExist_ThrowsException()
{
var repository = new CustomerRepository(Mock.Of<IDataContext>(), Mock.Of<IDateTime>());
Assert.ThrowsException<ArgumentException>(() => repository.FindById(Guid.Empty));
}
[TestMethod]
public void Update_IdentityDoesNotExist_ThrowsException()
{
var customer = new Customer(Guid.Empty,
"John J Doe",
"CC001",
Mock.Of<ICustomerType>(),
Mock.Of<IBranch>(),
Mock.Of<IOfficer>(),
Mock.Of<ICustomerStatus>(),
Mock.Of<ICustomerRisk>());
var repository = new CustomerRepository(Mock.Of<IDataContext>(), Mock.Of<IDateTime>());
Assert.ThrowsException<ArgumentException>(() => repository.Update(customer));
}
[TestMethod]
public void Update_IdentityExists_UpdatesCustomer()
{
Guid customerId = Guid.Parse("{341E4B1C-EBA3-4587-B7A6-3C9641C39191}");
Guid bankId = Guid.Parse("{BE3590B5-F570-44B6-BAF1-86597CC404A6}");
Guid branchId = Guid.Parse("{2CA73ABE-0EFC-4C8F-9BD9-8D1F4E0E74DE}");
Guid regionId = Guid.Parse("{3C4D243F-47AF-4224-B805-55E2D8EB0DE0}");
Guid riskId = Guid.Parse("{DC0A5EF1-2376-4FA9-B09A-69CD1B28CEF5}");
Guid officerId = Guid.Parse("{8F02B1F8-1551-4124-B9B7-492FD18830DD}");
Guid statusId = Guid.Parse("{C53BE489-DDC5-4178-BA83-3422A58CC1D8}");
Guid typeId = Guid.Parse("{F2118364-64FB-44DC-8AC2-19223447A125}");
var bank = new Bank(bankId, "...");
var region = new Region(regionId, "West US");
var branch = new Branch(branchId, "...", bank, region);
var risk = new CustomerRisk(riskId, "Low Risk");
var officer = new Officer(officerId, "Bob Smith", "Senior Lender");
var status = new CustomerStatus(statusId, "Active", true);
var type = new CustomerType(typeId, "Consumer");
var customer = new Customer(customerId,
"John J Doe",
"CC001",
type,
branch,
officer,
status,
risk)
{
FirstName = "John",
MiddleName = "J",
LastName = "Doe",
BusinessName = "Local Shipping, Inc.",
TaxId = "123456789"
};
customer.ContactInfo.Email = "jjdoe@....net";
customer.ContactInfo.Address.Address1 = "...";
customer.ContactInfo.Address.Address2 = "";
customer.ContactInfo.Address.City = "...";
customer.ContactInfo.Address.State = "...";
customer.ContactInfo.Address.Zip = "...";
customer.ContactInfo.FaxNumber = "123 456 7890";
customer.ContactInfo.HomeNumber = "123 456 7891";
customer.ContactInfo.WorkNumber = "123 456 7892";
customer.ContactInfo.MobileNumber = "123 456 7893";
var context = new Mock<IDataContext>();
var entity = new Data.Customer {CustomerId = customer.Id};
context.Setup(p => p.Find<Data.Customer>(It.Is<Guid>(q => q == customer.Id)))
.Returns(entity);
var repository = new CustomerRepository(context.Object, Mock.Of<IDateTime>());
repository.Update(customer);
Assert.AreEqual(customer.FirstName, entity.CustomerFirstName);
Assert.AreEqual(customer.MiddleName, entity.CustomerMiddleName);
Assert.AreEqual(customer.LastName, entity.CustomerLastName);
Assert.AreEqual(customer.FullName, entity.CustomerNumber);
Assert.AreEqual(customer.BusinessName, entity.BusinessName);
Assert.AreEqual(customer.TaxId, entity.TaxId);
Assert.AreEqual(customer.ContactInfo.FaxNumber, entity.PhoneFax);
Assert.AreEqual(customer.ContactInfo.HomeNumber, entity.PhoneHome);
Assert.AreEqual(customer.ContactInfo.MobileNumber, entity.PhoneMobile);
Assert.AreEqual(customer.ContactInfo.WorkNumber, entity.PhoneWork);
Assert.AreEqual(customer.ContactInfo.Email, entity.Email);
Assert.AreEqual(customer.ContactInfo.Address.Address1, entity.Address1);
Assert.AreEqual(customer.ContactInfo.Address.Address2, entity.Address2);
Assert.AreEqual(customer.ContactInfo.Address.City, entity.City);
Assert.AreEqual(customer.ContactInfo.Address.State, entity.State);
Assert.AreEqual(customer.ContactInfo.Address.Zip, entity.ZipCode);
Assert.AreEqual(bankId, entity.BankId);
Assert.AreEqual(branchId, entity.CustomerBranchId);
Assert.AreEqual(typeId, entity.CustomerTypeId);
Assert.AreEqual(statusId, entity.CustomerStatusId);
Assert.AreEqual(riskId, entity.ClassificationId);
Assert.AreEqual(officerId, entity.CustomerOfficerId);
//Assert.AreEqual(time.Now, entity.ModifiedDate);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:03:59.117",
"Id": "480993",
"Score": "1",
"body": "Have you considered creating a mapper between Data.Customer and Business.Customer? Then tests to assert on mapping would be easier and repository tests would focus on adding, retrieving, querying..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T16:40:07.217",
"Id": "244952",
"Score": "4",
"Tags": [
"c#",
"unit-testing",
"repository",
"ddd"
],
"Title": "Is there a better way to unit test a repository for a large aggregate root?"
}
|
244952
|
<p>I am doing a research to implement a dynamic system of parse and generation of fixed width flat files in C++....</p>
<p>The system works, but, it is not reliable ...</p>
<p>The class "FlatFileStructure", holds all the informations about the field in particular, such as position on the line, size, type of field (numeric, alpha-numeric and date) and keeps the variable pointer where the information that should be written to the file will be, or that will be read from the file</p>
<p>Like in this line:</p>
<pre><code>_descricaoCamposHeader->push_back(new FlatFileStructure(0, 1, TipoDoCampo::NUMERICO, "0", &_header->tipoDoRegistro));
</code></pre>
<p>the biggest problem exists, in the case of the information stored in the vectors "_descricaoCamposTitulo" and "_descricaoCamposTituloMensagens", where there can be N lines referring to this record within the file</p>
<p>On the method "void geraArquivo()", I do a 'memcpy' to send all the data to the '_titulo' variable, so, in this way, the system can save the data on the file...</p>
<p>My question is ... what can I do to make this code better and more secure and without burdening the memory?
my first attempt, for each instance of the 'model' class, I created a copy of the vector that contains the variable pointer, so it worked perfectly but the memory consumption was very high</p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <memory>
#include <cstring>
#include <fstream>
#include <ctime>
#include "stringutil.h"
//#include "Datetime/datetimehelper.h"
typedef enum
{
ALFANUMERICO,
NUMERICO,
NUMERICO_SEQUENCIAL,
DATA
} TipoDoCampo;
template<typename T>
struct deleter : std::unary_function<const T*, void>
{
void operator() (const T* ptr) const
{
if (ptr != nullptr)
{
delete ptr;
ptr = nullptr;
}
}
};
class FlatFileStructure
{
private:
size_t _inicialPosition;
size_t _size;
TipoDoCampo _tipoDoCampo;
std::string _defaultContent;
std::string* _content;
public:
FlatFileStructure(size_t inicialPosition, size_t size, TipoDoCampo tipoDoCampo)
: _inicialPosition(inicialPosition),
_size(size),
_tipoDoCampo(tipoDoCampo)
{}
FlatFileStructure(size_t inicialPosition, size_t size, TipoDoCampo tipoDoCampo, std::string defaultContent)
: _inicialPosition(inicialPosition),
_size(size),
_tipoDoCampo(tipoDoCampo),
_defaultContent(defaultContent)
{}
FlatFileStructure(size_t inicialPosition, size_t size, TipoDoCampo tipoDoCampo, std::string* content)
: _inicialPosition(inicialPosition),
_size(size),
_tipoDoCampo(tipoDoCampo),
_content(content)
{
}
FlatFileStructure(size_t inicialPosition, size_t size, TipoDoCampo tipoDoCampo, std::string defaultContent, std::string* content)
: _inicialPosition(inicialPosition),
_size(size),
_tipoDoCampo(tipoDoCampo),
_defaultContent(defaultContent),
_content(content)
{
}
size_t getPosicaoInicial() { return _inicialPosition; }
size_t getsize() { return _size; }
TipoDoCampo getTipoDoCampo() { return _tipoDoCampo; }
std::string getcontent()
{
if (!_defaultContent.empty())
return _defaultContent;
return std::string(*_content);
}
std::string getcontentFormatado()
{
if (_content->empty())
*_content = "";
std::string content = this->getcontent();
if (_tipoDoCampo == TipoDoCampo::ALFANUMERICO)
{
if (content.size() > _size)
content = util::truncate(content, _size);
content = util::pad_right(content, _size, ' ');
}
else if (_tipoDoCampo == TipoDoCampo::NUMERICO || _tipoDoCampo == TipoDoCampo::NUMERICO_SEQUENCIAL)
{
if (content.size() > _size)
content = util::truncate_numeric(content, _size);
content = util::pad_left(content, _size, '0');
}
//else if (_tipoDoCampo == TipoDoCampo::DATA)
//{
// if (content.empty())
// content = dragonfly::DateTimeHelper::hoje("%d%m%y");
// else
// content = dragonfly::DateTimeHelper::formataData_de_para(content, "%d.%m.%Y", "%d%m%y");
//}
return content;
}
void setcontent(std::string content)
{
*_content = std::string(content);
}
};
class FlatFile
{
private:
size_t _lineSize;
public:
FlatFile(size_t lineSize) : _lineSize(lineSize) {}
std::string buildLine(std::vector<FlatFileStructure*>* campos)
{
std::string str = util::pad_left("", _lineSize, ' ');
for (int i = 0; i < campos->size(); i++)
{
FlatFileStructure* ffs = (*campos)[i];
std::string content = ffs->getcontentFormatado();
//str = str.replace(ffs->getPosicaoInicial(), content.size(), content.c_str());
strncpy(&str[ffs->getPosicaoInicial()], content.c_str(), content.size());
}
return std::string(str);
}
void readLine(std::string line, std::vector<FlatFileStructure*>* campos)
{
for (int i = 0; i < campos->size(); i++)
{
FlatFileStructure* ffs = (*campos)[i];
std::string content = line.substr(ffs->getPosicaoInicial(), ffs->getsize());
ffs->setcontent(content);
}
}
};
class ArquivoDeTeste
{
private:
class Header
{
public:
std::string tipoDoRegistro;
std::string identificacaoDaRemessa;
std::string literalRemessa;
std::string codigoDeServico;
std::string literalServico;
std::string codigoDaEmpresa;
std::string nomeDaEmpresa;
std::string numeroDoBanco;
std::string nomeDoBanco;
std::string dataDeGravacao;
std::string identificacaoDoSistema;
std::string numeroSequencialDaRemessa;
std::string sequencial;
};
class TituloMensagens
{
public:
std::string tipoDoRegistro;
std::string mensagem1;
std::string mensagem2;
std::string sequencial;
};
class Titulo
{
public:
std::string tipoDoRegistro;
std::string nossoNumero;
std::string dvNossoNumero;
std::string nomePagador;
std::string sequencial;
TituloMensagens mensagens;
};
Header* _header;
Titulo* _titulo;
std::vector<Titulo*>* _titulos;
std::vector<FlatFileStructure*>* _descricaoCamposTituloMensagens;
std::vector<FlatFileStructure*>* _descricaoCamposHeader;
std::vector<FlatFileStructure*>* _descricaoCamposTitulo;
public:
ArquivoDeTeste()
: _header(new Header()),
_titulo(new Titulo()),
_titulos(nullptr)
{
inicializaDescricaoCamposHeader();
inicializaDescricaoCamposTitulo();
inicializaDescricaoCamposTituloMensagens();
}
~ArquivoDeTeste()
{
if (_header != nullptr)
{
delete _header;
_header = nullptr;
}
if (_titulo != nullptr)
{
delete _titulo;
_titulo = nullptr;
}
std::for_each(_descricaoCamposHeader->begin(), _descricaoCamposHeader->end(), deleter<FlatFileStructure>());
_descricaoCamposHeader->clear();
delete _descricaoCamposHeader;
std::for_each(_descricaoCamposTituloMensagens->begin(), _descricaoCamposTituloMensagens->end(), deleter<FlatFileStructure>());
_descricaoCamposTituloMensagens->clear();
delete _descricaoCamposTituloMensagens;
std::for_each(_descricaoCamposTitulo->begin(), _descricaoCamposTitulo->end(), deleter<FlatFileStructure>());
_descricaoCamposTitulo->clear();
delete _descricaoCamposTitulo;
std::for_each(_titulos->begin(), _titulos->end(), deleter<Titulo>());
_titulos->clear();
delete _titulos;
}
private:
void inicializaDescricaoCamposHeader()
{
_descricaoCamposHeader = new std::vector<FlatFileStructure*>();
_descricaoCamposHeader->push_back(new FlatFileStructure(0, 1, TipoDoCampo::NUMERICO, "0", &_header->tipoDoRegistro));
_descricaoCamposHeader->push_back(new FlatFileStructure(1, 1, TipoDoCampo::NUMERICO, "1", &_header->identificacaoDaRemessa));
_descricaoCamposHeader->push_back(new FlatFileStructure(2, 7, TipoDoCampo::ALFANUMERICO, "REMESSA", &_header->literalRemessa));
_descricaoCamposHeader->push_back(new FlatFileStructure(9, 2, TipoDoCampo::NUMERICO, "01", &_header->codigoDeServico));
_descricaoCamposHeader->push_back(new FlatFileStructure(11, 15, TipoDoCampo::ALFANUMERICO, "COBRANCA", &_header->literalServico));
_descricaoCamposHeader->push_back(new FlatFileStructure(26, 20, TipoDoCampo::NUMERICO, &_header->codigoDaEmpresa));
_descricaoCamposHeader->push_back(new FlatFileStructure(46, 30, TipoDoCampo::ALFANUMERICO, &_header->nomeDaEmpresa));
_descricaoCamposHeader->push_back(new FlatFileStructure(76, 3, TipoDoCampo::NUMERICO, "999", &_header->numeroDoBanco));
_descricaoCamposHeader->push_back(new FlatFileStructure(79, 15, TipoDoCampo::ALFANUMERICO, "XXXXXXXX", &_header->nomeDoBanco));
//_descricaoCamposHeader->push_back(new FlatFileStructure(94, 6, TipoDoCampo::DATA, &_header->dataDeGravacao));
_descricaoCamposHeader->push_back(new FlatFileStructure(108, 2, TipoDoCampo::ALFANUMERICO, "ZZ", &_header->identificacaoDoSistema));
_descricaoCamposHeader->push_back(new FlatFileStructure(110, 7, TipoDoCampo::NUMERICO, &_header->numeroSequencialDaRemessa));
_descricaoCamposHeader->push_back(new FlatFileStructure(394, 6, TipoDoCampo::NUMERICO_SEQUENCIAL, "000001", &_header->sequencial));
}
void inicializaDescricaoCamposTitulo()
{
_descricaoCamposTitulo = new std::vector<FlatFileStructure*>();
_descricaoCamposTitulo->push_back(new FlatFileStructure(0, 1, TipoDoCampo::NUMERICO, "1", &_titulo->tipoDoRegistro));
_descricaoCamposTitulo->push_back(new FlatFileStructure(70, 11, TipoDoCampo::NUMERICO, &_titulo->nossoNumero));
_descricaoCamposTitulo->push_back(new FlatFileStructure(81, 1, TipoDoCampo::ALFANUMERICO, &_titulo->dvNossoNumero));
_descricaoCamposTitulo->push_back(new FlatFileStructure(234, 40, TipoDoCampo::ALFANUMERICO, &_titulo->nomePagador));
_descricaoCamposTitulo->push_back(new FlatFileStructure(394, 6, TipoDoCampo::NUMERICO_SEQUENCIAL, &_titulo->sequencial));
}
void inicializaDescricaoCamposTituloMensagens()
{
_descricaoCamposTituloMensagens = new std::vector<FlatFileStructure*>();
_descricaoCamposTituloMensagens->push_back(new FlatFileStructure( 0, 1, TipoDoCampo::NUMERICO, "2", &_titulo->mensagens.tipoDoRegistro));
_descricaoCamposTituloMensagens->push_back(new FlatFileStructure( 1, 80, TipoDoCampo::ALFANUMERICO, &_titulo->mensagens.mensagem1));
_descricaoCamposTituloMensagens->push_back(new FlatFileStructure(81, 80, TipoDoCampo::ALFANUMERICO, &_titulo->mensagens.mensagem2));
_descricaoCamposTituloMensagens->push_back(new FlatFileStructure(394, 6, TipoDoCampo::NUMERICO_SEQUENCIAL, &_titulo->mensagens.sequencial));
}
public:
void parseArquivo()
{
std::unique_ptr<FlatFile> ff(new FlatFile(400));
std::string line;
std::ifstream infile("out.rem");
bool registroProcessado = false;
while (std::getline(infile, line))
{
switch (line[0])
{
case '0':
break;
case '1':
{
if (_titulos == nullptr)
_titulos = new std::vector<Titulo*>();
if (registroProcessado == true)
{
_titulos->push_back(new Titulo(*_titulo));
registroProcessado = false;
memset(_titulo, '\0', sizeof(Titulo));
}
ff->readLine(line, _descricaoCamposTitulo);
registroProcessado = true;
}
break;
case '2':
{
ff->readLine(line, _descricaoCamposTituloMensagens);
break;
}
case '9':
_titulos->push_back(new Titulo(*_titulo));
break;
default:
break;
}
}
}
void geraArquivo()
{
// Gera os titulos
if (_titulos == nullptr)
_titulos = new std::vector<Titulo*>();
for (int i = 2; i <= 100; i++)
{
auto tmpTitulo = new Titulo();
if (i % 2 == 0)
{
tmpTitulo->nossoNumero = "1234567891";
tmpTitulo->nomePagador = "AAAAAAAAAABBBBBBBBBBCCCCCCCCCCDDDDDDDDDDEEEEEEEEEEFFFFFFFFFF";
tmpTitulo->mensagens.mensagem1 = "Ola " + util::to_string<std::string, int>(i);
tmpTitulo->mensagens.mensagem2 = "Ola " + util::to_string<std::string, int>(i + 1);
}
else
{
tmpTitulo->nossoNumero = "1213141516";
tmpTitulo->nomePagador = "FFFFFFFFFFEEEEEEEEEEDDDDDDDDDDCCCCCCCCCCBBBBBBBBBBAAAAAAAAAA";
}
_titulos->push_back(tmpTitulo);
}
std::ofstream outputFile("out.rem");
std::unique_ptr<FlatFile> ff(new FlatFile(400));
// Gera o Header
outputFile << ff->buildLine(_descricaoCamposHeader) << std::endl;
// Gera os titulos
int seq = 2;
for (auto it = _titulos->begin(); it != _titulos->end(); ++it) {
//_titulo = new (_titulo) Titulo(*(*it));
memcpy(_titulo, (*it), sizeof(Titulo));
_titulo->sequencial = util::to_string<std::string, int>(seq++);
outputFile << ff->buildLine(_descricaoCamposTitulo) << std::endl;
if (_titulo->mensagens.mensagem1.size() != 0 || _titulo->mensagens.mensagem2.size() != 0)
{
_titulo->mensagens.sequencial = util::to_string<std::string, int>(seq++);
outputFile << ff->buildLine(_descricaoCamposTituloMensagens) << std::endl;
}
}
outputFile << "9" << std::endl;
memset(_titulo, '\0', sizeof(Titulo));
outputFile.close();
}
};
void gera() {
std::unique_ptr<ArquivoDeTeste> arquivoTeste(new ArquivoDeTeste());
arquivoTeste->geraArquivo();
}
void le() {
std::unique_ptr<ArquivoDeTeste> arquivoTeste(new ArquivoDeTeste());
arquivoTeste->parseArquivo();
}
int main()
{
gera();
le();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:09:48.477",
"Id": "480962",
"Score": "0",
"body": "Can you expand on `it is not reliable`? Are there errors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:15:47.013",
"Id": "480964",
"Score": "0",
"body": "The code works well... but it is visible that it is not reliable ..., starting with this 'memcpy' that I made to move the information to the pointer that is used to store the read or write data of the file.... I believe there is a better way to do this that I’m doing, but, I don’t know how"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:23:49.653",
"Id": "480967",
"Score": "0",
"body": "OK. I would categorize that as \"questionable design\" rather than \"unreliability\", but we will see what the reviews come up with."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T16:55:59.263",
"Id": "244954",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Dynamic fixed width flat file parser in C++"
}
|
244954
|
<h1>Note: I show almost all of my code for completeness, but I really only want the review to focus on <strong>Session.hs</strong>, <strong>Handler.hs</strong>, and maybe <strong>Controller.hs</strong>. I can delete the extra code from the review or collapse it to definitions.</h1>
<h1>The project</h1>
<p>I've never heard of <code>monad transformers</code> and <code>monad stacks</code> before, but I've decided to learn them while making a real world Haskell application. This is a Telegram bot that can do various tasks based on the user's commands. The project is meant to teach me about monad stacks and how to use them properly, while also being a useful tool for my own disposal.</p>
<h1>The scope of the review</h1>
<p>The project is on the proof of concept stage. The bot is working, but right now it's only a silly number guessing game. Some important features like logging and security are missing. Nothing is final here, and every part of the program will be added upon, but the basis is done, and I need to know that the foundation is good and flexible enough before moving on. I want this review to focus on my implementation and usage of monad stacks and monad transformers. I would also like know about my idiomatic mistakes that have to do with Haskell. Focus on what is done wrong, not what could be added.</p>
<p>For example, I know that I need a WriterT for logging somewhere in the stack, so don't tell it to me, but I would like to hear if stack implementation prevents me from doing it later. I don't want to hear about the missing error handling in the API communication code, but I would like to hear about mistakes in the error handling that I've already done.</p>
<h1>A working example</h1>
<p><a href="https://i.stack.imgur.com/jugu2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jugu2.png" alt="A working example" /></a></p>
<p>One example of a bot's function would be a number guessing game. The user writes a command <code>guess</code> to initiate the game. The bot generates a random number between 1 and 10. The user then proceeds to guess the number with multiple attempts while the bot provides the information if the guessed numbers are greater or less than what was generated.</p>
<h1>General introduction</h1>
<p>The framework has 3 main components: <code>controller</code>, <code>session</code> and <code>handlers</code>.</p>
<p>A <code>handler</code> is a subroutine that reacts to it's specific command and the follow-ups. In the example, the part that generates a number and provides feedback is a handler.</p>
<p>The <code>session</code> is a persistent storage that is attached to one chain of messages. When a handler needs to save something, it places the information in the session. The handler's reply to the user is then associated with this session, and when the user replies to the handler's message, the session is restored and passed back to the handler. The session also stores <strong>which</strong> handler is to be used for the reply handling: the used did not need to type 'guess 5' in the example: just '5' was enough.</p>
<p>The <code>controller</code> is a piece that glues these components together. When the user sends any message to the bot, a controller creates or restores the session and passes the control to the appropriate handler.</p>
<p>There is also a component to handle the Telegram API interactions, but I'll leave it out of the scope because it's a work in progress and it's not a part of the stack for now.</p>
<h1>The code</h1>
<h2>Config.hs</h2>
<p>This is a simple monad that reads the appication config. Note the lack of error handling here: if the config format is invalid the program may crash as it will, I don't care about proper error messages at this point.</p>
<pre><code>{-# LANGUAGE PackageImports #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Config ( Config(..)
, ConfigT
, runConfigT
, asks
, loadConfig
) where
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Reader (MonadReader, asks)
import qualified Control.Monad.Trans.Reader as Reader (ReaderT(..))
import "yaml-config" Data.Yaml.Config (load, lookup)
import Prelude hiding(lookup)
data Config = Config
{
telegram_bot_api_key :: String,
dropbox_access_token :: String
}
newtype ConfigT a = ConfigT
{ runConfigTa :: Reader.ReaderT Config IO a
} deriving ( Applicative
, Functor
, Monad
, MonadIO
, MonadReader Config )
runConfigT :: ConfigT a -> Config -> IO a
runConfigT = Reader.runReaderT . runConfigTa
loadConfig :: IO Config
loadConfig = do
config <- load "./config/secrets.yaml"
telegram <- lookup "telegram_bot_api_key" config
dropbox <- lookup "dropbox_access_token" config
return Config
{ telegram_bot_api_key = telegram
, dropbox_access_token = dropbox
}
</code></pre>
<h2>Session.hs</h2>
<p>When a user invokes a command, a new empty session is created. When a user answers a bot's message, an existing session is restored. When a session is restored, it is deleted from the drive. If the bot answers a user and the session has any info saved, it is written back to the drive with the new id. The id of a session is the id of this reply in Telegram. When a handler is finished with the whole interaction (the game is won in the example) the session can be cleared via <code>deleteSession</code>. When a handler action finishes and a the session is clear, no further files are created. This way, only active sessions are stored, and only for the last messasges in each active session (so that you can't continue the sesion from a middle).</p>
<p>I've created a new class <code>MonadSession</code> here, but I wonder if it is any good. I failed to use it as I have planned in the end.</p>
<p>Don't worry about the implementation details: I know that sessions can be stored in a database, that the usage of <code>read</code> and <code>show</code> is not elegant, and that using <code>SomeException</code> is bad.</p>
<pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
module Session ( SessionError
, SessionT
, MonadSession(..)
, withSession
) where
import Control.Exception (SomeException, try, tryJust, catchJust)
import Control.Monad (forM_, unless)
import Control.Monad.Except (MonadError, throwError, runExceptT, guard)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.State (MonadState, state, modify, gets)
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.Except (ExceptT(..))
import Control.Monad.Trans.State.Lazy (StateT, runStateT)
import qualified Data.Map as Map
import Data.String.Utils (maybeRead)
import System.Directory (removeFile, doesFileExist)
import System.IO.Error (isDoesNotExistError)
import Config (ConfigT)
-- Public
newtype SessionError = SessionError String
instance Show SessionError where
show (SessionError message) = "Session error: " ++ message
data Session = Session
{ originalId :: Maybe String
, newId :: Maybe String
, info :: Map.Map String String
}
class Monad m => MonadSession m where
save :: Show a => String -> a -> m ()
setId :: String -> m ()
recall :: Read a => String -> m a
tryRecall :: Read a => String -> m (Maybe a)
deleteSession :: m ()
newtype SessionT m a = SessionT
{ runSessionT :: StateT Session (ExceptT SessionError m) a
} deriving ( Applicative
, Functor
, Monad
, MonadIO
, MonadState Session
, MonadError SessionError
)
instance MonadTrans SessionT where
lift = SessionT . liftState . liftExcept
where liftState = lift :: Monad m => m a -> StateT Session m a
liftExcept = lift :: Monad m => m a -> ExceptT SessionError m a
instance Monad m => MonadSession (SessionT m) where
save key value = modify (\session -> session {info = Map.insert key (show value) $ info session})
setId newId = modify (\session -> session { newId = Just newId })
recall key = maybe (throwError $ SessionError $ "Missing field: " ++ key) return =<< tryRecall key
tryRecall key = gets ((read <$>) . Map.lookup key . info)
deleteSession = modify (\session -> session {info = Map.empty})
withSession :: MonadIO m => Maybe String -> SessionT m a -> m (Either SessionError a)
withSession sessionId scoped =
runExceptT (runAndSave scoped =<< maybe createSession getSession sessionId)
where
runAndSave scoped session = do
(result, session') <- runStateT (runSessionT scoped) session
saveSession session'
return result
-- Private
sessionFileName :: String -> String
sessionFileName sessionId = sessionId ++ ".ses"
createSession :: MonadIO m => ExceptT SessionError m Session
createSession = return $ Session
{ originalId = Nothing
, newId = Nothing
, info = Map.empty
}
getSession :: MonadIO m => String -> ExceptT SessionError m Session
getSession sessionId = do
saved <- liftIO (tryJust (guard . isDoesNotExistError)
(readFile $ sessionFileName sessionId)) >>=
either (const $ throwError $ SessionError "Session not found") return
info <- maybe (throwError $ SessionError "Session data corrupted") return $
maybeRead saved
return $ Session { originalId = Just sessionId
, newId = Nothing
, info = info }
saveSession :: MonadIO m => Session -> ExceptT SessionError m ()
saveSession session =
let oldSessionName = sessionFileName <$> originalId session
newSessionName = sessionFileName <$> newId session
sessionInfo = show $ info session
in liftIO (try (forM_ newSessionName $ \sessionFile -> do
unless (Map.null $ info session) $
writeFile sessionFile sessionInfo
forM_ oldSessionName justDelete)) >>=
either handleException return
where handleException :: MonadIO m => SomeException -> ExceptT SessionError m ()
handleException exception = throwError $ SessionError $
"Session failed to save " ++ show exception
justDelete :: String -> IO ()
justDelete fileName =
catchJust (guard . isDoesNotExistError) (removeFile fileName) return
</code></pre>
<h2>Handler.hs</h2>
<p>There are a lot of constructs in this file.</p>
<p>First of all, there is <code>data Handler</code>. This structure represents an actual handler. Every handler has a command that initiates it ('guess' in our example). Every handler must be able to respond to messages starting with this command (function <code>handleMessage</code>). Some handlers may handle responses via <code>handleResponse</code>, and buttom presses via <code>handleAnswer</code>, hense the <code>Maybe</code>. This structure will be extended in the future to allow handling file attachments and other interactions.</p>
<p><code>data HandlerContext</code> is everything a handler needs to at least send an error message to the user.</p>
<p><code>HandlerT</code> adds handling functionality to the stack. It adds it's own exceptions and provides the <code>HandlerContext</code>.</p>
<p><code>newtype HandlerAction</code> is my whole monad stack so far. I could derive instances from HandlerT automatically, but I had to <code>lift</code> the <code>MonadSession</code> instance explicitly. I don't like this manual labor, but I don't know if I can do anything about it. Shoud I maybe add it to <code>HandlerT</code> so I can automatically derive it in the <code>HandlerAction</code>? Like: <code>MonadSession m => MonadSession (HandlerT m)</code>.</p>
<p>Now for the functions:
<code>runHandler</code> just runs the given HandlerAction and reports any errors to the user. It needs a valid session. If the session failed to initialize or restore, <code>handleSessionError</code> should be called instead.</p>
<p><code>reply</code> is used only in the <code>Handler</code> implementations. It would a protected method in C++-like languages. It replies to the user's message and associates the session with this reply.</p>
<pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
module Handler ( HandlerAction
, HandlerContext(..)
, Handler(..)
, MonadSession(..)
, runHandler
, handleSessionError
, throwError
, reply
) where
import Control.Monad (void)
import Control.Monad.Except (ExceptT, MonadError, runExceptT, throwError)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.MonadStack (MonadStack, liftFrom)
import Control.Monad.Reader (MonadReader, ask, runReaderT)
import Control.Monad.State (MonadState)
import Control.Monad.Trans.Class (MonadTrans(..), lift)
import Control.Monad.Trans.Reader (ReaderT)
import Config (ConfigT)
import Session (SessionT, SessionError, MonadSession(..))
import qualified Telegram
import qualified Telegram.Types as TTypes
-- Public
newtype HandlerAction a = HandlerAction
{ runHandlerAction :: HandlerT (SessionT ConfigT) a
} deriving ( Applicative, Functor, Monad, MonadIO
, MonadError String, MonadReader HandlerContext
)
instance MonadSession HandlerAction where
save key value = HandlerAction $ lift $ (Session.save key value :: SessionT ConfigT ())
setId = HandlerAction . lift . Session.setId
recall = HandlerAction . lift . Session.recall
tryRecall = HandlerAction . lift . Session.tryRecall
deleteSession = HandlerAction $ lift $ Session.deleteSession
data Handler = Handler
{ command :: String
, handleMessage :: String -> HandlerAction ()
, handleResponse :: Maybe (String -> HandlerAction ())
, handleAnswer :: Maybe (String -> HandlerAction ())
}
data HandlerContext = HandlerContext
{ userId :: Int
, messageId :: Int
}
runHandler :: HandlerAction a -> HandlerContext -> SessionT ConfigT ()
runHandler handler = runReaderT (reportErrors =<< run handler)
where
reportErrors :: Either String a -> ReaderT HandlerContext (SessionT ConfigT) ()
reportErrors = either sendError (const $ return ())
sendError :: String -> ReaderT HandlerContext (SessionT ConfigT) ()
sendError message = do
context <- ask
liftFrom $ sendMessage_ context message
run :: HandlerAction a -> ReaderT HandlerContext (SessionT ConfigT) (Either String a)
run = runExceptT . runHandlerT . runHandlerAction
handleSessionError :: HandlerContext -> SessionError -> ConfigT ()
handleSessionError context error = sendMessage_ context $ show error
reply :: String -> HandlerAction ()
reply message = do
context <- ask
id <- HandlerAction $ liftFrom $ sendMessage context message
setId $ show id
-- Private
newtype HandlerT m a = HandlerT
{ runHandlerT :: ExceptT String(
ReaderT HandlerContext
m) a
} deriving ( Applicative
, Functor
, Monad
, MonadIO
, MonadReader HandlerContext
, MonadError String
)
instance MonadTrans HandlerT where
lift = HandlerT . lift . lift
sendMessage :: HandlerContext -> String -> ConfigT Int
sendMessage context message =
let chatId = userId context
originalId = messageId context
postMessage = TTypes.PostMessage
{ TTypes.chat_id = chatId
, TTypes.text = message
, TTypes.reply_markup = Nothing
, TTypes.reply_to_message_id = Just originalId
}
in Telegram.sendMessage postMessage
sendMessage_ :: HandlerContext -> String -> ConfigT ()
sendMessage_ context message = void $ sendMessage context message
</code></pre>
<h2>Controller.hs</h2>
<p><code>processUpdate</code> is the only public function. It takes a raw telegram message, determines it's type, creates or restores a session, and passes the execution to a handler.</p>
<p><code>data UpdateInfo</code> and <code>data Request</code> are adaptations of Telegram's entities that are only used by this module.</p>
<p><code>r</code> is a function that deals with duplicate record fields of Telegram's entities.</p>
<pre><code>{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE FlexibleContexts #-}
module Controller ( Controller(..)
, processUpdate
) where
import Control.Applicative ((<|>))
import Data.Char (toLower)
import Data.List (find, isPrefixOf)
import Data.Maybe (fromMaybe, isNothing)
import Config (ConfigT)
import Handler (Handler(..), HandlerContext(..), HandlerAction,
runHandler, handleSessionError, throwError)
import Session (SessionT, MonadSession(..), withSession)
import qualified Telegram.Types as TTypes
-- Public
newtype Controller = Controller
{ handlers :: [Handler]
}
processUpdate :: Controller -> TTypes.Update -> ConfigT ()
processUpdate controller update = do
updateInfo <- getUpdateInfo update
let sid = sessionId updateInfo
let context = HandlerContext { userId = r @UpdateInfo user_id updateInfo
, messageId = r @UpdateInfo message_id updateInfo
}
result <- withSession sid $ do
handlerAction <- findHandler updateInfo $ handlers controller
runHandler handlerAction context
either (handleSessionError context) return result
-- Private
data UpdateInfo = UpdateInfo
{ request :: Request
, message :: String
, user_id :: Int
, message_id :: Int
, sessionId :: Maybe String
}
data Request
= MessageRequest { message :: TTypes.GetMessage }
| ResponseRequest { message :: TTypes.GetMessage }
| QueryRequest { query :: TTypes.CallbackQuery
, message :: TTypes.GetMessage }
r :: (r -> a) -> r -> a
r = ($)
getUpdateInfo :: TTypes.Update -> ConfigT UpdateInfo
getUpdateInfo update =
let request = fromMaybe handleError $
tryMessage update <|>
tryEditedMessage update <|>
tryCallbackQuery update
in return UpdateInfo { request = request
, message = getText request
, user_id = getUser request
, message_id = TTypes.message_id $ getMessage request
, sessionId = show . TTypes.message_id <$> getInitialMessage request
}
where
tryMessage :: TTypes.Update -> Maybe Request
tryMessage update = messageOrReply <$> r @TTypes.Update TTypes.message update
tryEditedMessage :: TTypes.Update -> Maybe Request
tryEditedMessage update = messageOrReply <$> r @TTypes.Update TTypes.edited_message update
tryCallbackQuery :: TTypes.Update -> Maybe Request
tryCallbackQuery update = do
query <- TTypes.callback_query update
message <- r @TTypes.CallbackQuery TTypes.message query
Just $ QueryRequest { query = query
, message = message
}
getUser :: Request -> Int
getUser (MessageRequest message) =
r @TTypes.User TTypes.id $
r @TTypes.GetMessage TTypes.from message
getUser (ResponseRequest message) =
r @TTypes.User TTypes.id $
r @TTypes.GetMessage TTypes.from message
getUser (QueryRequest query _) =
r @TTypes.User TTypes.id $
r @TTypes.CallbackQuery TTypes.from query
getMessage :: Request -> TTypes.GetMessage
getMessage request@MessageRequest{} = r @Request message request
getMessage request@ResponseRequest{} = r @Request message request
getMessage request@QueryRequest{} = r @Request message request
getText :: Request -> String
getText request@MessageRequest{} =
fromMaybe "" $ r @TTypes.GetMessage TTypes.text $ getMessage request
getText request@ResponseRequest{} =
fromMaybe "" $ r @TTypes.GetMessage TTypes.text $ getMessage request
getText request@QueryRequest{} = TTypes.info $ query request
getInitialMessage :: Request -> Maybe TTypes.GetMessage
getInitialMessage (MessageRequest message) = Nothing
getInitialMessage (ResponseRequest message) = TTypes.reply_to_message message
getInitialMessage (QueryRequest _ message) = Just message
-- A proper error handler will be possible when Telegram service errors are implemented
handleError :: a
handleError = error "No message"
messageOrReply :: TTypes.GetMessage -> Request
messageOrReply message = if isNothing $ TTypes.reply_to_message message
then MessageRequest { message = message }
else ResponseRequest { message = message }
findHandler :: UpdateInfo -> [Handler] -> SessionT ConfigT (HandlerAction ())
findHandler updateInfo handlers =
tryRecall "handler" >>= \savedVerb ->
let messageText = r @UpdateInfo message updateInfo
verb = fromMaybe (map toLower messageText) savedVerb
predicate handler = command handler `isPrefixOf` verb
maybeHandler = find predicate handlers
noHandler = throwError "Handler not found"
noMethod = throwError "Method not found"
prepareHandler handler =
let maybeMethod = case request updateInfo of
MessageRequest _ -> Just $ handleMessage handler
ResponseRequest _ -> handleResponse handler
in save "handler" (command handler) >>
maybe noMethod ($ messageText) maybeMethod
in return $ maybe noHandler prepareHandler maybeHandler
</code></pre>
<h2>Telegram.hs</h2>
<p>I will include the Telegram entities from <em>Telegram/Types.hs</em> for completeness, but they are really not important. I will not include <em>Telegram.hs</em> because there are a lot of open issues in the module and I don't want the review to derail there. You wouldn't be able to run the bot without a telegram API key anyway, and if you would like to compile it, you can mock every function from Telegram with <code>undefined</code>.</p>
<pre><code>{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
module Telegram.Types where
import Data.Aeson ( FromJSON(..), ToJSON(..), Options(..)
, defaultOptions, genericToJSON, genericParseJSON )
import GHC.Generics (Generic)
-- GET queries
data File = File
{ file_id :: String
, file_path :: Maybe String
} deriving (Show, Generic, FromJSON)
data User = User
{ id :: Int
} deriving (Show, Generic, FromJSON)
data PhotoSize = PhotoSize
{ file_id :: String
, width :: Int
, height :: Int
} deriving (Show, Generic, FromJSON)
data GetMessage = GetMessage
{ message_id :: Int
, from :: User
, date :: Int
, text :: Maybe String
, photo :: Maybe [PhotoSize]
, caption :: Maybe String
, reply_to_message :: Maybe GetMessage
} deriving (Show, Generic, FromJSON)
data CallbackQuery = CallbackQuery
{ id :: String
, message :: Maybe GetMessage
, from :: User
, info :: String
} deriving (Show, Generic)
instance FromJSON CallbackQuery
where parseJSON = genericParseJSON defaultOptions
{ fieldLabelModifier = \f -> if f == "info" then "data" else f
}
data Update = Update
{ update_id :: Int
, message :: Maybe GetMessage
, callback_query :: Maybe CallbackQuery
, edited_message :: Maybe GetMessage
} deriving (Show, Generic, FromJSON)
data Response a = Response
{ ok :: Bool
, result :: Maybe a
} deriving (Show, Generic, FromJSON)
-- POST queries
data InlineKeyboardButton = InlineKeyboardButton
{ text :: String
, callback_data :: String
} deriving (Show, Generic, ToJSON)
data InlineKeyboardMarkup = InlineKeyboardMarkup
{ inline_keyboard :: [[InlineKeyboardButton]]
} deriving (Show, Generic, ToJSON)
data PostMessage = PostMessage
{ chat_id :: Int
, text :: String
, reply_markup :: Maybe InlineKeyboardMarkup
, reply_to_message_id :: Maybe Int
} deriving (Show, Generic)
instance ToJSON PostMessage where
toJSON = genericToJSON defaultOptions
{ omitNothingFields = True }
</code></pre>
<h2>Usage</h2>
<p>Here is how to use the framework: you write a number of handlers, create a controller with these handlers and start polling messages to your bot from Telegram. You then pass each new message to Handler.</p>
<h3>Handlers/NumberGameHandler.hs</h3>
<pre><code>{-# LANGUAGE FlexibleContexts #-}
module Handlers.NumberGameHandler (numberGameHandler) where
import Control.Monad.IO.Class (liftIO)
import System.Random (randomRIO)
import Text.Read (readMaybe)
import Handler
numberGameHandler :: Handler
numberGameHandler = Handler
{ command = "guess"
, handleMessage = doHandleMessage
, handleResponse = Just doHandleResponse
, handleAnswer = Nothing
}
doHandleMessage :: String -> HandlerAction ()
doHandleMessage _ = do
number <- liftIO (randomRIO (1, 10) :: IO Int)
save "number" number
reply "Guess a number between 1 and 10"
doHandleResponse :: String -> HandlerAction ()
doHandleResponse message = do
guess <- readNumber message
number <- recall "number"
case compare guess number of
LT -> reply "My number is greater"
GT -> reply "My number is less"
EQ -> reply "Correct!" >> deleteSession
where
readNumber :: String -> HandlerAction Int
readNumber message = maybe (throwError "This is not a number") return $ readMaybe message
</code></pre>
<h3>Main.hs</h3>
<pre><code>module Main where
import Control.Monad (unless)
import Control.Monad.IO.Class (liftIO)
import Config (ConfigT, runConfigT, loadConfig)
import Handlers.PingHandler
import Handlers.NumberGameHandler
import Controller (Controller(..), processUpdate)
import qualified Telegram (getUpdates)
import qualified Telegram.Types as TTypes (Update(..), GetMessage(..))
controller = Controller
{ handlers = [ pingHandler
, numberGameHandler
]
}
pollUpdates :: Int -> ConfigT ()
pollUpdates nextUpdate = do
updates <- Telegram.getUpdates nextUpdate
update_ids <- mapM process updates
unless (null update_ids) $ pollUpdates $ maximum update_ids + 1
where
process :: TTypes.Update -> ConfigT Int
process update = do
liftIO $ showUpdate update
processUpdate controller update
return $ TTypes.update_id update
showUpdate :: TTypes.Update -> IO ()
showUpdate update = maybe (return ()) putStrLn $ TTypes.message update >>= TTypes.text
main :: IO ()
main = loadConfig >>= runConfigT (pollUpdates 0)
</code></pre>
|
[] |
[
{
"body": "<h1>Default class implementation</h1>\n<p>I've discovered a blog post about implementing monad stack with <code>DefaultSignatures</code>. I don't remember the link. The idea is that you create a default implementation to your monadic classes, that uses <code>lift</code> to implement the function when you derive this class in another transformer. For example, here is my <code>Logger</code> implementation:</p>\n<h2>Simple example: Logger</h2>\n<p>First, define your monad as a class with supported methods:</p>\n<pre><code>class (Monad m, MonadIO m) => MonadLogger m where\n logMessage :: String -> m ()\n</code></pre>\n<p>Then, add the default implementation for deriving types, supposing the deriving types are derived from a <code>MonadLogger</code> using a <code>MonadTrans</code>. In this case (as in all simple cases where the monad only appears in the last position in the signature, i.e. the return type) this implementation is just the same function but lifted.</p>\n<pre><code>class (Monad m, MonadIO m) => MonadLogger m where\n logMessage :: String -> m ()\n\n default logMessage :: (MonadTrans t, MonadLogger m1, m ~ t m1)\n => String -> m ()\n logMessage = lift . logMessage\n</code></pre>\n<p>This requires some language extensions.</p>\n<pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DefaultSignatures #-}\n{-# LANGUAGE GADTs #-}\n</code></pre>\n<p>Next, implement the logger in a transformer:</p>\n<pre><code>newtype LoggerT m a = LoggerT\n { runLoggerT :: m a\n } deriving ( Applicative\n , Functor\n , Monad\n , MonadIO\n )\n\ninstance MonadTrans LoggerT where\n lift = LoggerT\n\ninstance (Monad m, MonadIO m) => MonadLogger (LoggerT m) where\n logMessage = liftIO . putStrLn\n</code></pre>\n<p>Finally, here is how to derive <code>MonadLogger</code> in a monad higher in the stack. This also requires some more language extensions:</p>\n<pre><code>{-# LANGUAGE DerivingStrategies #-}\n{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DeriveAnyClass #-}\n\nnewtype ConfigT m a = ConfigT\n { runConfigT :: Reader.ReaderT Config m a\n } deriving newtype ( Applicative\n , Functor\n , Monad\n , MonadIO\n , MonadReader Config\n , MonadTrans\n )\n deriving anyclass ( MonadLogger )\n</code></pre>\n<p>Here, we had to derive our class using a different strategy. Honestly, I don't fully understand what <code>anyclass</code> does, so I won't try to explain it here. But I know that the result is somewhat equivalent if we were to derive <code>MonadLogger</code> by hand: <code>instance MonadLogger m => MonadLogger (ConfigT m) where logMessage = lift . logMessage</code></p>\n<p>Not here is the punch line: When <code>m</code> is <code>MonadLogger</code>, <code>ConfigT</code> also a <code>MonadLogger</code>. Here we don't need to lift at all when use it's methods:</p>\n<pre><code>getConfig :: MonadLogger m => (Config -> a) -> ConfigT m a\ngetConfig getter =\n logMessage "Getting config value" >>\n asks getter\n</code></pre>\n<h2>Basic</h2>\n<p>I've defined a simple basic monad that would be the base of the actual stack.</p>\n<pre><code>type Basic = ConfigT (LoggerT IO)\nrunBasic :: Basic a -> IO a\nrunBasic basic =\n runLoggerT $ (runReaderT $ runConfigT basic) =<< loadConfig\n</code></pre>\n<p>The idea is that every monad in my stack (or maybe multiple stacks) will be able to at least read app config and log messages.</p>\n<h2>Telegram and Dropbox</h2>\n<p>In the original post, Telegram and Dropbox functions lived in the <code>ConfigT</code> monad without defining their own monads. I've defined their classes this time:</p>\n<pre><code>class Monad m => MonadTelegram m where\n getUpdates :: Int -> m [Update]\n sendMessage :: PostMessage -> m Int\n editReplyMarkup :: EditMessageReplyMarkup -> m ()\n answerCallback :: String -> m ()\n sendChatAction :: SendChatAction -> m ()\n downloadFile :: String -> m (Maybe (String, L.ByteString))\n\n default getUpdates :: (MonadTrans t, MonadTelegram m1, m ~ t m1)\n getUpdates = lift . getUpdates\n -- ... other similar default implementations that I will omit in this answer.\n\nclass Monad m => MonadDropbox m where\n uploadFile :: String -> L.ByteString -> m ()\n -- default uploadFile\n</code></pre>\n<p>Since these methods do not require their own monads and rely only on <code>ConfigT</code> which is a part of <code>Basic</code>, I've decided to skip the corresponding transformers and just add the functionality to <code>Basic</code> itself. Naturally, with more language extensions, since <code>Basic</code> is a <code>type</code>, not a <code>newtype</code>. So, <code>Telegram.hs</code> adds a <code>MonadTelegram</code> implementation to <code>Basic</code>:</p>\n<pre><code>{-# LANGUAGE TypeSynonymInstances #-}\n{-# LANGUAGE FlexibleInstances #-}\ninstance MonadTelegram Basic where\n getUpdates next_update = ...\n sendMessage message = ...\n editReplyMarkup = ...\n answerCallback qid = ...\n sendChatAction = ...\n downloadFile fileId = ...\n</code></pre>\n<p><code>Dropbox.hs</code> adds <code>MonadDropbox</code> to <code>Basic</code> in a similar fascion.</p>\n<h2>Session</h2>\n<p>Similarly, <code>SessionMonad</code> methods got default implementations. <code>SessionT</code> got more instances</p>\n<pre><code>newtype SessionT m a = SessionT\n { runSessionT :: StateT Session (ExceptT SessionError m) a\n } deriving newtype ( Applicative\n , Functor\n , Monad\n , MonadIO\n , MonadState Session\n , MonadError SessionError\n )\n deriving anyclass ( MonadTelegram\n , MonadDropbox\n , MonadLogger\n )\n</code></pre>\n<h1>Handler</h1>\n<p>Handler is at the top of the hierarchy right now, so I didn't define a MonadHandler class. <code>HandlerT</code> got more instances</p>\n<pre><code>newtype HandlerT m a = HandlerT\n { runHandlerT :: ExceptT String(\n ReaderT HandlerContext\n m) a\n } deriving newtype ( Applicative\n , Functor\n , Monad\n , MonadIO\n , MonadReader HandlerContext\n , MonadError String\n )\n deriving anyclass ( MonadSession\n , MonadTelegram\n , MonadDropbox\n , MonadLogger\n )\n\ninstance MonadTrans HandlerT where\n lift = HandlerT . lift . lift\n</code></pre>\n<h2>MonadStack</h2>\n<p>In the question, I've used <code>MonadStack</code>. It is a really cool library, in my opinion, because it is less than 10 lines of code and it looks like a math theorem. Here is it's source: <a href=\"https://hackage.haskell.org/package/MonadStack-0.1.0.3/docs/src/Control-Monad-MonadStack.html#MonadStack\" rel=\"nofollow noreferrer\">https://hackage.haskell.org/package/MonadStack-0.1.0.3/docs/src/Control-Monad-MonadStack.html#MonadStack</a></p>\n<p>For some reason, though, the compiler really dislikes this library. It complains about overlapping instances from time to time, and I couldn't really solve this problem. Also, there was a problem that I couldn't figure out a nice way to painlessly add monads in the middle of my stack. Now, every instance of lifting from something other than <code>IO</code> (including <code>liftFrom</code>) is removed from the project, because it is all in the default implementation. To add a monad in a stack, I only need to implement a class with a transformer and <code>derive anyclass</code> it up the stack. Take a look:</p>\n<pre><code>{-# LANGUAGE GeneralizedNewtypeDeriving #-}\n{-# LANGUAGE DuplicateRecordFields #-}\n{-# LANGUAGE FlexibleContexts #-}\n{-# LANGUAGE DerivingStrategies #-}\n{-# LANGUAGE DeriveAnyClass #-}\n{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}\n\nmodule Handler ( HandlerAction(..)\n , HandlerContext(..)\n , Handler(..)\n , MonadSession(..)\n , Attachment(..)\n , createHandler\n , runHandler\n , handleSessionError\n , throwError\n , reply\n , reply_\n , askQuestion\n , editAnswers\n , sendChatAction\n , downloadFile\n ) where\n\nimport Control.Monad (void)\nimport Control.Monad.Except (ExceptT, MonadError, runExceptT, throwError)\nimport Control.Monad.IO.Class (MonadIO)\nimport Control.Monad.Reader (MonadReader, ask, asks, runReaderT)\nimport Control.Monad.State (MonadState)\nimport Control.Monad.Trans.Class (MonadTrans(..), lift)\nimport Control.Monad.Trans.Reader (ReaderT)\nimport qualified Data.ByteString.Lazy as L\n\nimport Basic (Basic)\nimport Session (SessionT, SessionError, MonadSession(..))\nimport Telegram (MonadTelegram)\nimport Dropbox (MonadDropbox)\nimport Logger (MonadLogger(..))\nimport qualified Telegram\nimport qualified Telegram.Types as TTypes\nimport Utils (r, (.:))\n\n-- Public\n\ntype HandlerAction = HandlerT (SessionT Basic)\n\ndata Handler = Handler\n { command :: String\n , handleMessage :: String -> HandlerAction ()\n , handleResponse :: Maybe (String -> HandlerAction ())\n , handleAnswer :: Maybe (String -> HandlerAction ())\n }\n\ncreateHandler :: String -> Handler\ncreateHandler command = Handler\n { command = command\n , handleMessage = const $ throwError "Handler not implemented"\n , handleResponse = Nothing\n , handleAnswer = Nothing\n }\n\ndata Attachment = Attachment String\n\ndata HandlerContext = HandlerContext\n { userId :: Int\n , messageId :: Int\n , attachment :: Maybe Attachment\n }\n\nrunHandler :: HandlerAction a -> HandlerContext -> SessionT Basic ()\nrunHandler handler context = reportErrors context =<< run handler context\n where\n reportErrors :: HandlerContext -> Either String a -> SessionT Basic ()\n reportErrors context = either (sendError context) (const $ return ())\n\n sendError :: HandlerContext -> String -> SessionT Basic ()\n sendError = flip sendMessage_\n\n run :: HandlerAction a -> HandlerContext -> SessionT Basic (Either String a)\n run = runReaderT . runExceptT . runHandlerT\n\nhandleSessionError :: HandlerContext -> SessionError -> Basic ()\nhandleSessionError context error = sendMessage_ (show error) context\n\nreply :: String -> HandlerAction ()\nreply message = do\n context <- ask\n id <- postMessage (\\m -> m { TTypes.text = message\n , TTypes.reply_markup = Just $ TTypes.ForceReply { TTypes.force_reply = True }\n } )\n context\n setId $ show id\n\nreply_ :: String -> HandlerAction ()\nreply_ message = askContext >>=\n sendMessage message >>=\n setId . show\n\naskQuestion :: String -> [[String]] -> HandlerAction ()\naskQuestion question answers = do\n context <- ask\n messageId <- show <$> sendQuestion question (mapAnswers answers) context\n setId messageId\n save "keyboardId" messageId\n\nsendChatAction :: TTypes.ChatAction -> HandlerAction ()\nsendChatAction chatAction = asks userId >>= \\chatId ->\n Telegram.sendChatAction $ TTypes.SendChatAction\n { TTypes.chat_id = chatId\n , TTypes.action = chatAction\n }\n\neditAnswers :: [[String]] -> HandlerAction ()\neditAnswers answers = do\n context <- ask\n messageId <- recall "keyboardId" :: HandlerAction String\n void $ Telegram.editReplyMarkup $ TTypes.EditReplyMarkup\n { TTypes.message_id = messageId\n , TTypes.chat_id = userId context\n , TTypes.reply_markup = TTypes.InlineKeyboardMarkup\n { TTypes.inline_keyboard = mapAnswers answers }\n }\n\ndownloadFile :: String -> HandlerAction (String, L.ByteString)\ndownloadFile fileId = do\n result <- Telegram.downloadFile fileId\n maybe (throwError "Не качается с телеграма") return result\n\n\n-- Private\n\naskContext :: HandlerAction HandlerContext\naskContext = ask\n\nnewtype HandlerT m a = HandlerT\n { runHandlerT :: ExceptT String(\n ReaderT HandlerContext\n m) a\n } deriving newtype ( Applicative\n , Functor\n , Monad\n , MonadIO\n , MonadReader HandlerContext\n , MonadError String\n )\n deriving anyclass ( MonadSession\n , MonadTelegram\n , MonadDropbox\n , MonadLogger\n )\n\ninstance MonadTrans HandlerT where\n lift = HandlerT . lift . lift\n\npostMessage :: MonadTelegram m\n => (TTypes.PostMessage -> TTypes.PostMessage)\n -> HandlerContext\n -> m Int\npostMessage initializer context =\n let chatId = userId context\n originalId = messageId context\n in Telegram.sendMessage $ initializer $\n TTypes.PostMessage { TTypes.chat_id = chatId\n , TTypes.reply_to_message_id = Just originalId\n , TTypes.reply_markup = Nothing\n , TTypes.text = ""\n }\n\nmapAnswers :: [[String]] -> [[TTypes.InlineKeyboardButton]]\nmapAnswers = (map . map) (\\answer -> TTypes.InlineKeyboardButton\n { text = answer\n , callback_data = answer\n })\n\nsendQuestion :: MonadTelegram m\n => String\n -> [[TTypes.InlineKeyboardButton]]\n -> HandlerContext\n -> m Int\nsendQuestion question keyboard =\n let initialize message = message { TTypes.text = question\n , TTypes.reply_markup = Just $ TTypes.InlineKeyboardMarkup\n { inline_keyboard = keyboard }\n }\n in postMessage initialize\n\nsendMessage :: MonadTelegram m\n => String -> HandlerContext -> m Int\nsendMessage message = postMessage (\\m -> m {TTypes.text = message})\n\nsendMessage_ :: MonadTelegram m => String -> HandlerContext -> m ()\nsendMessage_ = void .: sendMessage\n</code></pre>\n<h1>Conclusions</h1>\n<p>I like the <code>default signatures</code> because it removes most of the code duplication and lifts from the project. I can add monads to the stack and shuffle them around with not too much pain.</p>\n<p>To add a monad, in general case I need to implement it's class and it's transformer, which is reasonable. I need to add derivations of it's transformer everywhere up the stack, which is annoying. I also need to copy-pase default implementations for derivation, which is incredibly annoying. Maybe some time in the future I will try to tackle the default implementations with <code>TemplateHaskell</code>, but it's too daunting for me for now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-20T10:52:44.613",
"Id": "249591",
"ParentId": "244955",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "249591",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:01:39.020",
"Id": "244955",
"Score": "12",
"Tags": [
"haskell",
"monads",
"telegram"
],
"Title": "Telegram bot in Haskell using custom monad transformers"
}
|
244955
|
<p>To sum up all the nodes' depths in any given binary tree, I've written the following recursive algorithm:</p>
<pre><code>def nodeDepths(root):
final=[0]
helper(root,0, final)
return final[0]
def helper(node,d, final):
if not node:
return
final[0]+= d
helper(node.left,d+1, final)
helper(node.right,d+1, final)
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
</code></pre>
<p>My thinking was: as I see each node, add the depth of that node to the final sum, then recursively call on the left and right with <code>final</code> list as an argument. At the end of the recursive call stack, <code>final[0]</code> should have the right value.</p>
<p>Is there a better way to do this? I have concerns about thread safety in general with global variables but is it a better practice to use global variables in this case?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T18:53:15.580",
"Id": "481076",
"Score": "0",
"body": "For those in the reopen queue. Python is only pass by value, by mutating the list you can hack pass by reference into Python."
}
] |
[
{
"body": "<h2>PEP8</h2>\n<p><code>nodeDepths</code> should be <code>node_depths</code> in snake_case.</p>\n<h2>Function naming</h2>\n<p><code>helper</code> is not a helpful name for a function. If I were to guess what this does, it should maybe be called <code>recurse_node_depths</code>.</p>\n<h2>Instance methods</h2>\n<p>As it stands, <code>BinaryTree</code> does not deserve to have an <code>__init__</code>. It would be better-suited as a <code>@dataclass</code> or maybe a named tuple. That said, it probably makes more sense for <code>node_depths</code> to be an instance method where <code>self</code> replaces <code>root</code>.</p>\n<h2>Integer-by-reference</h2>\n<p>My first read of this code was wrong. <code>final</code> is only ever going to have one member. My guess is that you did this to effectively pass an integer by reference, but this is a gross hack. Instead, just return the evolving sum as an integer from your recursion, and the uppermost return will be the total that you need.</p>\n<h2>Slots</h2>\n<p>Another way to squeeze performance out of this is to initialize <code>__slots__</code> for <code>BinaryTree</code> based on the three known members.</p>\n<h2>Recursion</h2>\n<p>Recursion is not a great idea in Python, for at least two reasons:</p>\n<ul>\n<li>Given that there is no indication to the maximum depth of your input tree, you may blow the stack.</li>\n<li>Since Python does not have tail recursion optimization, recursion is slower than some other languages.</li>\n</ul>\n<p>So you should attempt to reframe this as an iterative implementation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T18:23:42.237",
"Id": "245043",
"ParentId": "244956",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245043",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:02:58.070",
"Id": "244956",
"Score": "1",
"Tags": [
"python",
"recursion",
"binary-tree"
],
"Title": "Best way to store the sum of all node depths?"
}
|
244956
|
<p>Proteins are chains of amino acids. Amino acids are coded by codons, a sequence of 3 DNA/RNA molecules. DNA also has 3 open reading frames. This is basically the DNA sequence, but shift it by 1 (i.e. ignore the first entry). Thus, you will have 3 different translations (no skipping, skip 1st entry, skip 2nd entry). Additionally, for some sequencing techniques, the length of the DNA they can sequence is short. Thus, you may need to sequence forward, and backwards (-f and -r in my code). Finally, these amino acids sequences start with a specific codon, and end with specific codons.</p>
<p>This code takes the DNA, translates it to an amino acid using the start and stop codons as borders. It offers the user 3 options, either only forward sequencing or reverse sequencing (where the dna sequence needs to be reversed, and then complemented), or a combination using both the forward and reverse. If both is picked, the script then looks for a point of intersection, and combines the forward and reverse at that intersection. Furthermore, it offers the user to pick between all the potential sequences found.
Finally, it uses BLAST to search the sequence picked against a database, to confirm the identity of the protein.</p>
<p>A basic schematic:</p>
<pre><code>#DNA
AGTTGCGC
#translated
1st reading frame: MC
2nd reading frame: VA
3rd reading frame: LR
#since only 1st reading frame has seq that starts with M
#sequence to search
MC
#Blast will search MC
</code></pre>
<p>That's the basic idea.</p>
<p>I'm not very familiar with functions (its why I have randomly assigned globals at the bottom, it's my "cheating" way of trying to make everything work. Additionally, this is also my first time trying to design user inputs in the terminal and using those as "flags" (i.e. if user types this in, do this). In its current state its a little ugly (in both the main_loop and reverse/forward loops I have dependencies on user input and multiple nested loops).</p>
<p>Thus I'm looking for 2 things:</p>
<ol>
<li><p>A way to clean up some of the user input lines so I don't have this multiple nested main loop. And feedback on the design/structure and use of my functions.</p>
</li>
<li><p>Is the code structured/properly is it clean? Are the methodologies used "best practices". In other words, are there better ways to do what I am attempting to do.</p>
</li>
</ol>
<p>I'm writing this program in the aim of learning how to write longer/cleaner programs, learn how to design my program to work via terminal (instead of GUI), and an excuse to learn selenium as well (although I do think it has some practical applications as well).</p>
<p>To run: <code>python script.py -f forward_file.txt -r reverse_file.txt</code>
The correct option to pick when presented with the translations is 1 and 0</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import sys
dna_codon_dict={'TTT':'F','TTC':'F',
'TTA':'L','TTG':'L',
'CTT':'L','CTC':'L',
'CTA':'L','CTG':'L',
'ATT':'I','ATC':'I',
'ATA':'I','ATG':'M',
'GTT':'V','GTC':'V',
'GTA':'V','GTG':'V',
'TCT':'S','TCC':'S',
'TCA':'S','TCG':'S',
'CCT':'P','CCC':'P',
'CCA':'P','CCG':'P',
'ACT':'T','ACC':'T',
'ACA':'T','ACG':'T',
'GCT':'A','GCC':'A',
'GCA':'A','GCG':'A',
'TAT':'Y','TAC':'Y',
'CAT':'H','CAC':'H',
'CAA':'Q','CAG':'Q',
'AAT':'N','AAC':'N',
'AAA':'K','AAG':'K',
'GAT':'D','GAC':'D',
'GAA':'E','GAG':'E',
'TGT':'C','TGC':'C',
'TGG':'W','CGT':'R',
'CGC':'R','CGA':'R',
'CGG':'R','AGT':'S',
'AGC':'S','AGA':'R',
'AGG':'R','GGT':'G',
'GGC':'G','GGA':'G',
'GGG':'G'}
DNA_complement_dict={'A':'T',
'T':'A',
'G':'C',
'C':'G',
'N':'N'}
def load_file(files):
codon_list=[]
with open(files) as seq_result:
for lines in seq_result:
if lines.startswith('>') is True:
continue
remove_white_spaces=lines.strip().upper()
for codon in remove_white_spaces:
codon_list.append(codon)
return codon_list
def rev(files):
reverse_codon_list=[]
codon_list=load_file(files)
codon_list.reverse()
for codons in codon_list:
reversed_codon=DNA_complement_dict[codons]
reverse_codon_list.append(reversed_codon)
return reverse_codon_list
def codon_translation(global_codon_list):
codon_counter=0
codon_triple_list=[]
open_reading_frame_lists=[[],[],[],]
for i in range(3):
open_reading_frame_count=1
codon_triple_list.clear()
codon_counter=0
for codons in global_codon_list:
if open_reading_frame_count>=(i+1):
codon_counter+=1
codon_triple_list.append(codons)
if codon_counter == 3:
codon_counter=0
join_codons=''.join(codon_triple_list)
try:
amino_acid=dna_codon_dict[join_codons]
open_reading_frame_lists[i].append(amino_acid)
except:
pass
if join_codons in {'TAA','TAG','TGA'}:
open_reading_frame_lists[i].append('X')
codon_triple_list.clear()
else:
open_reading_frame_count+=1
return open_reading_frame_lists
def find_open_reading_frames(global_codon_list):
sequences_to_search=[]
sequence_to_add_to_search_list=[]
add_to_string=False
for open_reading_frames in codon_translation(global_codon_list):
for amino_acids in open_reading_frames:
if amino_acids == 'M':
add_to_string=True
if add_to_string is True:
sequence_to_add_to_search_list.append(amino_acids)
if amino_acids == 'X':
add_to_string=False
if len(sequence_to_add_to_search_list)>0:
sequences_to_search.append(''.join(sequence_to_add_to_search_list))
sequence_to_add_to_search_list.clear()
else:
sequence_to_add_to_search_list.clear()
return sequences_to_search
def forward_loop():
files=sys.argv[2]
forward_flag=False
if sys.argv[1] == '-f':
forward_flag=True
if forward_flag is True:
codon_list=load_file(files)
return codon_list
def reverse_loop():
if sys.argv[1] == '-f':
revsere_flag=False
try:
if sys.argv[3] == '-r':
files=sys.argv[4]
reverse_flag=True
if reverse_flag is True:
codon_list=rev(files)
return codon_list
except:
pass
else:
files=sys.argv[2]
reverse_flag=False
if sys.argv[1] == '-r':
reverse_flag=True
if reverse_flag is True:
codon_list=rev(files)
return codon_list
def overlay(sequence_list1,sequence_list2):
new_list1=[word for line in sequence_list1 for word in line]
new_list2=[word for line in sequence_list2 for word in line]
temp_list=[]
modified_list1=[]
counter=0
for x in new_list1:
temp_list.append(x)
modified_list1.append(x)
counter+=1
if counter >= 5:
if temp_list == new_list2[0:5]:
break
else:
temp_list.pop((0))
del new_list2[0:5]
return ''.join(modified_list1+new_list2)
sequence_list1=[]
sequence_list2=[]
global_codon_list=[]
def main_loop():
global global_codon_list
global sequence_list1
global sequence_list2
if sys.argv[1] == '-f':
global_codon_list=forward_loop()
sequences_to_search=find_open_reading_frames(global_codon_list)
sequence_to_search=[]
for sequence,number in zip(sequences_to_search,range(len(sequences_to_search))):
print(f'row {number} sequence: {sequence}')
sequence_to_search.append(sequence)
pick_sequence_to_search=input('indicate which row # sequence to search: ')
sequence_list1.append(sequence_to_search[int(pick_sequence_to_search)])
try:
if sys.argv[3] == '-r':
global_codon_list=reverse_loop()
sequences_to_search=find_open_reading_frames(global_codon_list)
sequence_to_search=[]
for sequence,number in zip(sequences_to_search,range(len(sequences_to_search))):
print(f'row {number} sequence: {sequence}')
sequence_to_search.append(sequence)
pick_sequence_to_search=input('indicate which row # sequence to search: ')
sequence_list2.append(sequence_to_search[int(pick_sequence_to_search)])
except:
pass
else:
sequence_to_search=[]
global_codon_list=reverse_loop()
sequences_to_search=find_open_reading_frames(global_codon_list)
for sequence,number in zip(sequences_to_search,range(len(sequences_to_search))):
print(f'row {number} sequence: {sequence}')
sequence_to_search.append(sequence)
pick_sequence_to_search=input('indicate which row # sequence to search: ')
sequence_list1.append(sequence_to_search[int(pick_sequence_to_search)])
main_loop()
driver = webdriver.Chrome()
driver.get('https://blast.ncbi.nlm.nih.gov/Blast.cgi?PROGRAM=blastp&PAGE_TYPE=BlastSearch&LINK_LOC=blasthome')
fill_box = driver.find_element_by_xpath('/html/body/div[2]/div/div[2]/form/div[3]/fieldset/div[1]/div[1]/textarea')
fill_box.clear()
fill_box.send_keys(overlay(sequence_list1,sequence_list2))
sumbit_button=driver.find_element_by_xpath('/html/body/div[2]/div/div[2]/form/div[6]/div/div[1]/div[1]/input')
sumbit_button.click()
</code></pre>
<pre><code>#DNA forward
>Delta_fl_pETDuet_1F
NNNNNNNNNNNNNNNNANTTAATACGACTCACTATAGGGGAATTGTGAGCGGATAACAATTCCCCTCTAGAAATAATTTT
GTTTAACTTTAAGAAGGAGATATACCATGGGCAGCAGCCATCACCATCATCACCACAGCCAGGATCCAATGATTCGGTTG
TACCCGGAACAACTCCGCGCGCAGCTCAATGAAGGGCTGCGCGCGGCGTATCTTTTACTTGGTAACGATCCTCTGTTATT
GCAGGAAAGCCAGGACGCTGTTCGTCAGGTAGCTGCGGCACAAGGATTCGAAGAACACCACACTTTTTCCATTGATCCCA
ACACTGACTGGAATGCGATCTTTTCGTTATGCCAGGCTATGAGTCTGTTTGCCAGTCGACAAACGCTATTGCTGTTGTTA
CCAGAAAACGGACCGAATGCGGCGATCAATGAGCAACTTCTCACACTCACCGGACTTCTGCATGACGACCTGCTGTTGAT
CGTCCGCGGTAATAAATTAAGCAAAGCGCAAGAAAATGCCGCCTGGTTTACTGCGCTTGCGAATCGCAGCGTGCAGGTGA
CCTGTCAGACACCGGAGCAGGCTCAGCTTCCCCGCTGGGTTGCTGCGCGCGCAAAACAGCTCAACTTAGAACTGGATGAC
GCGGCAAATCAGGTGCTCTGCTACTGTTATGAAGGTAACCTGCTGGCGCTGGCTCAGGCACTGGAGCGTTTATCGCTGCT
CTGGCCAGACGGCAAATTGACATTACCGCGCGTTGAACAGGCGGTGAATGATGCCGCGCATTTCACCCCTTTTCATTGGG
TTGATGCTTTGTTGATGGGAAAAAGTAAGCGCGCATTGCATATTCTTCAGCAACTGCGTCTGGAAGGCAGCGAACCGGTT
ATTTTGTTGCGCACATTAN
#DNA Reverse
>Delta_FL_pETDuet_R-T7-Term_B12.ab1
NNNNNNNNNNNNNAGCTGCGCTAGTAGACGAGTCCATGTGCTGGCGTTCAAATTTCGCAGCAGCGGTTTCTTTACCAGAC
TCGAGTTAACCGTCGATAAATACGTCCGCCAGGGGTTTATGGCACAACAGAAGAGATAACCCTTCCAGCTCTGCCCACAC
TGACTGACCGTAATCTTGTTTGAGGGTGAGTTCCGTTCGTGTCAGGAGTTGCACGGCCTGACGTAACTGCGTCTGACTTA
AGCGATTTAACGCCTCGCCCATCATGCCCCGGCGGTTCTGCCATACCCGATGCTTATCAAACAACGCACGCAGTGGCGTA
TGGGCAGACTGGCGTTTCAGGTTAACCAGTAACAACAGTTCACGTTGTAATGTGCGCAACAAAATAACCGGTTCGCTGCC
TTCCAGACGCAGTTGCTGAAGAATATGCAATGCGCGCTTACTTTTTCCCATCAACAAAGCATCAACCCAATGAAAAGGGG
TGAAATGCGCGGCATCATTCACCGCCTGTTCAACGCGCGGTAATGTCAATTTGCCGTCTGGCCAGAGCAGCGATAAACGC
TCCAGTGCCTGAGCCAGCGCCAGCAGGTTACCTTCATAACAGTAGCAGAGCACCTGATTTGCCGCGTCATCCAGTTCTAA
GTTGAGCTGTTTTGCGCGCGCAGCAACCCAGCGGGGAAGCTGAGCCTGCTCCGGTGTCTGACAGGTCACCTGCACGCTGC
GATTCGCAAGCGCAGTAAACCACGCGGCATTTTCTTGCGCTTTGCTTAATTTATTACCGCGGACGATCAACAGCNNNCGT
CATGCAGAAGTCCGGTGAGTGTGAGAAGTTGCTCATNGATCGCCCGCATTCGGNCCGTTTTCTGGTANCANCAGNNATAC
CGTTTGTCGANTGGCAAACANACN
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T18:00:21.757",
"Id": "480980",
"Score": "0",
"body": "I think this is roughly on-topic; but can you edit the question to include your concerns about the code and what you're looking for in a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T18:16:47.120",
"Id": "480982",
"Score": "0",
"body": "I have edited the original post to include that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T07:39:39.607",
"Id": "481098",
"Score": "0",
"body": "well, if it's biology that you are interested in , python has lots of packages for chemistry, biology and physics. You may be interested in this https://biopython.org/ . Not related to the answer but maybe useful. These libraries will be already having those encoding of amino acids and much more. I haven't used them but it's expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T00:41:30.637",
"Id": "481409",
"Score": "0",
"body": "@VisheshMangla seems like I reinvented the wheel here, almost everything my program does theirs does. But the above is less for practical use, and more for me to learn just how to use python. But thank you, lots of useful tools in that package."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T05:50:38.467",
"Id": "481427",
"Score": "0",
"body": "That's great if it helped, I just randomly searched google for \"python pip package biology\". I don't know what's inside."
}
] |
[
{
"body": "<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def load_file(files):\n codon_list=[]\n with open(files) as seq_result:\n for lines in seq_result:\n if lines.startswith('>') is True:\n continue\n remove_white_spaces=lines.strip().upper()\n for codon in remove_white_spaces:\n codon_list.append(codon)\n return codon_list\n</code></pre>\n</blockquote>\n<p>There is almost never a good reason to use <code>is True</code>, just remove that and your code will still work correctly.</p>\n<p>We can remove <code>remove_white_spaces</code> by moving <code>lines.strip().upper()</code>, this makes the code easier to read as we now don't need to check if <code>remove_white_spaces</code> is being used again.</p>\n<p>We can use a list comprehension instead to build <code>codon_list</code>, this is syntatic sugar that has increased the readability of lots of Python code.</p>\n<p>You are using incorrectly using plurals, <code>files</code> and <code>lines</code>. You can also use <code>path</code> instead of <code>files</code> and <code>sequence</code> instead of <code>seq_result</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def load_file(path):\n with open(path) as sequence:\n return [\n codon\n for line in sequence\n if not line.startswith('>')\n for codon in line.strip().upper()\n ]\n</code></pre>\n<hr />\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def rev(files):\n reverse_codon_list=[]\n codon_list=load_file(files)\n codon_list.reverse()\n for codons in codon_list:\n reversed_codon=DNA_complement_dict[codons]\n reverse_codon_list.append(reversed_codon)\n return reverse_codon_list\n</code></pre>\n</blockquote>\n<p>Much like the previous function you can use a comprehension, and <code>reversed_codon</code> only impairs readability.</p>\n<p>We can use the function <code>reversed</code> rather than <code>list.reverse</code> to reverse the list, to reduce line count and improve readability.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def rev(files):\n return [\n DNA_complement_dict[codons]\n for codons in reversed(load_file(files))\n ]\n</code></pre>\n<hr />\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>def codon_translation(global_codon_list):\n codon_counter=0\n codon_triple_list=[]\n open_reading_frame_lists=[[],[],[],]\n for i in range(3):\n open_reading_frame_count=1\n codon_triple_list.clear()\n codon_counter=0\n for codons in global_codon_list:\n if open_reading_frame_count>=(i+1):\n codon_counter+=1\n codon_triple_list.append(codons)\n if codon_counter == 3:\n codon_counter=0\n join_codons=''.join(codon_triple_list)\n try:\n amino_acid=dna_codon_dict[join_codons]\n open_reading_frame_lists[i].append(amino_acid)\n except:\n pass\n if join_codons in {'TAA','TAG','TGA'}:\n open_reading_frame_lists[i].append('X')\n codon_triple_list.clear()\n else:\n open_reading_frame_count+=1\n return open_reading_frame_lists\n</code></pre>\n</blockquote>\n<p>Your code is hard to read as your whitespace is not great and not consistant. If you put a space either side of all operators it will help readability.</p>\n<p>You can use <code>len(codon_triple_list)</code> rather than <code>codon_counter</code>, this cuts out a siginifact amount of code improving readability.</p>\n<p>You shouldn't have bare exepcts, <code>except:</code>, these catch too much and lead to problems. You should either use <code>except KeyError:</code> or make it so there is no exception.</p>\n<p>You should have either a second dictionary that contains TAA, TAG and TGA.</p>\n<p>You can inverse <code>open_reading_frame_count>=(i+1)</code> to reduce the level of the arrow anti-pattern you have.</p>\n<p>You have some really verbose names, making your code harder to read. Which is <em>quicker</em> to read <code>triples</code> or <code>codon_triple_list</code>?</p>\n<pre class=\"lang-py prettyprint-override\"><code>def codon_translation(codons):\n reading_frames = ([], [], [])\n for i, reading_frame in enumerate(reading_frames):\n open_reading_frame_count = 1\n triples = []\n for codon in codons:\n if open_reading_frame_count <= i:\n open_reading_frame_count += 1\n continue\n\n triples += [codon]\n if len(triples) == 3:\n reading_frame.append(dna_codon_dict2[''.join(triples)])\n triples = []\n return reading_frames\n</code></pre>\n<p>You can remove the need for <code>open_reading_frame_count</code> by simply slicing <code>codons</code> by <code>i</code>.</p>\n<p>You can build a <code>windowed</code> function to get triplets easily.</p>\n<p>We can convert this into a nested comprehension.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def windowed(values, size):\n return zip(*size*[iter(values)])\n\n\ndef codon_translation(codons):\n return [\n [\n dna_codon_dict2[''.join(triplet)]\n for triplet in windowed(codons[i:], 3)\n if ''.join(triplet) in dna_codon_dict2\n ]\n for i in range(3)\n ]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T20:17:13.077",
"Id": "481080",
"Score": "0",
"body": "Wow thank you! I just wanted to add a comment saying I've seen it and am going through it, it's just this is quite a bit (and I'm also unfamiliar with list comprehensions), so it's been taking me sometime to go through all the modifications/improvements. Thank you again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T20:18:45.240",
"Id": "481081",
"Score": "0",
"body": "@samman No problem! If you find anything particularly confusing just shout :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T20:34:55.693",
"Id": "481083",
"Score": "0",
"body": "There are some things that jump out at me. 1) What's wrong with plurals? I don't quite understand the change to the nomenclature. 2) Is there any advantage to redefining the list as empty versus using .clear() triples=[] 3) I believe enumerate starts at 0, and we want our first value at 1. Can you just do ((reading_frames),1)? 4) The reason for try is because there will be values (that I cannot predict ahead of time) that will not be in my dict. However, I only want to append values that are in my dict. 5) Are nested listed comprehensions more readable though? It might be that I'm stil inadep"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T20:35:38.450",
"Id": "481086",
"Score": "0",
"body": "at reading list comprehensions, but I find the final box with the nested list comprehension to be significantly harder to read/follow than the one without it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T20:46:04.387",
"Id": "481087",
"Score": "1",
"body": "1) If you name something in its plural form, then you're saying there are 0-infinate values. So you're saying \"this is a list\", however this is not the case. Saying something is something it's not is confusing. 2) Ignore that, I changed the code but didn't put it back fully. 3) Range starts at 0 as well, what's the problem? 4) This is confusing when you had the if afterwards. 5) With time nested comprehensions like the one above are really easy to read. The underlying for loops may be harder to understand, but that'd be the same if it were not a comprehension either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T20:58:54.460",
"Id": "481088",
"Score": "0",
"body": "1) Oh I see, I didn't know that, thank you. 3) It's not that its an issue, that's why my open_reading_frame was i+1. However, I believe with enumerate you can actually choose to start at 1 (whereas you can't with range). I was just confirming you can. 4) The if afterwards is because I thought of that line after the fact (I should just include those values in the original dictionary)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T21:01:16.960",
"Id": "481089",
"Score": "0",
"body": "3) By inverting the if we've got rid of that anyway. But yes you could use `enumerate(reading_frames, 1)` as you, pretty much, said. 4) Ok, I've edited the final code to address that, there should be no issues with missing values now."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T16:45:58.633",
"Id": "245004",
"ParentId": "244959",
"Score": "3"
}
},
{
"body": "<h3>overall structure</h3>\n<p>I suggest splitting the program into two files. Everything before <code>forward_loop()</code> processes the files and could be split out into a separate library. This will make it easier to test the functions as well as reuse them in other scripts.</p>\n<p><code>Forward_loop()</code> and <code>reverse_loop()</code> don't really seem necessary. Basically the former calls <code>load_file()</code> and the later calls <code>rev(load_file())</code>.</p>\n<p>It's not clear what's the purpose of <code>overlay()</code>. If it's a typical DNA processing function it should go in the library. If it's only needed to enter data in the web form, then it should go in the main script.</p>\n<p>The rest of the code seems to deal with processing command-line args, getting user input and doing the search using selenium. It can go in the main script, which import the library.</p>\n<h3>try argparse</h3>\n<p>Your code processes command line parameters in several places and multiple functions. Try using <code>argparse</code> from the standard library.</p>\n<pre><code>import argparse\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('-f', '--forward', help="file for forward sequencing")\n parser.add_argument('-r', '--reverse', help="file for reverse sequencing")\n\n return parser.parse_args()\n</code></pre>\n<p>Calling it will return an object with attributes <code>forward</code> and <code>reverse</code> set to the argument or None.</p>\n<p>It looks like you intend to let the user pick multiple sequences for the search. That can be split into another function. Also, doc strings are good.</p>\n<pre><code>def get_selection(sequences):\n """Lets the user select a subset of sequences from a list of sequences.\n\n Prints the sequences, one per row, with a row number and prompts the user to\n enter a space separated list or row numbers.\n\n Returns a list of the selected sequences or an empty list.\n """\n\n print(f'row sequence')\n for number, sequence in enumerate(sequences, 1)):\n print(f'{number:3} {sequence}')\n\n print('To select sequences for the search, enter the'\n 'row numbers separates by spaces, e.g,. 0 2 3' )\n picks = input(': ').strip()\n\n return [sequence[int(i)] for i in picks.split()] if picks else []\n\n\ndef get_sequences(args):\n\n if args.forward:\n codons = load_file(args.forward)\n sequences = find_open_reading_frames(codons)\n forward_sequences = get_selection(sequences)\n\n if args.reverse:\n codons = rev(load_file(args.reverse))\n sequences = find_open_reading_frames(codons)\n reverse_sequences = get_selection(sequences)\n\n return forward_sequences, reverse_sequences\n\ndef main():\n args = parse_args()\n\n forward_sequences, reverse_sequences = get_sequences(args)\n\n driver = webdriver.Chrome()\n driver.get('https://blast.ncbi.nlm.nih.gov/Blast.cgi?PROGRAM=blastp&PAGE_TYPE=BlastSearch&LINK_LOC=blasthome')\n fill_box = driver.find_element_by_xpath('/html/body/div[2]/div/div[2]/form/div[3]/fieldset/div[1]/div[1]/textarea')\n fill_box.clear()\n fill_box.send_keys(overlay(forward_sequences, reverse_sequences))\n submit_button=driver.find_element_by_xpath(\n '/html/body/div[2]/div/div[2]/form/div[6]/div/div[1]/div[1]/input'\n )\n submit_button.click()\n\nmain()\n</code></pre>\n<p>I've run out of time, so this isn't tested. Hopefully you get the idea.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T23:16:28.477",
"Id": "245018",
"ParentId": "244959",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T17:24:26.693",
"Id": "244959",
"Score": "5",
"Tags": [
"python"
],
"Title": "DNA Translator and Verifier (using BLAST)"
}
|
244959
|
<p>I'll try to publish a paper about the programming language I've made (<a href="https://flatassembler.github.io/compiler.html" rel="nofollow noreferrer">ArithmeticExpressionCompiler</a>, short AEC) in Osječki Matematički List and, in order to demonstrate its usability for implementing algorithms, I've tried to implement a fast sorting algorithm in it.</p>
<p>The basic idea of my algorithm is that QuickSort works better when the array is randomly-shuffled, while MergeSort works better when the array is already nearly sorted. Here it goes:</p>
<pre><code>Syntax GAS ;Neka ArithmeticExpressionCompiler ispisuje asemblerski kod kompatibilan s GNU Assemblerom, da bude kompatibilan s GCC-om. Po defaultu ispisuje kod kompatibilan s FlatAssemblerom (a FlatAssembler na Linuxu ne radi bas najbolje).
verboseMode ON ;Neka ArithmeticExpressionCompiler ispisuje vise komentara u asemblerski kod koji ispisuje (da bude laksi za citanje i debuggiranje).
AsmStart ;Neka GNU Assembler obavijesti linkera da je "hybrid_sort" naziv potprograma...
.global hybrid_sort
hybrid_sort:
AsmEnd
If gornja_granica-donja_granica<2 ;Ako je niz duljine manje od 2 (0 ili 1), znaci da je vec poredan, pa prekidamo izvodenje ovog potprograma.
AsmStart ;Kako radimo izvan sekcija, mozemo jednostavno prekinuti izvodenje potprograma asemblerskom naredbom "ret" (inace bismo, da radimo u sekcijama, morali znati vrti li se program na 32-bitnom ili 64-bitnom Linuxu).
ret
AsmEnd
EndIf
razvrstanost:=0
i:=donja_granica
While i < gornja_granica - 1
razvrstanost:=razvrstanost+(originalni_niz[i]<originalni_niz[i+1])
i:=i+1
EndWhile
razvrstanost:=razvrstanost/((gornja_granica-donja_granica-1)/2)-1
i:=2
While i<7 | i=7
razvrstanost_na_potenciju[i] := pow(abs(razvrstanost), i) ;"pow(x,y)" je u AEC-u samo sintaksni secer za "exp(ln(x)*y)", i to vraca NaN za x=0 ili x<0. Nema ocitog nacina da se "pow(x,y)" prevede na asemblerski.
razvrstanost_na_potenciju[i] := (razvrstanost=0) ? 0 : (mod(i,2)=1 & razvrstanost<0) ? (-razvrstanost_na_potenciju[i]) : razvrstanost_na_potenciju[i] ;C-ov i JavaScriptin uvjetni operator nekad zna znatno skratiti kod, zato sam ga ugradio i u svoj jezik.
i:=i+1
EndWhile
;Formula koju je ispisao genetski algoritam za predvidanje koliko ce usporedbi QuickSort napraviti: https://github.com/FlatAssembler/ArithmeticExpressionCompiler/tree/master/QuickSort/Genetic_algorithm_for_deriving_the_formula
polinom_pod_apsolutnom := 2.38854*razvrstanost_na_potenciju[7] - 0.284258*razvrstanost_na_potenciju[6] - 1.87104*razvrstanost_na_potenciju[5] + 0.372637*razvrstanost_na_potenciju[4] + 0.167242*razvrstanost_na_potenciju[3] - 0.0884977*razvrstanost_na_potenciju[2] + 0.315119*razvrstanost
Eulerov_broj_na_koju_potenciju := (ln(gornja_granica - donja_granica) + ln(ln(gornja_granica - donja_granica))) * 1.05 + (ln(gornja_granica - donja_granica) - ln(ln(gornja_granica - donja_granica)) - ln(2)) * 0.9163 * abs(polinom_pod_apsolutnom)
koliko_usporedbi_ocekujemo_od_QuickSorta := exp(Eulerov_broj_na_koju_potenciju)
koliko_usporedbi_ocekujemo_od_MergeSorta := 2 * (gornja_granica - donja_granica) * ln(gornja_granica - donja_granica) / ln(2)
If razvrstanost=1 ;Ako je niz vec poredan.
broj_vec_poredanih_podniza := broj_vec_poredanih_podniza + 1
AsmStart
ret
AsmEnd
ElseIf razvrstanost = -1 ;Ako je niz obrnuto poredan...
broj_obrnuto_poredanih_podniza := broj_obrnuto_poredanih_podniza + 1
i:=donja_granica
j:=gornja_granica-1
While i<gornja_granica
pomocni_niz[i] := originalni_niz[j]
j := j - 1
i := i + 1
EndWhile
i := donja_granica
While i < gornja_granica
originalni_niz[i] := pomocni_niz[i]
i := i + 1
EndWhile
AsmStart
ret
AsmEnd
ElseIf koliko_usporedbi_ocekujemo_od_MergeSorta < koliko_usporedbi_ocekujemo_od_QuickSorta ;MergeSort algoritam (priblizno poredani podnizovi, za koje je MergeSort efikasniji od QuickSorta)...
broj_pokretanja_MergeSorta := broj_pokretanja_MergeSorta + 1
sredina_niza:=(gornja_granica+donja_granica)/2
sredina_niza:=sredina_niza-mod(sredina_niza,1)
vrh_stoga:=vrh_stoga+1 ;Zauzmi mjesta na stogu za rekurziju. Ne koristimo sistemski stog, kao sto koristi C++, nego koristimo vise globalnih polja kao stogove. Da koristimo sistemski stog, morali bismo znati pokrecemo li se na 32-bitnom Linuxu ili 64-bitnom Linuxu, jer oni nisu kompatibilni u tom pogledu.
stog_s_donjim_granicama[vrh_stoga]:=donja_granica
stog_s_gornjim_granicama[vrh_stoga]:=gornja_granica
stog_sa_sredinama_niza[vrh_stoga]:=sredina_niza
gornja_granica:=sredina_niza
AsmStart
call hybrid_sort
AsmEnd
donja_granica:=stog_s_donjim_granicama[vrh_stoga] ;Sad je rekurzija gotovo sigurno izmijenila sve globalne varijable koje nam trebaju ("donja_granica", "gornja_granica" i "sredina_niza"), ali zato imamo njihove stare vrijednosti na stogovima.
gornja_granica:=stog_s_gornjim_granicama[vrh_stoga]
sredina_niza:=stog_sa_sredinama_niza[vrh_stoga]
donja_granica:=sredina_niza
AsmStart
call hybrid_sort
AsmEnd
donja_granica:=stog_s_donjim_granicama[vrh_stoga]
gornja_granica:=stog_s_gornjim_granicama[vrh_stoga]
sredina_niza:=stog_sa_sredinama_niza[vrh_stoga]
;Spajanje nizova originalni_niz[donja_granica..sredina_niza] i originalni_niz[sredina_niza..gornja_granica] u jedan niz...
i:=donja_granica
gdje_smo_u_prvom_nizu:=donja_granica
gdje_smo_u_drugom_nizu:=sredina_niza
While i<gornja_granica
If (gdje_smo_u_prvom_nizu=sredina_niza | originalni_niz[gdje_smo_u_drugom_nizu]<originalni_niz[gdje_smo_u_prvom_nizu]) & gdje_smo_u_drugom_nizu<gornja_granica
pomocni_niz[i]:=originalni_niz[gdje_smo_u_drugom_nizu]
gdje_smo_u_drugom_nizu:=gdje_smo_u_drugom_nizu+1
Else
pomocni_niz[i]:=originalni_niz[gdje_smo_u_prvom_nizu]
gdje_smo_u_prvom_nizu:=gdje_smo_u_prvom_nizu+1
EndIf
i:=i+1
EndWhile
i:=donja_granica
While i<gornja_granica
originalni_niz[i]:=pomocni_niz[i]
i:=i+1
EndWhile
vrh_stoga:=vrh_stoga-1 ;Oslobodi mjesto na stogovima.
AsmStart
ret
AsmEnd
Else ;QuickSort algoritam (nasumicno ispremjestani podnizovi)...
broj_pokretanja_QuickSorta := broj_pokretanja_QuickSorta + 1
;Daljnji kod je priblizno prepisan s https://www.geeksforgeeks.org/quick-sort/
pivot := originalni_niz[gornja_granica - 1]
i := donja_granica - 1
j := donja_granica
While j < gornja_granica - 1
If originalni_niz[j] < pivot
i := i + 1
pomocna_varijabla_za_zamijenu := originalni_niz[i]
originalni_niz[i] := originalni_niz [j]
originalni_niz[j] := pomocna_varijabla_za_zamijenu
EndIf
j:=j+1
EndWhile
pomocna_varijabla_za_zamijenu := originalni_niz[i + 1]
originalni_niz[i + 1] := originalni_niz[gornja_granica - 1]
originalni_niz[gornja_granica - 1] := pomocna_varijabla_za_zamijenu
gdje_je_pivot := i + 1
vrh_stoga := vrh_stoga + 1 ;Zauzmi mjesta na stogu za rekurziju (ne koristimo sistemski stog, kao sto koristi C++, nego koristimo vise globalnih polja kao stogove).
stog_s_donjim_granicama[vrh_stoga] := donja_granica
stog_s_gornjim_granicama[vrh_stoga] := gornja_granica
stog_sa_sredinama_niza[vrh_stoga] := gdje_je_pivot
gornja_granica := gdje_je_pivot
AsmStart
call hybrid_sort
AsmEnd
donja_granica := stog_s_donjim_granicama[vrh_stoga]
gornja_granica := stog_s_gornjim_granicama[vrh_stoga]
gdje_je_pivot := stog_sa_sredinama_niza[vrh_stoga]
donja_granica := gdje_je_pivot
AsmStart
call hybrid_sort
AsmEnd
vrh_stoga := vrh_stoga - 1 ;Oslobodi mjesto na stogovima.
AsmStart
ret
AsmEnd
EndIf
AsmStart ;Ovdje tok programa ne smije doci. Ako dode, pozovi debugger.
call abort
AsmEnd
</code></pre>
<p>The assembly code that my compiler produces can be seen <a href="https://raw.githubusercontent.com/FlatAssembler/ArithmeticExpressionCompiler/master/recursive_HybridSort/hybrid_sort.s" rel="nofollow noreferrer">here</a>. It can be assembled using GNU Assembler, however, you won't get an executable program from it. It's just a routine that expects to be called from an external program. An example of such a program is here:</p>
<pre class="lang-cpp prettyprint-override"><code>/*
* Dakle, ovo ce biti omotac oko "hybrid_sort.aec" napisan u C++-u.
* "hybrid_sort.aec" sam po sebi nije program koji se moze pokrenuti,
* i zato cemo od C++ compilera (u ovom slucaju, GCC-a) traziti da
* napravi program unutar kojeg ce se "hybrid_sort.aec" moze pokrenuti,
* i, po mogucnosti, koji ce olaksati da ga testiramo. Drugim rijecima,
* ovo je program s kojim se "hybrid_sort.aec" moze staticki linkirati.
* */
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <iterator>
namespace AEC { // Da se razlikuju AEC-ove varijable od C++-ovih.
extern "C" { // Za GNU Linker (koji se dobije uz Linux i koristi ga GCC), AEC
// jezik je dijalekt C-a, a moj compiler je C compiler.
float result, originalni_niz[1 << 16], kopija_originalnog_niza[1 << 16],
pomocni_niz[1 << 16], i, gdje_smo_u_prvom_nizu, gdje_smo_u_drugom_nizu,
gornja_granica, donja_granica, sredina_niza,
stog_sa_sredinama_niza[1 << 10], stog_s_donjim_granicama[1 << 10],
stog_s_gornjim_granicama[1 << 10], vrh_stoga, pomocna_varijabla_za_zamijenu,
gdje_je_pivot, j, pivot, koliko_usporedbi_ocekujemo_od_QuickSorta,
koliko_usporedbi_ocekujemo_od_MergeSorta, razvrstanost,
Eulerov_broj_na_koju_potenciju, polinom_pod_apsolutnom,
razvrstanost_na_potenciju[8],
broj_vec_poredanih_podniza = 0, broj_obrnuto_poredanih_podniza = 0,
broj_pokretanja_MergeSorta = 0,
broj_pokretanja_QuickSorta =
0; // GNU Linker omogucuje da se varijable ne deklariraju ne samo u
// razlicitim datotekama, nego i u razlicitim jezicima. Znaci, ne
// moram traziti kako se, recimo, na 64-bitnom Linuxu deklariraju
// globalne varijable na asemblerskom jeziku, jer GCC to vec zna.
void hybrid_sort(); //".global hybrid_sort" iz "hybrid_sort.aec". U C++-u ga
// morate deklarirati da biste ga mogli koristiti. C++ nije
// kao JavaScript ili AEC u tom pogledu, C++ pokusava pronaci
// krivo natipkana imena varijabli i funkcija vec za vrijeme
// compiliranja.
}
} // namespace AEC
const int n = 1 << 16;
int main() {
std::cout << "sortedness\tsorted_array\treverse\tMergeSort\tQuickSort\n";
for (int i = 0; i < n; i++)
AEC::originalni_niz[i] = i;
for (int i = 0; i <= n; i += 1 << 9) {
std::sort(&AEC::originalni_niz[0], &AEC::originalni_niz[n]);
if (i < (n / 2))
std::reverse(&AEC::originalni_niz[0], &AEC::originalni_niz[n]);
int broj_ispremjestanja = abs(i - (n / 2)) * 1.5;
for (int j = 0; j < broj_ispremjestanja; j++)
std::iter_swap(&AEC::originalni_niz[std::rand() % n],
&AEC::originalni_niz[std::rand() % n]);
if (!(rand() % 100))
std::random_shuffle(
&AEC::originalni_niz[0],
&AEC::originalni_niz[n]); // Ponekad namjesti da poredanost bude nula.
if (!(rand() % 100))
std::sort(&AEC::originalni_niz[0], &AEC::originalni_niz[n],
[](float a, float b) -> bool {
return a > b;
}); // Ponekad namjesti da poredanost bude 1. Za to sam koristio
// C++-ove lambda funkcije. Njih GCC podrzava jos od 2007, a
// komercijalni compileri jos od ranije. Nadam se da netko
// nece pokusati ukucati ovo u neki arhaican compiler.
float razvrstanost = 0;
for (int j = 0; j < n - 1; j++)
razvrstanost += AEC::originalni_niz[j] < AEC::originalni_niz[j - 1];
razvrstanost = razvrstanost / ((n - 1) / 2) - 1;
std::copy_n(&AEC::originalni_niz[0], n, &AEC::kopija_originalnog_niza[0]);
AEC::broj_vec_poredanih_podniza = 0;
AEC::broj_obrnuto_poredanih_podniza = 0;
AEC::broj_pokretanja_MergeSorta = 0;
AEC::broj_pokretanja_QuickSorta = 0;
AEC::gornja_granica = n;
AEC::donja_granica = 0;
AEC::vrh_stoga = -1;
AEC::hybrid_sort();
std::sort(&AEC::kopija_originalnog_niza[0],
&AEC::kopija_originalnog_niza[n]);
if (!std::equal(&AEC::originalni_niz[0], &AEC::originalni_niz[n],
&AEC::kopija_originalnog_niza[0])) {
std::cerr << "C++-ov std::sort nije dobio isti rezultat za i=" << i << '!'
<< std::endl;
return 1; // Javi operativnom sustavu da je doslo do pogreske.
}
std::cout << razvrstanost << '\t'
<< std::log(1 + AEC::broj_vec_poredanih_podniza)
<< '\t' // Broj vec poredanih podniza moze biti i nula (ako je,
// recimo, razvrstanost jednaka -1), a, kako logaritam od
// nula ne postoji, dodat cu jedinicu da se program ne rusi
// na nekim compilerima.
<< std::log(1 + AEC::broj_obrnuto_poredanih_podniza) << '\t'
<< std::log(1 + AEC::broj_pokretanja_MergeSorta) << '\t'
<< std::log(1 + AEC::broj_pokretanja_QuickSorta) << '\n';
}
std::flush(std::cout); // Obrisi meduspremnik prije no sto zavrsis program.
return 0; // Javi operativnom sustavu da je program uspjesno zavrsen.
}
</code></pre>
<p>I am interested in how I can make it better. I notice it's not nearly as fast as the C++ <code>std::sort</code>.</p>
<p>Here are some measurements I've made:<br/>
<img src="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/recursive_HybridSort/test_results.png"><br/>
I've also tried to diagnose the performance problems by measuring how often each algorithm is used for an array of specific sortedness:<br/>
<img src="https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/recursive_HybridSort/which_algorithms_are_used.png"><br/>
But I still can't figure out what's exactly slowing it down to be more than 100 times slower than C++ <code>std::sort</code> is. Can you figure it out? Or can you make my code better in some other way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T18:03:23.557",
"Id": "481137",
"Score": "1",
"body": "I'm very impressed by what you've created **but** because all the important stuff like label names, variable names, and comments are in a language understood by almost nobody else but you on this forum, I fear you can not expect a review of some quality. Also the assembly code for which you've provided a link is not only massive but lacks the necessary formatting to be readable! Personally I don't mind it being massive, but it's just not readable in its present form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T18:57:20.867",
"Id": "481143",
"Score": "0",
"body": "`sredina_niza:=sredina_niza-mod(sredina_niza,1)` The remainder from dividing by 1 is always 0. Shouldn't this read `sredina_niza:=sredina_niza-mod(sredina_niza,2)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T19:17:03.847",
"Id": "481146",
"Score": "0",
"body": "@SepRoland The remainder from one is the decimal part. When you subtract it, the number becomes an integer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T19:31:22.437",
"Id": "481147",
"Score": "1",
"body": "Sorry, forgot it's a float value."
}
] |
[
{
"body": "<h2>The generated assembly code is very inefficient!</h2>\n<h3>First example.</h3>\n<p>Ley's look at this small part right at the top:</p>\n<blockquote>\n<pre><code>If gornja_granica-donja_granica<2\nAsmStart\n ret\nAsmEnd\nEndIf\n</code></pre>\n</blockquote>\n<p>This is its assembly code in a readable form:</p>\n<pre><code> finit\n fld dword ptr [gornja_granica]\n fld dword ptr [donja_granica]\n fsubp\n mov dword ptr [result],0x40000000 #IEEE754 hex of 2\n fld dword ptr [result]\n fcomip\n fstp dword ptr [result]\n jna secondOperandOfTheComparisonIsSmallerOrEqualLabel914728\n fld1\n jmp endOfTheLessThanComparisonLabel862181\nsecondOperandOfTheComparisonIsSmallerOrEqualLabel914728:\n fldz ; 2 LT (a-b)\nendOfTheLessThanComparisonLabel862181:\n\n#Comparing the just-calculated expression with 0...\n fistp dword ptr [result]\n mov eax, dword ptr [result]\n test eax,eax\n#Branching based on whether the expression is 0...\n jz ElseLabel529946\n ret\n finit\nElseLabel529946:\nEndIfLabel210662:\n</code></pre>\n<p>Basically this code wants to arrive at <em>ElseLabel529946</em> if <code>gornja_granica-donja_granica<2</code>. For branching the only info that you really need comes from the <code>fcomip</code> instruction. It defines the CF and ZF (and PF) in EFLAGS and you could have jumped immediately</p>\n<ul>\n<li>without loading that 0.0 or 1.0</li>\n<li>without storing into a memory variable</li>\n<li>without testing that memory variable</li>\n<li>without the additional jumping</li>\n</ul>\n<p>This is an improved code:</p>\n<pre><code> finit\n fld dword ptr [gornja_granica]\n fld dword ptr [donja_granica]\n fsubp\n mov dword ptr [result], 0x40000000 ; IEEE754 hex of 2\n fld dword ptr [result]\n fcomip\n fstp st(0) ; Clears FPU stack\n jna ElseLabel529946\n ret\n finit\nElseLabel529946:\n</code></pre>\n<p>Please notice that to throw away st(0), you don't need to move to memory. Copy st(0) to itself and have the FPU stack popped.</p>\n<p>And this improves still further. Less memory access and shorter code!</p>\n<pre><code> finit\n fld dword ptr [gornja_granica]\n fsub dword ptr [donja_granica]\n fld1\n fadd st(0), st(0) ; st(0) == 1 + 1\n fcomip\n fstp ; Clears FPU stack\n jna ElseLabel529946\n ret\nElseLabel529946:\n</code></pre>\n<h3>Second example.</h3>\n<blockquote>\n<pre><code>While i<7 | i=7\n</code></pre>\n</blockquote>\n<p>This should be written as <code>While i<=7</code></p>\n<p>I've looked at the assembly code for it and I have seen the same inefficiencies as above. But because of the <code>|</code> operator their negative impact is still worse.</p>\n<h3>Third example.</h3>\n<blockquote>\n<pre><code>sredina_niza:=sredina_niza-mod(sredina_niza,1)\n</code></pre>\n</blockquote>\n<p>The assembly code for the <code>mod()</code> function uses a lot of instructions. What your AEC needs is an <code>int()</code> function for which you can get by with a mere <code>frndint</code> (Round to integer) instruction.<br />\nThis:</p>\n<pre><code>sredina_niza:=int(sredina_niza)\n</code></pre>\n<p>would then be much faster.</p>\n<hr />\n<p>Knowing the forementioned, I have no doubt that the MergeSort or QuickSort would be any less inefficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T06:50:26.597",
"Id": "481188",
"Score": "0",
"body": "Interesting stuff. However, I think there is some problem with the algorithm and that, no matter how efficient the Assembly is, it would still crash (cause segmentation fault) on some large arrays, such as this one: https://github.com/FlatAssembler/ArithmeticExpressionCompiler/raw/master/recursive_HybridSort/worst_case.txt"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T15:02:40.993",
"Id": "481474",
"Score": "0",
"body": "@FlatAssembler I've overcome my initial fear for the foreign language, Kroatian I believe, and have finally managed to review your program. I've posted the review separately. My first answer remains valid, but I think the second answer is more constructive. You be the judge..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T20:40:24.943",
"Id": "245048",
"ParentId": "244966",
"Score": "3"
}
},
{
"body": "\n<h2>A conceptual problem</h2>\n<p>The idea to choose between MergeSort and QuickSort looks very promising, but because the code that makes the decision is so lengthy and <strong>because that code gets repeated on every recursive call</strong>, the program is spending 99% of its time deciding and only 1% of its time sorting. That's a bad trade-off!</p>\n<p>Also consider:</p>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>While i < j\n razvrstanost := razvrstanost + (originalni_niz[i] < originalni_niz[i+1])\n i := i + 1\nEndWhile\n</code></pre>\n</blockquote>\n<p>A cascade of comparing adjacent elements is typical for the lesser sorting methods. Because in your program this cascade is repeated on arrays that get smaller and smaller, you can not hope for this approach to lead to something better/faster than an humble BubbleSort.</p>\n<p>My suggestions:</p>\n<blockquote>\n<p>Find out where it leads you if you apply the current decision process only once on the original array.</p>\n</blockquote>\n<blockquote>\n<p>Simplify the decision process. Go for Less Accurate but Much Faster.</p>\n</blockquote>\n<h2>Why c++ <code>std::sort</code> is much faster</h2>\n<p>Apart from not suffering from the above conceptual problem, that library function</p>\n<ul>\n<li><p>will have been written directly in Assembly or at least in some higher level language that translates very closely to Assembly.</p>\n</li>\n<li><p>will use 32-bit integers as much as possible (array indexing, counting, ...) Your project exclusively works with single precision floating point variables.</p>\n</li>\n<li><p>will avoid using FPU instructions whenever possible. e.g. copying variables even if they represent floats:</p>\n<pre class=\"lang-none prettyprint-override\"><code> mov eax, [donja_granica]\n mov [i], eax\n</code></pre>\n<p>Your code makes a detour via the FPU stack</p>\n<pre class=\"lang-none prettyprint-override\"><code> #i := donja_granica\n finit\n fld dword ptr [donja_granica]\n fstp dword ptr [TEMP]\n mov edx, dword ptr [TEMP]\n mov dword ptr [i], edx\n</code></pre>\n</li>\n<li><p>will use the normal stack in a straightforward fashion. e.g. preserving the <em>LeftBound</em></p>\n<pre class=\"lang-none prettyprint-override\"><code> push dword ptr [donja_granica]\n</code></pre>\n<p>Your code uses a series of arrays to mimic several stacks:</p>\n<pre class=\"lang-none prettyprint-override\"><code> #stog_s_donjim_granicama[vrh_stoga] := donja_granica\n finit\n fld dword ptr [donja_granica]\n fstp dword ptr [TEMP]\n mov edx, dword ptr [TEMP]\n fld dword ptr [vrh_stoga]\n fistp dword ptr [TEMP]\n mov ebx, dword ptr [TEMP]\n mov dword ptr [stog_s_donjim_granicama+4*ebx], edx\n</code></pre>\n</li>\n<li><p>...</p>\n</li>\n</ul>\n<h2>What you can do</h2>\n<p>The idea of your sorting methods is to partition the array into ever smaller pieces until such a piece is of length 1 or 2. You correctly return immediately for a length of 1, but for a length of 2 your code executes pointlessly all of those very costly calculations (using <code>pow()</code>, <code>mod()</code>, <code>ln()</code>, <code>exp()</code>) in order to assign values to <em>razvrstanost_na_potenciju[i]</em>, <em>polinom_pod_apsolutnom</em>, <em>Eulerov_broj_na_koju_potenciju</em>, <em>koliko_usporedbi_ocekujemo_od_QuickSorta</em>, and <em>koliko_usporedbi_ocekujemo_od_MergeSorta</em> - <strong>values that will not be used</strong>.<br />\nThis is the major reason why the code is slow, since reductions downto a length of 2 are very common.</p>\n<p>In the line <code>razvrstanost := razvrstanost / ((gornja_granica-donja_granica-1)/2) - 1</code> you are expecting, that for an already sorted partition the value be 1.<br />\nBut what if this should ever produce 0.99999999 or 1.00000001 ? Floating point divisions tend to do this.<br />\nThen the line <code>If razvrstanost = 1</code> will be missed and the code will go haywire. Could be the reason why the program crashes.</p>\n<p>Next code tries to address both concerns:</p>\n<pre class=\"lang-none prettyprint-override\"><code>razvrstanost := 0\ni := donja_granica\nj := gornja_granica - 1 ; This optimizes the following WHILE\nWhile i < j\n razvrstanost := razvrstanost + (originalni_niz[i] < originalni_niz[i+1])\n i := i + 1\nEndWhile\n\nj := j - donja_granica\n\nIf razvrstanost = j\n broj_vec_poredanih_podniza := broj_vec_poredanih_podniza + 1\n ...\n\nElseIf razvrstanost = 0\n broj_obrnuto_poredanih_podniza := broj_obrnuto_poredanih_podniza + 1\n ...\n\nElse\n i := 2\n razvrstanost := razvrstanost / (j / i) - 1\n While i <= 7 \n razvrstanost_na_potenciju[i] := pow(abs(razvrstanost), i)\n razvrstanost_na_potenciju[i] := ...\n i := i + 1\n EndWhile\n polinom_pod_apsolutnom := ...\n Eulerov_broj_na_koju_potenciju := ...\n koliko_usporedbi_ocekujemo_od_QuickSorta := ...\n koliko_usporedbi_ocekujemo_od_MergeSorta := ...\n If koliko_usporedbi_ocekujemo_od_MergeSorta < koliko_usporedbi_ocekujemo_od_QuickSorta\n broj_pokretanja_MergeSorta := broj_pokretanja_MergeSorta + 1\n ...\n\n Else ;QuickSort algoritam\n broj_pokretanja_QuickSorta := broj_pokretanja_QuickSorta + 1\n ...\n\n EndIf\nEndIf\n</code></pre>\n<hr />\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>If (gdje_smo_u_prvom_nizu = sredina_niza | originalni_niz[gdje_smo_u_drugom_nizu] < originalni_niz[gdje_smo_u_prvom_nizu]) & gdje_smo_u_drugom_nizu < gornja_granica\n</code></pre>\n</blockquote>\n<p>Because your AEC does not perform an early out on the <code>|</code> operator in this complex expression, everything in it is evaluated every single time. Moreover this expression can at some point read past the last element of the array.<br />\nNext code, using simple <code>If</code>'s, avoids reading array elements unnecessarily or illegally. I believe it's also easier to understand.</p>\n<pre class=\"lang-none prettyprint-override\"><code>i := donja_granica\ngdje_smo_u_prvom_nizu := donja_granica\ngdje_smo_u_drugom_nizu := sredina_niza\nWhile i < gornja_granica\n If gdje_smo_u_prvom_nizu = sredina_niza\n PickRightSide := 1\n ElseIf gdje_smo_u_drugom_nizu = donja_granica\n PickRightSide := 0\n Else\n PickRightSide := (originalni_niz[gdje_smo_u_drugom_nizu] < originalni_niz[gdje_smo_u_prvom_nizu])\n Endif\n If PickRightSide = 1\n pomocni_niz[i] := originalni_niz[gdje_smo_u_drugom_nizu]\n gdje_smo_u_drugom_nizu := gdje_smo_u_drugom_nizu + 1\n Else\n pomocni_niz[i] := originalni_niz[gdje_smo_u_prvom_nizu]\n gdje_smo_u_prvom_nizu := gdje_smo_u_prvom_nizu + 1\n EndIf\n i := i + 1\nEndWhile\n</code></pre>\n<hr />\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>pomocna_varijabla_za_zamijenu := originalni_niz[i + 1]\noriginalni_niz[i + 1] := originalni_niz[gornja_granica - 1]\noriginalni_niz[gornja_granica - 1] := pomocna_varijabla_za_zamijenu\ngdje_je_pivot := i + 1\n</code></pre>\n</blockquote>\n<p>This snippet can be optimized.<br />\nIf you assign <em>gdje_je_pivot</em> first, you can avoid the index addition <code>[i + 1]</code> twice. And because at this point in the code <code>originalni_niz[gornja_granica - 1]</code> is stored in the <em>pivot</em> variable, you should get it from there which will be a lot faster.</p>\n<pre class=\"lang-none prettyprint-override\"><code>gdje_je_pivot := i + 1\npomocna_varijabla_za_zamijenu := originalni_niz[gdje_je_pivot]\noriginalni_niz[gdje_je_pivot] := pivot\noriginalni_niz[gornja_granica - 1] := pomocna_varijabla_za_zamijenu\n</code></pre>\n<hr />\n<p>The simplest change you can make to AEC is to dismiss that myriad of <code>finit</code> instructions. When every snippet in the program always pops everything it pushes (and your code seems to work that way), then you only need to use <code>finit</code> once and only once at the start.</p>\n<p>You should special-case some very common operations if you desire speed.</p>\n<ul>\n<li><p>To copy a simple variable to another simple variable, you don't need to use the FPU. e.g. <code>i := donja_granica</code></p>\n<pre class=\"lang-none prettyprint-override\"><code> mov eax, [donja_granica]\n mov [i], eax\n</code></pre>\n</li>\n<li><p>Incrementing a simple variable. e.g. <code>inc i</code></p>\n<pre class=\"lang-none prettyprint-override\"><code> fld1\n fadd dword ptr [i]\n fstp dword ptr [i]\n</code></pre>\n</li>\n<li><p>Decrementing a simple variable. e.g. <code>dec i</code></p>\n<pre class=\"lang-none prettyprint-override\"><code> fld1\n fsubr dword ptr [i]\n fstp dword ptr [i]\n</code></pre>\n</li>\n<li><p>If you would compile a short list of frequently used immediates (<code>iList dw 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10</code>), then using these would be a breeze. Assigning would be very efficient. e.g. <code>i := 2</code></p>\n<pre class=\"lang-none prettyprint-override\"><code> fild word ptr [iList + 4]\n fstp dword ptr [i]\n</code></pre>\n</li>\n</ul>\n<p>There's nothing that prevents you from using the normal stack instead of dedicated arrays</p>\n<pre class=\"lang-none prettyprint-override\"><code>#AsmStart\npush dword ptr [donja_granica]\n#AsmEnd\n</code></pre>\n<h2>The segmentation fault</h2>\n<p>I see 3 reasons why this could happen:</p>\n<ul>\n<li>Reading past the last element of the array. See above.</li>\n<li>The code goes haywire if the execution misses <code>If razvrstanost=1</code>. See above.</li>\n<li>The dedicated arrays that mimic a stack are too small. This can happen when the pivotting mechanism, continually partitions the array in a very big and a very small chunk. On an array with 65536 elements, the recursion depth will rapidly exceed 1024\n(dimension of your special arrays).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T18:48:35.813",
"Id": "481487",
"Score": "1",
"body": "I've figured out myself my program is running out of stack memory, I fixed it by switching to MergeSort instead of QuickSort once `vrh_stoga` comes close to 1024."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T14:53:54.330",
"Id": "245188",
"ParentId": "244966",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T18:00:29.573",
"Id": "244966",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"assembly",
"mergesort",
"quick-sort"
],
"Title": "HybridSort of QuickSort and MergeSort"
}
|
244966
|
<p>How can I make the solution to this <a href="https://www.codewars.com/kata/5506b230a11c0aeab3000c1f/train/fsharp" rel="nofollow noreferrer">https://www.codewars.com/kata/5506b230a11c0aeab3000c1f/train/fsharp</a> more "functional"?</p>
<pre><code>module Evaporator
let evaporator (content: double) (evapPerDay: double) (threshold: double): int =
let minUsefulAmount = content * (threshold / 100.)
let evapAsPercentage = evapPerDay / 100.
let rec solve (content: double) (dayCount: int) =
let amountLost = content * evapAsPercentage
let newContent = content - amountLost
let stillUseful = newContent > minUsefulAmount
let result =
match stillUseful with
| true -> solve newContent dayCount + 1
| false -> dayCount
result
solve content 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T05:16:10.923",
"Id": "481014",
"Score": "0",
"body": "Hello, to increase odds of receiving more answers you could add the description of the task to the link you already provided and the tag `programming-challenge`."
}
] |
[
{
"body": "<p>The first thing that comes into my mind is that if <code>evapPerDay</code> is <code><= 0</code> the function will continue infinitely - or more precise: until a stack overflow is encountered. So you have to guard against that:</p>\n<pre><code>let evaporatorReview (content: float) (evapPerDay: float) (threshold: float): int =\n if evapPerDay <= 0. then \n failwith "evapPerDay must be greater than 0.0"\n else\n // ... The original algorithm\n</code></pre>\n<hr />\n<p>The next is that by having the unnecessary local <code>result</code> variable <code>solve()</code> isn't tail recursive. You can fix that by simply return directly from the <code>match</code>-entries:</p>\n<pre><code>let evaporator (content: float) (evapPerDay: float) (threshold: float): int =\n let minUsefulAmount = content * (threshold / 100.)\n let evapAsPercentage = evapPerDay / 100.\n\n let rec solve (content: float) (dayCount: int) =\n let amountLost = content * evapAsPercentage\n let newContent = content - amountLost\n let stillUseful = newContent > minUsefulAmount\n\n match stillUseful with\n | true -> solve newContent (dayCount + 1)\n | false -> dayCount\n solve content 1\n</code></pre>\n<hr />\n<p>IMO all the temporary variables in <code>solve()</code> blur what actually is going on. By skipping them and do the calculations directly in the recursive call to <code>solve()</code> the picture is more clear:</p>\n<pre><code>let evaporator (content: float) (evapPerDay: float) (threshold: float): int =\n if evapPerDay <= 0. then \n failwith "evapPerDay must be greater than 0.0"\n else\n let limit = content * threshold / 100.\n let rec solve (content: float) (dayCount: int) =\n match content with\n | x when x <= limit -> dayCount\n | _ -> solve (content * (1. - evapPerDay / 100.)) (dayCount + 1)\n\n solve content 0\n</code></pre>\n<hr />\n<p>In fact you don't have to calculate on the content, you can do it percentage wise:</p>\n<pre><code>let evaporatorReview (content: float) (evapPerDay: float) (threshold: float): int =\n if evapPerDay <= 0. then \n failwith "evapPerDay must be greater than 0.0"\n else\n let limit = threshold / 100.\n let rec solve (remaining: float) (dayCount: int) =\n match remaining with\n | x when x <= limit -> dayCount\n | _ -> solve (remaining * (1. - evapPerDay / 100.)) (dayCount + 1)\n\n solve 1. 0\n</code></pre>\n<hr />\n<p>The mathematical "discipline" in question here is exponential growth (<code>r > 0</code>) or decay (<code>r < 0</code>) and there is a formula for that:</p>\n<pre><code>Xn = X0 * (1 + r)^n\n</code></pre>\n<p>Where <code>Xn</code> is <code>threshold</code>, <code>X0</code> is <code>100</code> or <code>content</code>, <code>r</code> is <code>evapPerDay / 100.</code> and <code>n</code> is the number of days = the result.</p>\n<p>This can be use in sequential calculations ending when the threshold is met:</p>\n<pre><code>let evaporatorSeq (content: float) (evapPerDay: float) (threshold: float): int =\n if evapPerDay <= 0. then \n failwith "evapPerDay must be greater than 0.0"\n else\n let limit = threshold / 100.0\n Seq.initInfinite (fun i -> i) \n |> Seq.takeWhile (fun n -> Math.Pow(1.0 - evapPerDay / 100.0, float n) > limit)\n |> Seq.last\n |> (+) 1\n</code></pre>\n<hr />\n<p>But even better, it can be solved in respect to <code>n</code> as :</p>\n<pre><code>n = log(Xn/X0) / log(1 + r)\n</code></pre>\n<p>which can be used in the function as an O(1) - solution:</p>\n<pre><code>let evaporator content evapPerDay threshold = \n match evapPerDay with\n | x when x = 100. -> 1\n | x when x <= 0.0 -> failwith "evapPerDay must be greater than 0.0"\n | _ -> int (Math.Ceiling(Math.Log((threshold / 100.) / 1.) / Math.Log(1. - evapPerDay / 100.)))\n</code></pre>\n<p>The division by <code>1.</code> is of cause redundant, but it emphasize the relation of the expression to its origin.</p>\n<p><code>if evapPerDay = 100. then 1</code> is necessary here because if <code>evapPerDay = 100</code> then <code>Math.Log(1.0 - evapPerDay / 100.)</code> becomes <code>Math.Log(0.)</code> which isn't defined.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T06:49:31.170",
"Id": "244984",
"ParentId": "244967",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T18:21:27.453",
"Id": "244967",
"Score": "4",
"Tags": [
"programming-challenge",
"f#"
],
"Title": "CodeWars Deodorant Evaporator"
}
|
244967
|
<p>I'm trying to work up to being able to print the hailstone sequence in assembly. To do that though, I first needed to learn how to actually print a number out using the <code>write</code> system call.</p>
<p>After a few design iterations, I ended up using division to get each digit one at a time by using the remainder. Each remainder gets pushed onto the stack, then the address of the stack is given to the system call to print out.</p>
<p>What I'd like advice on:</p>
<ul>
<li><p>In a couple places, I have math split out over multiple lines, like:</p>
<pre><code> sub edx, esp ; Calculate how many were pushed
dec edx
</code></pre>
<p>It doesn't seem like it's possible to combine that into something like <code>sub edx, esp - 0</code>, but if there is a neater way, I'd like to know.</p>
</li>
<li><p>This is my first time using <code>div</code>. Is there anything wrong with how I'm using it? Also, is there a sane way of not using <code>div</code> altogether? Apparently it's stupid slow and should be avoided if possible.</p>
</li>
<li><p>Anything else notable. I'm a super-beginner, and this code is quite verbose.</p>
</li>
</ul>
<p>I'm using <code>n</code> to represent the number that I want to print out. In theory though, that number could come from anywhere. It's just a placeholder for the exercise.</p>
<pre class="lang-none prettyprint-override"><code>global _start
section .data
n: dd 123456
section .text
_start:
mov ebp, esp ; So we can tell how many were pushed
mov ecx, [n]
.loop:
mov edx, 0 ; Zeroing out edx for div
mov eax, ecx ; Num to be divided
mov ebx, 10 ; Divide by 10
div ebx
mov ecx, eax ; Quotient
add edx, '0'
push edx ; Remainder
cmp ecx, 0
jne .loop
mov eax, 4 ; Write system call
mov ebx, 1 ; STDOUT
mov ecx, esp ; The string on the stack
mov edx, ebp
sub edx, esp ; Calculate how many were pushed
dec edx
int 0x80
mov eax, 1
mov ebx, 0
int 0x80
</code></pre>
<p>Assembled and linked using:</p>
<pre><code>nasm numprint2.asm -g -f elf32 -Wall -o numprint2.o
ld numprint2.o -m elf_i386 -o numprint2
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T00:43:58.017",
"Id": "490832",
"Score": "0",
"body": "Just curious, how come you went with 32 bit over 64 bit?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T00:48:41.403",
"Id": "490834",
"Score": "1",
"body": "@JoseFernandoLopezFernandez Our school decided to go with 32-bit. I believe it had to do with tools we used later (like immunity) being easier to use. We did all the debugging later on a 32-bit VM."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T18:30:11.980",
"Id": "244968",
"Score": "5",
"Tags": [
"beginner",
"nasm"
],
"Title": "Printing a number from memory in assembly"
}
|
244968
|
<p>I'm wondering if there are better practices, and optimizations I could make on my code, to do things easier/faster.<br />
I have added comments, in many places in the code, to make understanding easier.</p>
<pre><code>import sys
class Node():
def __init__(self, data):
self.data = data # holds the key
self.parent = None #pointer to the parent
self.left = None # pointer to left child
self.right = None #pointer to right child
self.color = 1 # 1 . Red, 0 . Black
# class RedBlackTree implements the operations in Red Black Tree
class RedBlackTree():
def __init__(self, List=None):
self.TNULL = Node(0)
self.TNULL.color = 0
self.TNULL.left = None
self.TNULL.right = None
self.root = self.TNULL
if List:
for val in List:
self.insert(val)
def __pre_order_helper(self, node):
if node != TNULL:
sys.stdout.write(node.data + " ")
self.__pre_order_helper(node.left)
self.__pre_order_helper(node.right)
def __in_order_helper(self, node):
if node != TNULL:
self.__in_order_helper(node.left)
sys.stdout.write(node.data + " ")
self.__in_order_helper(node.right)
def __post_order_helper(self, node):
if node != TNULL:
self.__post_order_helper(node.left)
self.__post_order_helper(node.right)
sys.stdout.write(node.data + " ")
def __search_tree_helper(self, node, key):
if node == TNULL or key == node.data:
return node
if key < node.data:
return self.__search_tree_helper(node.left, key)
return self.__search_tree_helper(node.right, key)
# fix the rb tree modified by the delete operation
def __fix_delete(self, x):
while x != self.root and x.color == 0:
if x == x.parent.left:
s = x.parent.right
if s.color == 1:
# case 3.1
s.color = 0
x.parent.color = 1
self.left_rotate(x.parent)
s = x.parent.right
if s.left.color == 0 and s.right.color == 0:
# case 3.2
s.color = 1
x = x.parent
else:
if s.right.color == 0:
# case 3.3
s.left.color = 0
s.color = 1
self.right_rotate(s)
s = x.parent.right
# case 3.4
s.color = x.parent.color
x.parent.color = 0
s.right.color = 0
self.left_rotate(x.parent)
x = self.root
else:
s = x.parent.left
if s.color == 1:
# case 3.1
s.color = 0
x.parent.color = 1
self.right_rotate(x.parent)
s = x.parent.left
if s.left.color == 0 and s.right.color == 0:
# case 3.2
s.color = 1
x = x.parent
else:
if s.left.color == 0:
# case 3.3
s.right.color = 0
s.color = 1
self.left_rotate(s)
s = x.parent.left
# case 3.4
s.color = x.parent.color
x.parent.color = 0
s.left.color = 0
self.right_rotate(x.parent)
x = self.root
x.color = 0
def __rb_transplant(self, u, v):
if u.parent == None:
self.root = v
elif u == u.parent.left:
u.parent.left = v
else:
u.parent.right = v
v.parent = u.parent
def __delete_node_helper(self, node, key):
# find the node containing key
z = self.TNULL
while node != self.TNULL:
if node.data == key:
z = node
if node.data <= key:
node = node.right
else:
node = node.left
if z == self.TNULL:
print("Couldn't find key in the tree")
return
y = z
y_original_color = y.color
if z.left == self.TNULL:
x = z.right
self.__rb_transplant(z, z.right)
elif (z.right == self.TNULL):
x = z.left
self.__rb_transplant(z, z.left)
else:
y = self.minimum(z.right)
y_original_color = y.color
x = y.right
if y.parent == z:
x.parent = y
else:
self.__rb_transplant(y, y.right)
y.right = z.right
y.right.parent = y
self.__rb_transplant(z, y)
y.left = z.left
y.left.parent = y
y.color = z.color
if y_original_color == 0:
self.__fix_delete(x)
# fix the red-black tree
def __fix_insert(self, k):
while k.parent.color == 1: # while k's parent is red
if k.parent == k.parent.parent.right: # if k's parent is the right child of k's grandparent, then the uncle is the left child of k's grandparent
u = k.parent.parent.left # uncle
if u.color == 1: # if k's parent and uncle are both red ---> recolor both uncle and the parent to black, and the grandparent to red.
# case 3.1
u.color = 0
k.parent.color = 0
k.parent.parent.color = 1
k = k.parent.parent
else: # if k's parent is red, and uncle is black
if k == k.parent.left:
# case 3.2.2, if parent is the right child of grandparent and k is the left child of parent (Right-Left) ---> Perform Right Rotation on Parent, and it becomes case 3.2.1
k = k.parent
self.right_rotate(k)
# case 3.2.1, if parent is the right child of grandparent and k is the right child of parent {Right-Right} ---> Perform Left Rotation on grandparent, and recolor k's new parent to black, and it's sibling to red
k.parent.color = 0
k.parent.parent.color = 1
self.left_rotate(k.parent.parent)
else: # if k's parent is the left child of k's grandparent, then the uncle is the right child of k's grandparent
u = k.parent.parent.right # uncle
if u.color == 1:
# mirror case 3.1
u.color = 0
k.parent.color = 0
k.parent.parent.color = 1
k = k.parent.parent
else:
if k == k.parent.right:
# mirror case 3.2.2
k = k.parent
self.left_rotate(k)
# mirror case 3.2.1
k.parent.color = 0
k.parent.parent.color = 1
self.right_rotate(k.parent.parent)
if k == self.root:
break
self.root.color = 0
def __print_helper(self, node, indent, last):
# print the tree structure on the screen
if node != self.TNULL:
sys.stdout.write(indent)
if last:
sys.stdout.write("R----")
indent += " "
else:
sys.stdout.write("L----")
indent += "| "
s_color = "RED" if node.color == 1 else "BLACK"
print(str(node.data) + "(" + s_color + ")")
self.__print_helper(node.left, indent, False)
self.__print_helper(node.right, indent, True)
# Pre-Order traversal
# Node.Left Subtree.Right Subtree
def preorder(self):
self.__pre_order_helper(self.root)
# In-Order traversal
# left Subtree . Node . Right Subtree
def inorder(self):
self.__in_order_helper(self.root)
# Post-Order traversal
# Left Subtree . Right Subtree . Node
def postorder(self):
self.__post_order_helper(self.root)
# search the tree for the key k
# and return the corresponding node
def searchTree(self, k):
return self.__search_tree_helper(self.root, k)
# find the node with the minimum key
def minimum(self, node):
while node.left != self.TNULL:
node = node.left
return node
# find the node with the maximum key
def maximum(self, node):
while node.right != self.TNULL:
node = node.right
return node
# find the successor of a given node
def successor(self, x):
# if the right subtree is not None,
# the successor is the leftmost node in the
# right subtree
if x.right != self.TNULL:
return self.minimum(x.right)
# else it is the lowest ancestor of x whose
# left child is also an ancestor of x.
y = x.parent
while y != self.TNULL and x == y.right:
x = y
y = y.parent
return y
# find the predecessor of a given node
def predecessor(self, x):
# if the left subtree is not None,
# the predecessor is the rightmost node in the
# left subtree
if (x.left != self.TNULL):
return self.maximum(x.left)
y = x.parent
while y != self.TNULL and x == y.left:
x = y
y = y.parent
return y
# rotate left at node x
def left_rotate(self, x):
y = x.right
x.right = y.left
if y.left != self.TNULL:
y.left.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left = x
x.parent = y
# rotate right at node x
def right_rotate(self, x):
y = x.left
x.left = y.right
if y.right != self.TNULL:
y.right.parent = x
y.parent = x.parent
if x.parent == None:
self.root = y
elif x == x.parent.right:
x.parent.right = y
else:
x.parent.left = y
y.right = x
x.parent = y
# insert the key to the tree in its appropriate position
# and fix the tree
def insert(self, key):
# Ordinary Binary Search Insertion
node = Node(key)
node.parent = None
node.data = key
node.left = self.TNULL
node.right = self.TNULL
node.color = 1 # new node must be red
y = None
x = self.root
while x != self.TNULL:
y = x
if node.data < x.data:
x = x.left
else:
x = x.right
# y is parent of x
node.parent = y
if y == None:
self.root = node
elif node.data < y.data:
y.left = node
else:
y.right = node
# if new node is a root node, simply return
if node.parent == None:
node.color = 0
return
# if the grandparent is None, simply return
if node.parent.parent == None:
return
# Fix the tree
self.__fix_insert(node)
def get_root(self):
return self.root
# delete the node from the tree
def delete_node(self, data):
self.__delete_node_helper(self.root, data)
# print the tree structure on the screen
def pretty_print(self):
self.__print_helper(self.root, "", True)
if __name__ == "__main__":
bst = RedBlackTree([1,2,3,4,5,6])
</code></pre>
|
[] |
[
{
"body": "<h2>Docstrings</h2>\n<p>You are using comments instead of docstrings, which is not a good tone, as I think. You can read more about docstring in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>. Also it's not necessary to write class name in docstring. For example, you can write <code>Implements the operations in Red Black Tree</code> instead of <code>class RedBlackTree implements the operations in Red Black Tree</code>.</p>\n<h2>Type hinting</h2>\n<p>Your code doesn't have type hinting at all. It's not really a bad thing, but it's always better to do type hinting. You can read more about why you may want to do it in <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a> and how to do it <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<h2>Double underscores in method names</h2>\n<p>It's not really necessary to write <code>__</code> before the method name, because <code>_</code> is already enough. But it's a matter of preference.</p>\n<h2>Node colors</h2>\n<p>I'd use <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enum</a> instead of 0/1 for colors. Your code will be more understandable if you write <code>self.color = Color.Red</code> instead of <code>self.color = 1</code>.</p>\n<h2>Node.data</h2>\n<p>Data is very wide and uninformative name. If <code>data</code> holds <code>key</code>, why don't you name it <code>key</code>?</p>\n<h2>sys.stdout</h2>\n<p>I suppose that there's no need to overcomplicate your code by using <code>sys.stdout.write</code> instead of <code>print</code>, which also prints to stdout.</p>\n<h2>RedBlackTree.pretty_print()</h2>\n<p>You should definitely read about <a href=\"https://holycoders.com/python-dunder-special-methods/\" rel=\"nofollow noreferrer\">dunders</a>. They will allow you to integrate your class with default python methods. In this particular case dunders will allow you to use <code>print(some_tree)</code> instead of <code>some_tree.pretty_print()</code>.</p>\n<h2>Long methods</h2>\n<p>Some of your methods are really long and difficult to read. For example, <code>__fix_delete</code>. Also comments like <code># case 3.1</code> are uninformative. I guess you should extract each case in separate function and write a little bit more about each case in docstrings.</p>\n<h2>Style comments</h2>\n<p>I think that every Python programmer should use <a href=\"https://pylint.org/\" rel=\"nofollow noreferrer\">pylint</a>. It's a good tool to find small issues like too long lines, absence of spaces after commas, etc. It's really helpful, but try not to become pylint maniac - it's not always necessary to achieve 10/10.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T14:14:26.487",
"Id": "481116",
"Score": "3",
"body": "Re. `_` _is a matter of preference_ - it's more than that. Single- and double-underscored methods follow well-defined conventions - single underscores are for \"weakly-enforced private variables\", and double underscores are for name mangling. Read https://stackoverflow.com/questions/1301346"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T10:40:46.840",
"Id": "245028",
"ParentId": "244971",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T19:43:38.020",
"Id": "244971",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"tree",
"binary-search-tree"
],
"Title": "Red-Black Tree Implementation in Python"
}
|
244971
|
<p>This program takes a text file and parses the initial cube start position, the pattern that the result should have and an optional start sequence. The cube is using numbers instead of colors for more exact positioning. Each face is represented by 9 numbers 3 rows of 3. The top face would be 1 2 3 4 5 6 7 8 9. The left face would be 10 11 12 13 14 15 16 17 18. etc. Speed is the most important thing to consider. On my computer with 16 cores it can solve a 7 move sequence in a couple of seconds. The time however grows by a factor of 12 with each move. So sequence of 10 moves would be hours. It will create multiple threads to find a sequence.</p>
<p>I can add the header files if needed.</p>
<p>Here is the code:</p>
<p><strong>sequencefinder.cpp</strong></p>
<pre><code>#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <thread>
#include "cube.h"
#include "str.h"
#include "findsequence.h"
using namespace std;
int find_sequence(string& file_name, bool use_slice);
void read_cube_start(istream& inputstream, vector<face_val<face_val_type>>& cubestart);
void read_pattern(istream& inputstream, vector<face_val<face_val_type>>& pattern);
void read_sequence(istream& inputstream, string& sequence);
void readstring(istream& inputstream, string& str);
void readfaceval(istream& inputstream, face_val<face_val_type>& val);
int parse_args(int argc, char** argv);
int check_parameter(vector<string>& args, string searcharg, string& var);
static const vector<face_val<face_val_type>> init = {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};
static int max_depth = 8;
//************************************
// Method: main
// FullName: main
// Access: public
// Returns: int
// Qualifier:
// Parameter: const int argc
// Parameter: char * * argv
//************************************
int main(const int argc, char** argv)
{
try
{
return parse_args(argc, argv);
}
catch (...)
{
cout << "Exception thrown." << endl;
return -1;
}
}
//************************************
// Method: parse_args
// FullName: parse_args
// Access: public
// Returns: int
// Qualifier:
// Parameter: const int argc
// Parameter: char * * argv
//
// Parse the arguments
//************************************
int parse_args(const int argc, char** argv)
{
if (argc < 2)
{
cout << "No options specified." << endl;
return -1;
}
string name;
string matchpattern;
string cubestring;
string sequence;
string reversesequence;
string filename;
string executesequence;
string executereversesequence;
string slice;
string maxdepth;
bool use_slice;
vector<string> args;
for (auto argindex = 1; argindex < argc; argindex++)
args.emplace_back(argv[argindex]);
auto result = check_parameter(args, "-c", cubestring);
if (result < 0) return result;
result = check_parameter(args, "-slice", slice);
if (result < 0) return result;
result = check_parameter(args, "-f", filename);
if (result < 0) return result;
result = check_parameter(args, "-depth", maxdepth);
if (result < 0) return result;
if (!maxdepth.empty())
{
max_depth = stoi(maxdepth);
}
use_slice = !slice.empty();
if (!args.empty())
{
cout << "Unknown argument(s) ";
for (auto& arg : args)
cout << arg << " ";
cout << endl;
return -1;
}
if (!filename.empty())
{
result = find_sequence(filename, use_slice);
}
return result;
}
//************************************
// Method: check_parameter
// FullName: check_parameter
// Access: public
// Returns: int
// Qualifier: // NOLINT(performance-unnecessary-value-param)
// Parameter: vector<string> & args
// Parameter: const string searcharg
// Parameter: string & var
//
// check a single parameter
//************************************
int check_parameter(vector<string>& args, const string searcharg, string& var) // NOLINT(performance-unnecessary-value-param)
{
auto argindex = 0;
const auto argc = int(args.size());
while (argindex < argc)
{
if (args[argindex++] == searcharg)
{
if (argindex >= argc)
{
cout << "No sequence specified with " << args[argindex] << "." << endl;
return -1;
}
var = args[argindex];
args.erase(args.begin() + (argindex - 1ll));
args.erase(args.begin() + (argindex - 1ll));
return 1;
}
}
return 0;
}
//************************************
// Method: read_cube_start
// FullName: read_cube_start
// Access: public
// Returns: void
// Qualifier:
// Parameter: istream & inputstream
// Parameter: vector<face_val<face_val_type>>& cubestart
//************************************
void read_cube_start(istream& inputstream, vector<face_val<face_val_type>>& cubestart)
{
cubestart.clear();
while (!inputstream.eof() && cubestart.size() < 54)
{
face_val<face_val_type> val;
readfaceval(inputstream, val);
cubestart.push_back(val);
}
}
//************************************
// Method: read_pattern
// FullName: read_pattern
// Access: public
// Returns: void
// Qualifier:
// Parameter: istream & inputstream
// Parameter: vector<face_val<face_val_type>> & pattern
//************************************
void read_pattern(istream& inputstream, vector<face_val<face_val_type>>& pattern)
{
pattern.clear();
while (!inputstream.eof() && pattern.size() < 54)
{
face_val<face_val_type> val;
readfaceval(inputstream, val);
pattern.push_back(val);
}
}
//************************************
// Method: read_sequence
// FullName: read_sequence
// Access: public
// Returns: void
// Qualifier:
// Parameter: istream & inputstream
// Parameter: string & sequence
//************************************
void read_sequence(istream& inputstream, string& sequence)
{
sequence.clear();
string temp;
readstring(inputstream, temp);
if (temp == "**" || temp != "*") return;
temp.clear();
do
{
readstring(inputstream, temp);
if (temp != "*")
{
if (sequence.length() > 0) sequence.append(" ");
sequence.append(temp);
}
} while (temp != "*");
}
//************************************
// Method: find_sequence
// FullName: find_sequence
// Access: public
// Returns: int
// Qualifier:
// Parameter: string & file_name
// Parameter: const bool use_slice
//************************************
int find_sequence(string& file_name, const bool use_slice)
{
ifstream inputfile;
try
{
inputfile.open(file_name);
if (!inputfile.is_open())
throw;
}
catch (...)
{
cout << "Error opening input file." << endl;
return -1;
}
while (!inputfile.eof())
{
auto cube_values = init;
vector<face_val<face_val_type>> pattern;
string start_seq;
string case_name;
readstring(inputfile, case_name);
if (inputfile.eof())
continue;
read_cube_start(inputfile, cube_values);
read_pattern(inputfile, pattern);
read_sequence(inputfile, start_seq);
std::cout << "<Entry> " << endl;
std::cout << " <Key>" << case_name << "</Key>" << endl;
string found_sequence;
findsequence f;
const auto found = f.find_sequence(cube_values, pattern, start_seq, found_sequence, 0, max_depth, use_slice);
if (found)
{
auto seq = start_seq.append(" ") + found_sequence;
seq = trim(seq);
if (!seq.empty())
{
std::cout << " <Value>" << seq << "</Value>" << endl;
}
else
{
std::cout << " <Value />" << endl;
}
}
else
{
cout << " <!-- Not Found! -->" << endl << " <Value />" << endl;
}
cout << "</Entry>" << endl << endl;
}
inputfile.close();
return 0;
}
//************************************
// Method: readstring
// FullName: readstring
// Access: public
// Returns: void
// Qualifier:
// Parameter: istream & inputstream
// Parameter: string & str
//************************************
void readstring(istream& inputstream, string& str)
{
string temp;
while (!inputstream.eof() && temp.empty())
{
inputstream >> temp;
str = trim(temp);
if (str.length() > 1 && str[0] == '/' && str[1] == str[0])
{
cout << str << " ";
getline(inputstream, str);
cout << str << endl;
temp.erase();
}
}
}
//************************************
// Method: readfaceval
// FullName: readfaceval
// Access: public
// Returns: void
// Qualifier:
// Parameter: istream & inputstream
// Parameter: face_val<face_val_type> val
//************************************
void readfaceval(istream& inputstream, face_val<face_val_type>& val)
{
string temp;
readstring(inputstream, temp);
if (temp == "-")
{
val = 0;
return;
}
const auto n = stoi(temp);
val = n;
}
</code></pre>
<p><strong>findsequence.cpp</strong></p>
<pre><code>#include <string>
#include <vector>
#include <iostream>
#include <thread>
#include <memory>
#include "cube.h"
#include "findsequence.h"
#include "str.h"
#ifndef __countof
#define _countof(array) (sizeof(array) / sizeof(array[0]))
#endif
//************************************
// Method: find_sequence
// FullName: findsequence::find_sequence
// Access: public
// Returns: bool
// Qualifier:
// Parameter: cube * cube_original
// Parameter: std::vector<face_val<face_val_type>> & pattern
// Parameter: int n
// Parameter: std::vector<std::string> & data
// Parameter: std::string & out
//
// Find the moves from a given cube that
// makes the cube match the pattern. The number of moves
// will be exactly n or 0 if the cube already has the pattern.
// On exit out will be the sequence of moves or empty string.
// This will return true if the pattern is matched.
//
// This will start a thread for each possible move and wait for all to complete.
// This is the second layer of the findsequence API
//************************************
bool findsequence::find_sequence(cube* cube_original, std::vector<face_val<face_val_type>>& pattern, int n,
std::vector<std::string>& data, std::string& out)
{
out = "";
// Check for initial match
if (*cube_original == pattern)
{
return true;
}
if (n > -1)
{
constexpr auto buff_sz = 26;
auto timer = time(nullptr);
char buffer[buff_sz];
const auto tm_info = localtime(&timer);
strftime(buffer, _countof(buffer), "%Y-%m-%d %H:%M:%S", tm_info);
std::cout << " <!-- Level " << n << " " << buffer << " -->" << std::endl;
}
auto result = false;
// create the thread start data
auto threaddata = std::vector<std::unique_ptr<thread_start_data>>(data.size());
for (auto i = 0lu; i < data.size(); i++)
{
threaddata[i] = std::make_unique<thread_start_data>(cube_original, pattern, n, data, data[i], this);
}
// Create the threads
auto threads = std::vector<std::thread>(threaddata.size());
for (auto i = 0lu; i < threads.size(); i++)
{
threads[i] = std::thread(&find_sequence_async, threaddata[i].get());
}
// wait for threads to terminate
for (auto& t : threads)
{
t.join();
}
// Check result
for (auto& td : threaddata)
{
if (!result && td->result)
{
// save result
out = td->out;
result = true;
break;
}
}
return result;
}
//************************************
// Method: find_sequence
// FullName: findsequence::find_sequence
// Access: public
// Returns: bool
// Qualifier:
// Parameter: std::vector<face_val<face_val_type>> & cube_initial_values
// Parameter: std::vector<face_val<face_val_type>> & pattern
// Parameter: std::string & start_seq
// Parameter: std::string & out
// Parameter: const int start
// Parameter: const int max_moves
// Parameter: const bool use_slice
//
// Find the moves from a given cube string that
// makes the cube match the pattern (pattern). The number of moves will up to n.
// On exit out will be the sequence of moves or empty string.
// This will return true if the pattern is matched.
// This will start a thread for each possible move and wait for all to complete.
//
// This is the topmost layer of the find_sequence API
//************************************
bool findsequence::find_sequence(std::vector<face_val<face_val_type>>& cube_initial_values, std::vector<face_val<face_val_type>>& pattern, std::string& start_seq,
std::string& out, const int start, const int max_moves, const bool use_slice)
{
static std::vector<std::string> cube_directions =
{
"U", "Ui", "D", "Di", "L", "Li", "R", "Ri", "B", "Bi", "F", "Fi",
"Us", "Ds", "Ls", "Rs", "Fs", "Bs"
};
static std::vector<std::string> cube_directions_no_slice =
{
"U", "Ui", "D", "Di", "L", "Li", "R", "Ri", "B", "Bi", "F", "Fi"
};
auto data = use_slice ? cube_directions : cube_directions_no_slice;
const auto cube_original = std::make_unique<cube>();
cube_original->set_cube(cube_initial_values);
// if there is a start sequence execute it here
if (!start_seq.empty())
{
cube_original->execute_sequence(start_seq);
}
auto found = false;
for (auto n = start; !found && n <= max_moves; n++)
{
// call second layer of API
found = find_sequence(cube_original.get(), pattern, n, data, out);
}
return found;
}
//************************************
// Method: find_sequence
// FullName: findsequence::find_sequence
// Access: public
// Returns: void
// Qualifier: const
// Parameter: cube * cube_original
// Parameter: std::vector<face_val<face_val_type>> & pattern
// Parameter: const int n
// Parameter: std::vector<std::string> & data
// Parameter: std::string & out
// Parameter: std::string & start
// Parameter: bool & result
//************************************
void findsequence::find_sequence(cube* cube_original, std::vector<face_val<face_val_type>>& pattern, const int n,
std::vector<std::string>& data, std::string& out, std::string& start, bool& result) const
{
std::vector<face_val<face_val_type>> cube_initial_values;
cube_original->get_cube(cube_initial_values);
find_sequence(cube_initial_values, pattern, n, data, out, start, result);
}
//************************************
// Method: find_sequence
// FullName: findsequence::find_sequence
// Access: public
// Returns: void
// Qualifier: const
// Parameter: std::string & cube_initial_values
// Parameter: std::vector<std::string> & pattern
// Parameter: const int n
// Parameter: std::vector<std::string> & data
// Parameter: std::string & out
// Parameter: std::string & start
// Parameter: bool & result
//************************************
void findsequence::find_sequence(std::vector<face_val<face_val_type>>& cube_initial_values, std::vector<face_val<face_val_type>>& pattern,
const int n, std::vector<std::string>& data, std::string& out, std::string& start, bool& result) const
{
result = false;
auto indexlist = std::vector<int>(n, 0);
auto done = false;
const auto end = data.size();
std::vector<std::string> start_moves;
std::string chars = "\t\n\r\v\f ";
split(start, chars, start_moves);
auto c = std::make_unique<cube>();
while (!done)
{
c->set_cube(cube_initial_values);
auto tokens = start_moves;
for (auto i = 1; i < n; i++)
{
tokens.push_back(data[indexlist[i]]);
}
c->execute_sequence(tokens);
done = true;
if (*c == pattern)
{
join(tokens, out, " ");
result = true;
}
else
{
for (auto index = 1; index < n; index++)
{
if (indexlist[index] + 1 < int(end))
{
indexlist[index]++;
done = false;
break;
}
indexlist[index] = 0;
}
}
}
}
//************************************
// Method: find_sequence_async
// FullName: findsequence::find_sequence_async
// Access: private static
// Returns: void
// Qualifier:
// Parameter: thread_start_data * threadstart
//************************************
void findsequence::find_sequence_async(thread_start_data* threadstart)
{
const auto sz = threadstart->n;
auto data = threadstart->data;
auto pattern = threadstart->pattern;
std::vector<face_val<face_val_type>> cube_initial_values;
threadstart->cube_original->get_cube(cube_initial_values);
auto c = std::make_unique<cube>();
c->set_cube(cube_initial_values);
std::string out;
bool result;
auto start = threadstart->start;
threadstart->instance->find_sequence(cube_initial_values, pattern, sz, data, out, start, result);
threadstart->result = result;
threadstart->out = out;
}
</code></pre>
<p><strong>cube.cpp</strong></p>
<pre><code>#include <cstdlib>
#include <cstring>
#include <ctime>
#include <string>
#include <vector>
#include "cube.h"
#include "str.h"
//************************************
// Method: cube
// FullName: cube::cube
// Access: public
// Returns:
// Qualifier:
//
// Build a default cube.
//************************************
cube::cube()
{
const auto time_ui = unsigned (time(nullptr));
srand(time_ui);
whitechars = "\t\n\r\v\f ";
record_ = true;
init_cube();
}
//************************************
// Method: init_cube
// FullName: cube::init_cube
// Access: public
// Returns: void
// Qualifier:
//
// Initialize the cube.
// This clears _moves and _scramble_sequence.
//************************************
void cube::init_cube()
{
face *faces[] = { &up, &left, &front, &right, &back, &down };
auto n = 1;
for (auto& f : faces)
for (auto& row : f->square)
for (auto& col : row)
col = n++;
moves_.clear();
scramble_sequence_.clear();
}
//************************************
// Method: set_cube
// FullName: cube::set_cube
// Access: public
// Returns: void
// Qualifier:
// Parameter: const char * cube_values
//
// Set cube values.
// This clears _moves and _scramble_sequence.
//************************************
void cube::set_cube(std::vector<face_val<face_val_type>>& cube_values)
{
face *faces[] = { &up, &left, &front, &right, &back, &down };
auto n = 0;
for (auto& f : faces)
for (auto& row : f->square)
for (auto& col : row)
col = cube_values[n++];
moves_.clear();
scramble_sequence_.clear();
}
//************************************
// Method: get_cube
// FullName: cube::get_cube
// Access: private
// Returns: void
// Qualifier: const
// Parameter: std::vector<face_val<face_val_type>> & pattern
//************************************
void cube::get_cube(std::vector<face_val<face_val_type>>& pattern) const
{
pattern.clear();
const face *faces[] = { &up, &left, &front, &right, &back, &down };
for (auto& f : faces)
for (auto& row : f->square)
for (auto& col : row)
pattern.push_back(col);
}
//************************************
// Method: clone
// FullName: cube::clone
// Access: public
// Returns: cube::cube *
// Qualifier:
//
// This clones the cube instance
//************************************
cube * cube::clone() const
{
auto clone_cube = std::make_unique<cube>();
for (auto row = 0; row < cube_size; row++)
for (auto col = 0; col < cube_size; col++)
{
clone_cube->up.square[row][col] = up.square[row][col];
clone_cube->left.square[row][col] = left.square[row][col];
clone_cube->front.square[row][col] = front.square[row][col];
clone_cube->right.square[row][col] = right.square[row][col];
clone_cube->back.square[row][col] = back.square[row][col];
clone_cube->down.square[row][col] = down.square[row][col];
}
return clone_cube.get();
}
// ReSharper disable once CppMemberFunctionMayBeStatic
//************************************
// Method: simple_solve
// FullName: cube::simple_solve
// Access: public
// Returns: bool
// Qualifier:
// Parameter: char * buffer
// Parameter: size_t * sz
//
// This performs a simple solve
//************************************
bool cube::simple_solve(char* buffer, size_t* sz)
{
// const c_simple_solver solver(this);
// return solver.solve(buffer, sz);
return true;
}
//************************************
// Method: issolved
// FullName: cube::issolved
// Access: public
// Returns: bool
// Qualifier:
//
// This returns true if the cube is solved
//************************************
bool cube::issolved()
{
return up.issolved() && left.issolved() && front.issolved() && right.issolved() && back.issolved() && down.issolved();
}
//************************************
// Method: f
// FullName: cube::f
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the front face clockwise
//************************************
void cube::f()
{
front.rotate_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[cube_size - 1][cube_size - 1 - index];
up.square[cube_size - 1][cube_size - 1 - index] = left.square[index][cube_size - 1];
left.square[index][cube_size - 1] = down.square[0][index];
down.square[0][index] = right.square[cube_size - 1 - index][0];
right.square[cube_size - 1 - index][0] = temp;
}
if (record_)
moves_ += "F ";
}
//************************************
// Method: fi
// FullName: cube::fi
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the front face counter clockwise
//************************************
void cube::fi()
{
front.rotate_counter_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[cube_size -1][cube_size -1 - index];
up.square[cube_size - 1][cube_size - 1 - index] = right.square[cube_size - 1 - index][0];
right.square[cube_size - 1 - index][0] = down.square[0][index];
down.square[0][index] = left.square[index][cube_size -1];
left.square[index][cube_size - 1] = temp;
}
if (record_)
moves_ += "Fi ";
}
//************************************
// Method: u
// FullName: cube::u
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the up face clockwise
//************************************
void cube::u()
{
up.rotate_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = front.square[0][index];
front.square[0][index] = right.square[0][index];
right.square[0][index] = back.square[0][index];
back.square[0][index] = left.square[0][index];
left.square[0][index] = temp;
}
if (record_)
moves_ += "U ";
}
//************************************
// Method: ui
// FullName: cube::ui
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the up face counter clockwise
//************************************
void cube::ui()
{
up.rotate_counter_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = front.square[0][index];
front.square[0][index] = left.square[0][index];
left.square[0][index] = back.square[0][index];
back.square[0][index] = right.square[0][index];
right.square[0][index] = temp;
}
if (record_)
moves_ += "Ui ";
}
//************************************
// Method: b
// FullName: cube::b
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the back face clockwise
//************************************
void cube::b()
{
back.rotate_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[0][index];
up.square[0][index] = right.square[index][cube_size - 1];
right.square[index][cube_size - 1] = down.square[cube_size - 1][cube_size - 1 - index];
down.square[cube_size - 1][cube_size - 1 - index] = left.square[cube_size - 1 - index][0];
left.square[cube_size - 1 - index][0] = temp;
}
if (record_)
moves_ += "B ";
}
//************************************
// Method: bi
// FullName: cube::bi
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the back face counter clockwise
//************************************
void cube::bi()
{
back.rotate_counter_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[0][index];
up.square[0][index] = left.square[cube_size -1 - index][0];
left.square[cube_size - 1 - index][0] = down.square[cube_size - 1][cube_size - 1 - index];
down.square[cube_size - 1][cube_size - 1 - index] = right.square[index][cube_size - 1];
right.square[index][cube_size - 1] = temp;
}
if (record_)
moves_ += "Bi ";
}
//************************************
// Method: l
// FullName: cube::l
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the left face clockwise
//************************************
void cube::l()
{
left.rotate_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[index][0];
up.square[index][0] = back.square[cube_size - 1 - index][cube_size - 1];
back.square[cube_size - 1 - index][cube_size - 1] = down.square[index][0];
down.square[index][0] = front.square[index][0];
front.square[index][0] = temp;
}
if (record_)
moves_ += "L ";
}
//************************************
// Method: li
// FullName: cube::li
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the left face counter clockwise
//************************************
void cube::li()
{
left.rotate_counter_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[index][0];
up.square[index][0] = front.square[index][0];
front.square[index][0] = down.square[index][0];
down.square[index][0] = back.square[cube_size - 1 - index][cube_size - 1];
back.square[cube_size - 1 - index][cube_size - 1] = temp;
}
if (record_)
moves_ += "Li ";
}
//************************************
// Method: r
// FullName: cube::r
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the right face clockwise
//************************************
void cube::r()
{
right.rotate_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[index][cube_size - 1];
up.square[index][cube_size - 1] = front.square[index][cube_size - 1];
front.square[index][cube_size - 1] = down.square[index][cube_size - 1];
down.square[index][cube_size - 1] = back.square[cube_size - 1 - index][0];
back.square[cube_size - 1 - index][0] = temp;
}
if (record_)
moves_ += "R ";
}
//************************************
// Method: ri
// FullName: cube::ri
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the right face counter clockwise
//************************************
void cube::ri()
{
right.rotate_counter_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[cube_size - 1 - index][cube_size - 1];
up.square[cube_size - 1 - index][cube_size - 1] = back.square[index][0];
back.square[index][0] = down.square[cube_size - 1 - index][cube_size - 1];
down.square[cube_size - 1 - index][cube_size - 1] = front.square[cube_size - 1 - index][cube_size - 1];
front.square[cube_size - 1 - index][cube_size - 1] = temp;
}
if (record_)
moves_ += "Ri ";
}
//************************************
// Method: d
// FullName: cube::d
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the down face clockwise
//************************************
void cube::d()
{
down.rotate_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = front.square[cube_size -1][index];
front.square[cube_size - 1][index] = left.square[cube_size - 1][index];
left.square[cube_size - 1][index] = back.square[cube_size - 1][index];
back.square[cube_size - 1][index] = right.square[cube_size - 1][index];
right.square[cube_size - 1][index] = temp;
}
if (record_)
moves_ += "D ";
}
//************************************
// Method: di
// FullName: cube::di
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the down face counter clockwise
//************************************
void cube::di()
{
down.rotate_counter_clockwise();
for (auto index = 0; index < cube_size; index++)
{
const auto temp = front.square[cube_size - 1][index];
front.square[cube_size - 1][index] = right.square[cube_size - 1][index];
right.square[cube_size - 1][index] = back.square[cube_size - 1][index];
back.square[cube_size - 1][index] = left.square[cube_size - 1][index];
left.square[cube_size - 1][index] = temp;
}
if (record_)
moves_ += "Di ";
}
//************************************
// Method: us
// FullName: cube::us
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube up slice clockwise
//************************************
void cube::us()
{
for (auto col = 0; col < cube_size; col++)
{
const auto temp = front.square[1][col];
front.square[1][col] = right.square[1][col];
right.square[1][col] = back.square[1][col];
back.square[1][col] = left.square[1][col];
left.square[1][col] = temp;
}
if (record_)
moves_ += "Us ";
}
//************************************
// Method: ds
// FullName: cube::ds
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube down slice clockwise
//************************************
void cube::ds()
{
for (auto col = 0; col < cube_size; col++)
{
const auto temp = front.square[1][col];
front.square[1][col] = left.square[1][col];
left.square[1][col] = back.square[1][col];
back.square[1][col] = right.square[1][col];
right.square[1][col] = temp;
}
if (record_)
moves_ += "Ds ";
}
//************************************
// Method: ls
// FullName: cube::ls
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube left slice clockwise
//************************************
void cube::ls()
{
for (auto row = 0; row < cube_size; row++)
{
const auto temp = up.square[row][1];
up.square[row][1] = back.square[cube_size - row - 1][1];
back.square[cube_size - row - 1][1] = down.square[row][1];
down.square[row][1] = front.square[row][1];
front.square[row][1] = temp;
}
if (record_)
moves_ += "Ls ";
}
//************************************
// Method: rs
// FullName: cube::rs
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube right slice clockwise
//************************************
void cube::rs()
{
for (auto row = 0; row < cube_size; row++)
{
const auto temp = up.square[row][1];
up.square[row][1] = front.square[row][1];
front.square[row][1] = down.square[row][1];
down.square[row][1] = back.square[cube_size - row - 1][1];
back.square[cube_size - row - 1][1] = temp;
}
if (record_)
moves_ += "Rs ";
}
//************************************
// Method: fs
// FullName: cube::fs
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube front slice clockwise
//************************************
void cube::fs()
{
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[1][index];
up.square[1][index] = left.square[cube_size - index - 1][1];
left.square[cube_size - index - 1][1] = down.square[1][cube_size - index -1];
down.square[1][cube_size - index -1] = right.square[index][1];
right.square[index][1] = temp;
}
if (record_)
moves_ += "Fs ";
}
//************************************
// Method: bs
// FullName: cube::bs
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube back slice clockwise
//************************************
void cube::bs()
{
for (auto index = 0; index < cube_size; index++)
{
const auto temp = up.square[1][index];
up.square[1][index] = right.square[index][1];
right.square[index][1] = down.square[1][cube_size - index - 1];
down.square[1][cube_size - index - 1] = left.square[cube_size - index - 1][1];
left.square[cube_size - index - 1][1] = temp;
}
if (record_)
moves_ += "Bs ";
}
//************************************
// Method: cu
// FullName: cube::cu
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube up
//************************************
void cube::cu()
{
left.rotate_counter_clockwise();
right.rotate_clockwise();
for (auto row = 0; row < cube_size; row++)
for (auto col = 0; col < cube_size; col++)
{
const auto temp = up.square[row][col];
up.square[row][col] = front.square[row][col];
front.square[row][col] = down.square[row][col];
down.square[row][col] = back.square[cube_size - 1 - row][cube_size - 1 - col];
back.square[cube_size - 1 - row][cube_size - 1 - col] = temp;
}
if (record_)
moves_ += "Cu ";
}
//************************************
// Method: cd
// FullName: cube::cd
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube down
//************************************
void cube::cd()
{
left.rotate_clockwise();
right.rotate_counter_clockwise();
for (auto row = 0; row < cube_size; row++)
for (auto col = 0; col < cube_size; col++)
{
const auto temp = down.square[row][col];
down.square[row][col] = front.square[row][col];
front.square[row][col] = up.square[row][col];
up.square[row][col] = back.square[cube_size - 1 - row][cube_size - 1 - col];
back.square[cube_size - 1 - row][cube_size - 1 - col] = temp;
}
if (record_)
moves_ += "Cd ";
}
//************************************
// Method: cl
// FullName: cube::cl
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube left
//************************************
void cube::cl()
{
down.rotate_counter_clockwise();
up.rotate_clockwise();
for (auto row = 0; row < cube_size; row++)
for (auto col = 0; col < cube_size; col++)
{
const auto temp = front.square[row][col];
front.square[row][col] = right.square[row][col];
right.square[row][col] = back.square[row][col];
back.square[row][col] = left.square[row][col];
left.square[row][col] = temp;
}
if (record_)
moves_ += "Cl ";
}
//************************************
// Method: cr
// FullName: cube::cr
// Access: public
// Returns: void
// Qualifier:
//
// Rotate the cube face_right
//************************************
void cube::cr()
{
down.rotate_clockwise();
up.rotate_counter_clockwise();
for (auto row = 0; row < cube_size; row++)
for (auto col = 0; col < cube_size; col++)
{
const auto temp = front.square[row][col];
front.square[row][col] = left.square[row][col];
left.square[row][col] = back.square[row][col];
back.square[row][col] = right.square[row][col];
right.square[row][col] = temp;
}
if (record_)
moves_ += "Cr ";
}
//************************************
// Method: reverse_sequence
// FullName: cube::reverse_sequence
// Access: public static
// Returns: void
// Qualifier: const
// Parameter: const char * sequence
// Parameter: char * buffer
// Parameter: size_t * sz
//
// Create an inverse to a sequence
//************************************
void cube::reverse_sequence(const char* sequence, char* buffer, size_t* sz) const
{
std::string result;
reverse_sequence(sequence, result);
if (buffer != nullptr && *sz >= result.length())
strcpy(buffer, result.c_str());
if (sz != nullptr) *sz = result.length();
}
//************************************
// Method: reverse_sequence
// FullName: cube::reverse_sequence
// Access: public static
// Returns: void
// Qualifier:
// Parameter: const std::string & sequence
// Parameter: std::string & out
//
// Create an inverse to a sequence
//************************************
void cube::reverse_sequence(const std::string& sequence, std::string& out)
{
std::string buffer;
const std::string white = "\t\n\r\v\f ";
std::vector<std::string> strs;
split(sequence, white, strs);
for (auto str : strs)
{
auto lowerstr = lower(str);
if (buffer.length() > 0)
buffer.insert(buffer.begin(), ' ');
if (lowerstr == "u")
{
buffer.insert(buffer.begin(), 'i');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "ui")
{
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "l")
{
buffer.insert(buffer.begin(), 'i');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "li")
{
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "f")
{
buffer.insert(buffer.begin(), 'i');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "fi")
{
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "r")
{
buffer.insert(buffer.begin(), 'i');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "ri")
{
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "b")
{
buffer.insert(buffer.begin(), 'i');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "bi")
{
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "d")
{
buffer.insert(buffer.begin(), 'i');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "di")
{
buffer.insert(buffer.begin(), 'd');
}
else if (lowerstr == "us")
{
buffer.insert(buffer.begin(), str[1]);
buffer.insert(buffer.begin(), 'D');
}
else if (lowerstr == "ds")
{
buffer.insert(buffer.begin(), str[1]);
buffer.insert(buffer.begin(), 'U');
}
else if (lowerstr == "ls")
{
buffer.insert(buffer.begin(), str[1]);
buffer.insert(buffer.begin(), 'R');
}
else if (lowerstr == "rs")
{
buffer.insert(buffer.begin(), str[1]);
buffer.insert(buffer.begin(), 'L');
}
else if (lowerstr == "fs")
{
buffer.insert(buffer.begin(), str[1]);
buffer.insert(buffer.begin(), 'B');
}
else if (lowerstr == "bs")
{
buffer.insert(buffer.begin(), str[1]);
buffer.insert(buffer.begin(), 'F');
}
else if (lowerstr == "cu")
{
buffer.insert(buffer.begin(), 'd');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "cd")
{
buffer.insert(buffer.begin(), 'u');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "cl")
{
buffer.insert(buffer.begin(), 'r');
buffer.insert(buffer.begin(), str[0]);
}
else if (lowerstr == "cr")
{
buffer.insert(buffer.begin(), 'l');
buffer.insert(buffer.begin(), str[0]);
}
}
optimize_sequence(buffer, out);
}
//************************************
// Method: execute_move
// FullName: cube::execute_move
// Access: public
// Returns: void
// Qualifier:
// Parameter: const char * move
//
// Perform a single move
//************************************
void cube::execute_move(const char* move)
{
if (iequals(move, "u")) u();
else if (iequals(move, "ui")) ui();
else if (iequals(move, "d")) d();
else if (iequals(move, "di")) di();
else if (iequals(move, "l")) l();
else if (iequals(move, "li")) li();
else if (iequals(move, "r")) r();
else if (iequals(move, "ri")) ri();
else if (iequals(move, "f")) f();
else if (iequals(move, "fi")) fi();
else if (iequals(move, "b")) b();
else if (iequals(move, "bi")) bi();
else if (iequals(move, "us")) us();
else if (iequals(move, "ds")) ds();
else if (iequals(move, "rs")) rs();
else if (iequals(move, "ls")) ls();
else if (iequals(move, "fs")) fs();
else if (iequals(move, "bs")) bs();
else if (iequals(move, "cu")) cu();
else if (iequals(move, "cd")) cd();
else if (iequals(move, "cl")) cl();
else if (iequals(move, "cr")) cr();
}
//************************************
// Method: execute_move
// FullName: cube::execute_move
// Access: public
// Returns: void
// Qualifier:
// Parameter: const std::string & move
//
// Perform a single move
//************************************
void cube::execute_move(const std::string& move)
{
execute_move(move.c_str());
}
//************************************
// Method: execute_sequence
// FullName: cube::execute_sequence
// Access: public
// Returns: void
// Qualifier:
// Parameter: const char * sequence
//
// Execute a move sequence
//************************************
void cube::execute_sequence(const char* sequence)
{
const std::string seq = sequence;
execute_sequence(seq);
}
//************************************
// Method: execute_sequence
// FullName: cube::execute_sequence
// Access: public
// Returns: void
// Qualifier:
// Parameter: const std::string & sequence
//
// Execute a move sequence
//************************************
void cube::execute_sequence(const std::string& sequence)
{
if (sequence.length() == 0) return;
std::vector<std::string> tokens;
split(sequence, whitechars, tokens);
execute_sequence(tokens);
}
//************************************
// Method: execute_sequence
// FullName: cube::execute_sequence
// Access: public
// Returns: void
// Qualifier:
// Parameter: const std::vector<std::string> & tokens
//************************************
void cube::execute_sequence(const std::vector<std::string>& tokens)
{
for (const auto &token : tokens)
execute_move(token);
}
//************************************
// Method: scramble_cube
// FullName: cube::scramble_cube
// Access: public
// Returns: void
// Qualifier:
// Parameter: const int scramble_count
//
// Scramble the cube
//************************************
void cube::scramble_cube(const int scramble_count = 1000)
{
const auto temp = record_;
record_ = false;
const auto count = scramble_count;
const auto num_moves = 18;
static const std::string directions[num_moves] =
{
"U", "Ui", "D", "Di", "L", "Li", "R", "Ri", "B", "Bi", "F", "Fi",
"Us", "Ds", "Ls", "Rs", "Fs", "Bs"
};
std::string sequence;
for (auto scrambleloop = 0; scrambleloop < count; scrambleloop++)
{
const auto rnd = rand() % num_moves;
sequence += directions[rnd] + ' ';
}
optimize_sequence(sequence, scramble_sequence_);
execute_sequence(scramble_sequence_);
record_ = temp;
}
//************************************
// Method: get_optimized_moves
// FullName: cube::get_optimized_moves
// Access: public
// Returns: void
// Qualifier: const
// Parameter: std::string & moves
//
// get the optimized moves as a string
//************************************
void cube::get_optimized_moves(std::string& moves) const
{
optimize_sequence(moves_, moves);
}
//************************************
// Method: get_moves
// FullName: cube::get_moves
// Access: public
// Returns: void
// Qualifier: const
// Parameter: std::string & moves
//
// get the moves as a string
//************************************
void cube::get_moves(std::string& moves) const
{
moves = moves_;
trim(moves);
}
//************************************
// Method: get_scramble_sequence
// FullName: cube::get_scramble_sequence
// Access: public
// Returns: void
// Qualifier: const
// Parameter: std::string & scramble_sequence
//
// get the scramble sequence as a string
//************************************
void cube::get_scramble_sequence(std::string& scramble_sequence) const
{
scramble_sequence = scramble_sequence_;
}
//************************************
// Method: get_moves
// FullName: cube::get_moves
// Access: public
// Returns: void
// Qualifier: const
// Parameter: char * buffer
// Parameter: size_t * sz
//
// get the moves as a c string
//************************************
void cube::get_moves(char* buffer, size_t* sz) const
{
std::string moves;
get_moves(moves);
if (buffer != nullptr && *sz > moves.length())
strcpy(buffer, moves.c_str());
if (sz != nullptr)
*sz = moves_.length() + 1;
}
//************************************
// Method: get_optimized_moves
// FullName: cube::get_optimized_moves
// Access: public
// Returns: void
// Qualifier: const
// Parameter: char * buffer
// Parameter: size_t * sz
//
// get the moves made as a string that are optimized
//************************************
void cube::get_optimized_moves(char* buffer, size_t* sz) const
{
std::string moves;
get_optimized_moves(moves);
if (buffer != nullptr && *sz > moves.length())
strcpy(buffer, moves.c_str());
if (sz != nullptr)
*sz = moves_.length() + 1;
}
//************************************
// Method: get_scramble_sequence
// FullName: cube::get_scramble_sequence
// Access: public
// Returns: void
// Qualifier: const
// Parameter: char * buffer
// Parameter: size_t * sz
//
// get the scramble sequence
//************************************
void cube::get_scramble_sequence(char* buffer, size_t* sz) const
{
std::string scramble_sequence;
get_scramble_sequence(scramble_sequence);
if (buffer != nullptr && *sz > scramble_sequence.length())
strcpy(buffer, scramble_sequence.c_str());
if (sz != nullptr)
*sz = scramble_sequence_.length() + 1;
}
//************************************
// Method: optimize_sequence
// FullName: cube::optimize_sequence
// Access: public static
// Returns: void
// Qualifier:
// Parameter: const std::string & sequence
// Parameter: std::string & out
//
// optimize a sequence
//************************************
void cube::optimize_sequence(const std::string& sequence, std::string& out)
{
auto temp = sequence;
size_t len1;
size_t len2;
do
{
optimize_sequence_recursion(temp, out);
len1 = temp.length();
len2 = out.length();
temp = out;
} while (len2 < len1);
}
//************************************
// Method: optimize_sequence_recursion
// FullName: cube::optimize_sequence_recursion
// Access: private static
// Returns: void
// Qualifier:
// Parameter: const std::string & sequence
// Parameter: std::string & out
//
// optimize a sequence
//
// The basic algorithm is to track
// how many turns there are in a given direction
// and opposite direction while keeping track of which moves can be ignored.
// Optimize the ignored moves via recursion
//************************************
void cube::optimize_sequence_recursion(const std::string& sequence, std::string& out)
{
out.clear();
const std::string end_marker = "****";
std::vector<std::string>tokens;
const std::string white = "\t\n\r\v\f ";
split(sequence, white, tokens);
tokens.emplace_back(end_marker);
auto index = 0u;
auto count = 0;
std::vector<std::string> ignore;
std::vector<std::string> add;
std::vector<std::string> subtract;
std::string search;
std::string ig_string;
std::string add_string;
std::string subtract_string;
// loop through all tokens
while (index < tokens.size())
{
// get the current token
auto tok = lower(tokens[index++]);
// new sequence
// set add subtract and ignore vectors
if (search.length() == 0)
{
count = 0;
search = tok;
ignore.clear();
add.clear();
subtract.clear();
ig_string.clear();
search = tok;
add_string.clear();
subtract_string.clear();
// left and left inverse
if (tok == "l" || tok == "li")
{
add.emplace_back("l");
subtract.emplace_back("li");
ignore.emplace_back("r");
ignore.emplace_back("ri");
ignore.emplace_back("ls");
ignore.emplace_back("rs");
add_string = "L";
subtract_string = "Li";
}
// right and right inverse
else if (tok == "r" || tok == "ri")
{
add.emplace_back("r");
subtract.emplace_back("ri");
ignore.emplace_back("l");
ignore.emplace_back("li");
ignore.emplace_back("ls");
ignore.emplace_back("rs");
add_string = "R";
subtract_string = "Ri";
}
// front and front inverse
else if (tok == "f" || tok == "fi")
{
add.emplace_back("f");
subtract.emplace_back("fi");
ignore.emplace_back("b");
ignore.emplace_back("bi");
ignore.emplace_back("fs");
ignore.emplace_back("bs");
add_string = "F";
subtract_string = "Fi";
}
// back and back inverse
else if (tok == "b" || tok == "bi")
{
add.emplace_back("b");
subtract.emplace_back("bi");
ignore.emplace_back("f");
ignore.emplace_back("fi");
ignore.emplace_back("fs");
ignore.emplace_back("bs");
add_string = "B";
subtract_string = "Bi";
}
// up and up inverse
else if (tok == "u" || tok == "ui")
{
add.emplace_back("u");
subtract.emplace_back("ui");
ignore.emplace_back("d");
ignore.emplace_back("di");
ignore.emplace_back("us");
ignore.emplace_back("ds");
add_string = "U";
subtract_string = "Ui";
}
// down and down inverse
else if (tok == "d" || tok == "di")
{
add.emplace_back("d");
subtract.emplace_back("di");
ignore.emplace_back("u");
ignore.emplace_back("ui");
ignore.emplace_back("us");
ignore.emplace_back("ds");
add_string = "D";
subtract_string = "Di";
}
// cube up and cube down
else if (tok == "cu" || tok == "cd")
{
add.emplace_back("cu");
subtract.emplace_back("cd");
add_string = "Cu";
subtract_string = "Cd";
}
// cube left and cube right
else if (tok == "cl" || tok == "cr")
{
add.emplace_back("cl");
subtract.emplace_back("cr");
add_string = "Cl";
subtract_string = "Cr";
}
// up slice, up slice inverse, down slice and down slice inverse
else if (tok == "us" || tok == "ds")
{
add.emplace_back("us");
subtract.emplace_back("ds");
ignore.emplace_back("u");
ignore.emplace_back("ui");
ignore.emplace_back("d");
ignore.emplace_back("di");
add_string = "Us";
subtract_string = "Ds";
}
// left slice, left slice inverse, right slice and right slice inverse
else if (tok == "ls" || tok == "rs")
{
add.emplace_back("ls");
subtract.emplace_back("rs");
ignore.emplace_back("l");
ignore.emplace_back("li");
ignore.emplace_back("r");
ignore.emplace_back("ri");
add_string = "Ls";
subtract_string = "Rs";
}
// front slice, front slice inverse, back slice and back slice inverse
else if (tok == "fs" || tok == "bs")
{
add.emplace_back("fs");
subtract.emplace_back("bs");
ignore.emplace_back("f");
ignore.emplace_back("fi");
ignore.emplace_back("b");
ignore.emplace_back("bi");
add_string = "Fs";
subtract_string = "Bs";
}
else // if (tok == end_marker)
{
add.emplace_back(tok);
}
}
// At this point add, subtract and ignore vectors are set
// add
auto found = false;
for (const auto& a : add)
{
if (tok == a)
{
count++;
found = true;
break;
}
}
// subtract
if (!found)
for (const auto& s : subtract)
{
if (tok == s)
{
count--;
found = true;
break;
}
}
// ignore
if (!found)
for (const auto& i : ignore)
{
if (tok == i)
{
ig_string += ' ' + tok;
found = true;
break;
}
}
// check for end of sequence
if (!found)
{
// recurse over ignore string
if (ig_string.length() > 0)
{
std::string opt;
optimize_sequence_recursion(ig_string, opt);
if (opt.length() > 0)
out += ' ' + opt;
}
// the numbers of moves in any direction must be mod 4
count %= 4;
if (count > 0)
{
switch (count)
{
case 1:
out += ' ' + add_string;
break;
case 2:
out += ' ' + add_string;
out += ' ' + add_string;
break;
case 3: // 3 add == 1 substract
out += ' ' + subtract_string;
break;
default:
break;
}
}
else if (count < 0)
{
switch (count)
{
case -1:
out += ' ' + subtract_string;
break;
case -2: // 2 subtracts == 2 adds for simplicity
out += ' ' + add_string;
out += ' ' + add_string;
break;
case -3: // 3 subtracts == 1 add
out += ' ' + add_string;
break;
default:
break;
}
}
// trigger a new sequence by clearing it
search.clear();
// move 1 token backwards
index--;
}
}
trim(out);
}
//************************************
// Method: optimize_sequence
// FullName: cube::optimize_sequence
// Access: public static
// Returns: void
// Qualifier: const
// Parameter: const char * sequence
// Parameter: char * buffer
// Parameter: size_t * sz
//
// optimize a sequence
//************************************
void cube::optimize_sequence(const char* sequence, char* buffer, size_t* sz) const
{
std::string out;
optimize_sequence(sequence, out);
if (buffer != nullptr && *sz > out.length())
strcpy(buffer, out.c_str());
if (sz != nullptr)
*sz = out.length() + 1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T19:55:58.680",
"Id": "480986",
"Score": "0",
"body": "I omitted face.cpp and headers due to size."
}
] |
[
{
"body": "<h2>Literal initialization of vector</h2>\n<pre><code>static const vector<face_val<face_val_type>> init = {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};\n</code></pre>\n<p>seems like something a computer should be able to do. Indeed, <a href=\"https://en.cppreference.com/w/cpp/algorithm/iota\" rel=\"nofollow noreferrer\"><code>iota</code></a> seems capable.</p>\n<h2>Return values</h2>\n<p>In a language with exception handling, this:</p>\n<pre><code>auto result = check_parameter(args, "-c", cubestring);\nif (result < 0) return result;\n\nresult = check_parameter(args, "-slice", slice);\nif (result < 0) return result;\n\nresult = check_parameter(args, "-f", filename);\nif (result < 0) return result;\n\nresult = check_parameter(args, "-depth", maxdepth);\nif (result < 0) return result;\n</code></pre>\n<p>seems like it should not use return codes, and should use exceptions instead.</p>\n<h2><code>// This is a comment</code></h2>\n<pre><code>// Method: parse_args\n// FullName: parse_args\n// Access: public \n// Returns: int\n// Qualifier:\n// Parameter: const int argc\n// Parameter: char * * argv\n</code></pre>\n<p>is worse than having no comment at all. You should document what the <code>int</code> actually means.</p>\n<h2>stderr</h2>\n<pre><code> cout << "Unknown argument(s) ";\n</code></pre>\n<p>seems like it should use <code>cerr</code>.</p>\n<h2>Returning strings</h2>\n<p>Currently, something like <code>cubestring</code>:</p>\n<ul>\n<li>Is constructed once, with an empty value, in <code>parse_args</code> <code>string cubestring;</code></li>\n<li>Is constructed a second time with an actual value, in <code>args.emplace_back</code></li>\n<li>Is copy-constructed a <em>third</em> time, on <code>var = args[argindex];</code></li>\n</ul>\n<p>This is not great. I think you can reduce it by:</p>\n<ul>\n<li>Not pre-declaring <code>string cubestring;</code></li>\n<li>Not accepting a mutable reference in <code>check_parameter</code></li>\n<li>Not returning an integer from <code>check_parameter</code></li>\n<li>Returning a <code>const string &</code> from <code>check_parameter</code></li>\n<li>Immediately assigning that returned reference to <code>const string &cubestring = check_parameter(...</code></li>\n</ul>\n<p>Also note that you should be able to pass <code>argv</code> directly to the <code>vector</code> constructor <a href=\"https://www.cplusplus.com/reference/vector/vector/vector/\" rel=\"nofollow noreferrer\">without a loop</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T19:19:45.510",
"Id": "481275",
"Score": "0",
"body": "FYI the comments for methods was auto generated and I will add to them"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T17:40:40.953",
"Id": "245093",
"ParentId": "244974",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245093",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T19:55:02.450",
"Id": "244974",
"Score": "3",
"Tags": [
"c++"
],
"Title": "c++ program to help find move sequences to solve Rubiks cubes"
}
|
244974
|
<p>I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!</p>
<h3>Problem</h3>
<blockquote>
<ul>
<li>Return the length of the shortest, non-empty, contiguous subarray of <code>nums</code> with sum at least <code>k</code>.</li>
<li>If there is no non-empty subarray with sum at least k, return -1.</li>
</ul>
<h3>Example 1:</h3>
<p>Input: nums = [1], k = 1 Output: 1</p>
<h3>Example 2:</h3>
<p>Input: nums = [1,2], k = 4 Output: -1</p>
<h3>Example 3:</h3>
<p>Input: nums = [2,-1,2], k = 3 Output: 3</p>
<h3>Note:</h3>
<ul>
<li><span class="math-container">\$1 <= \text{nums.length} <= 50000\$</span></li>
<li><span class="math-container">\$-10 ^ 5 <= \text{nums}[i] <= 10 ^ 5\$</span></li>
<li><span class="math-container">\$1 <= k <= 10 ^ 9\$</span></li>
</ul>
</blockquote>
<h3>Code</h3>
<pre><code>#include <vector>
#include <algorithm>
#include <deque>
class Solution {
public:
static int shortestSubarray(std::vector<int> nums, const int k) {
const int length = nums.size();
int shortest = length + 1;
std::deque<int> deque_indicies;
for (int index = 0; index < length; index++) {
if (index) {
nums[index] += nums[index - 1];
}
if (nums[index] >= k) {
shortest = std::min(shortest, index + 1);
}
while (!deque_indicies.empty() && nums[index] - nums[deque_indicies.front()] >= k) {
shortest = std::min(shortest, index - deque_indicies.front());
deque_indicies.pop_front();
}
while (!deque_indicies.empty() && nums[index] <= nums[deque_indicies.back()]) {
deque_indicies.pop_back();
}
deque_indicies.emplace_back(index);
}
return shortest <= length ? shortest : -1;
}
};
</code></pre>
<ul>
<li><p><a href="https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/solution/" rel="nofollow noreferrer">Solution</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h2>Passing by reference or value</h2>\n<p>Currently,</p>\n<pre><code>std::vector<int> nums\n</code></pre>\n<p>forces callers to pass a copy of the entire vector by value. You could argue that this is actually useful, since your algorithm needs to mutate it (or a copy of it) in-place. My preference is usually to make this copy-step explicit instead:</p>\n<ul>\n<li>Pass a <code>const &</code> reference, not a mutable copy</li>\n<li>Make a local copy of the vector explicitly, invoking the copy constructor</li>\n<li>Mutate your copy.</li>\n</ul>\n<h2>Spelling</h2>\n<p><code>deque_indicies</code> -> <code>deque_indices</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T13:58:41.193",
"Id": "244998",
"ParentId": "244976",
"Score": "2"
}
},
{
"body": "<p>This is not a proper review. I just want to show an argument why passign the input by value is actually more useful then passing it by const reference, in this particular case.</p>\n<p>Yes, it's true you should not modify the input for the caller, because he didnt ask you to do so.</p>\n<p>But it is also true, that your implementation takes advantage of the ability to modify the input.</p>\n<p>As @Reinderien proposed, if you pass it by reference and create a copy inside your function you satisfy both the caller (who doesnt want his input changed) and the implementation (who wants to change the input so it can do its job effectively).</p>\n<pre><code>int solution(const vector<int> & input)\n{\n vector<int> inputClone = input;\n\n // do the thing mutating inputClone\n\n return result;\n}\n</code></pre>\n<p>But if you passed it by value, you actually satisfy both too and you get a shorter code.</p>\n<pre><code>int solution(vector<int> input)\n{\n // do the thing mutating input which already is a clone\n\n return result;\n}\n</code></pre>\n<p>What make the pass-by-value approach even better is the fact that now you are allowing the caller to have its input vector mutated, if he doesn't need it after the function is called.</p>\n<p>if caller wants immutable input he calls the function directly:</p>\n<pre><code>int result = solution(input);\n\n// here input is unchanged and I can work with it\n</code></pre>\n<p>if caller does not care if the input changes he can <code>std::move</code> it into the function:</p>\n<pre><code>int result = solution(std::move(input));\n\n// here input is probably changed, but I don't intend to touch it here anymore anyway\n</code></pre>\n<p>This cannot be done with const reference. If you make it accept const reference, the code is doomed to always create a copy, regardless of the caller requiring it.</p>\n<p>So yes pass by const reference is generaly prefered, but when the function needs to copy the input so it can modify it so it can work efficiently and not mutate input for caller, use pass by value and let caller decide if he wants it to work with a copy or move the input to the function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T09:02:16.387",
"Id": "245025",
"ParentId": "244976",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "244998",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T20:45:47.413",
"Id": "244976",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 862: Shortest Subarray with Sum at Least K"
}
|
244976
|
<p>I have an object with three possible properties:</p>
<pre><code>consistencySelector = {
transaction: "kkjk4k45kjlkf";
newTransaction: {};
readTime: "sometime";
}
</code></pre>
<p>I would like only one property to be present at any time using the following definitions:</p>
<pre><code>interface Transaction {
transaction: string;
newTransaction: never;
readTime: never;
}
interface NewTransaction {
newTransaction: object;
readTime?: never;
transaction?: never;
}
interface ReadTime {
readTime: string;
transaction?: never;
newTransaction?: never;
}
type consistencySelector = Transaction | NewTransaction | ReadTime;
</code></pre>
<p>Must I make optional <code>never</code> properties for every branch or is there a more elegant way to achieve the same result? for instance if <code>consistencySelector</code> had 20 properties</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T05:55:12.810",
"Id": "481015",
"Score": "2",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>No you don't use 'never' rather you don't include properties that aren't relevant at all.</p>\n<pre><code>interface Transaction {\n transaction: string;\n}\n\ninterface NewTransaction {\n newTransaction: object;\n}\n\ninterface ReadTime {\n readTime: string;\n}\n\ntype consistencySelector = Transaction | NewTransaction | ReadTime;\n\ncs: consistencySelector = {\n transaction: "kkjk4k45kjlkf";\n newTransaction: {};\n readTime: "sometime";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T23:05:37.977",
"Id": "244980",
"ParentId": "244977",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:48:25.360",
"Id": "244977",
"Score": "-3",
"Tags": [
"typescript"
],
"Title": "Typescript interface union with different properties"
}
|
244977
|
<h1>Problem Statement</h1>
<p>You are receiving n objects in a random order, and you need to print them to stdout correctly ordered by sequence number.</p>
<p>The sequence numbers start from 0 (zero) and you have to wait until you get a complete, unbroken sequence batch of j objects before you output them.</p>
<p>You have to process all objects without loss. The program should exit once it completes outputting the first 50000 objects Batch size j = 100</p>
<p>The object is defined as such:</p>
<pre><code> {
"id" : "object_id", // object ID (string)
"seq" : 0, // object sequence number (int64, 0-49999)
"data" : "" // []bytes
}
</code></pre>
<h1>Example Output Statement</h1>
<pre><code> Step Input Value Output State j = 1 Output state j = 3
0 6
1 0 0
2 4 0
3 2 0
4 1 0,1,2 0,1,2
5 3 0,1,2,3,4 0,1,2
6 9 0,1,2,3,4 0,1,2
7 5 0,1,2,3,4,5,6 0,1,2,3,4,5
</code></pre>
<hr />
<h1>Solution</h1>
<pre><code>func (receiver *Receiver) Print(seqNumber uint64, batchSize uint64, outputFile io.Writer) (error, bool) {
fmt.Fprintf(outputFile, "[ ")
if seqNumber >= receiver.outputSequence.length {
receiver.outputSequence.bufferSizeIncrease(seqNumber)
}
receiver.outputSequence.sequence[seqNumber] = true
printedCount := uint64(0) // check for MAX_OBJECTS_TO_PRINT
var nthBatchStartingIndex uint64
MaxObjectsToPrint := config.GetMaxPrintSize()
Loop:
for nthBatchStartingIndex < receiver.outputSequence.length { // check unbroken sequence
var assessIndex = nthBatchStartingIndex
for j := assessIndex; j < nthBatchStartingIndex+batchSize; j++ { // Assess nth batch
if j >= receiver.outputSequence.length { //index out of range - edge case
break Loop
}
if receiver.outputSequence.sequence[j] == false {
break Loop
}
}
count, printThresholdReached := receiver.printAssessedBatchIndexes(assessIndex, printedCount, batchSize, MaxObjectsToPrint, outputFile)
if printThresholdReached { // print sequence threshold reached MAX_OBJECTS_TO_PRINT
fmt.Fprintf(outputFile, " ] ")
fmt.Fprintf(outputFile, " ----for input value %d\n", seqNumber)
return nil, false
}
printedCount += count
if printedCount >= MaxObjectsToPrint { // print sequence threshold reached MAX_OBJECTS_TO_PRINT
fmt.Fprintf(outputFile, " ] ")
fmt.Fprintf(outputFile, " ----for input value %d\n", seqNumber)
receiver.Log.Printf("****MaxObjectsToPrint threshold(%d) reached \n", MaxObjectsToPrint)
return nil, false
}
nthBatchStartingIndex = assessIndex + batchSize // next batch
}
fmt.Fprintf(outputFile, " ] ")
fmt.Fprintf(outputFile, " ----for input value %d\n", seqNumber)
return nil, true
}
</code></pre>
<hr />
<p><a href="https://github.com/shamhub/threadapp" rel="nofollow noreferrer">Here</a> is the complete solution, written for this problem.</p>
<hr />
<p><code>Print()</code> is the method that does heavy lifting in this code, with varying size of memory & heavy CPU usage:</p>
<ol>
<li><p>How to make <code>receiver.outputSequence</code> memory effective by using datastructure other than array? because <code>newBufferSize := 2 * seqNumber</code> is doubling memory...</p>
</li>
<li><p>How to make <code>Print</code> method have effective CPU usage? On some goroutine</p>
</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T05:04:43.277",
"Id": "481013",
"Score": "0",
"body": "What does \"batch size j=100\" mean? Does it mean you will never receive out-of-sequence entries farther than 100? If so, you can do this with a fixed size array of 100. If that's not the case, you might want to try putting the elements in a map instead of an array. No matter the solution, you have to remember max(distance between out of sequence elements). With a slice, you have to move them as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T05:56:52.143",
"Id": "481016",
"Score": "0",
"body": "@BurakSerdar batch size j = 3 mean {0,1,2} {3,4,5}....batch size j = 2 mean {0,1} {2,3} {4,5}... So, batch size j=100 mean, once we have 100 unbroken sequence {0.1.2.3.4.5,.....99} then display it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T06:41:17.847",
"Id": "481017",
"Score": "0",
"body": "@BurakSerdar batch size j = 3 mean display unbroken sequence of set of 3 elements {0,1,2} {3,4,5}....batch size j = 2 mean display unbroken sequence of set of 2 elements {0,1} {2,3} {4,5}... So, batch size j=100 mean, once we have 100 unbroken sequence {0.1.2.3.4.5,.....99} then display it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T07:08:20.247",
"Id": "481018",
"Score": "0",
"body": "I think you overcomplicated the problem by trying to keep things in a slice. If the seqnumber is int and no seqnumbers are skipped, you can simply keep a map keyed with seqnumber and the last item printed. Then when you get the next item in sequence, output the next items until you hit a gap. If you need to batch the output, you can batch it up after this stage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T08:01:11.037",
"Id": "481020",
"Score": "0",
"body": "@BurakSerdar sequence numbers are coming in random order. For me linkedlist makes more sense, because ordering is enforced"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T15:41:44.047",
"Id": "481052",
"Score": "0",
"body": "Linked list will have the worst time complexity because the only way to find elements in it is using linear search. A map definitely outperforms a linked list in this scenario. It is likely to outperform a slice as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:04:25.363",
"Id": "481056",
"Score": "0",
"body": "@BurakSerdar So, what would be the map key and its value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:10:50.443",
"Id": "481057",
"Score": "0",
"body": "Map key would be the sequence (int) and value be the struct. You keep the last sequence printed in a variable, and when you get the next in sequence, you print the following items from the map until you hit the next gap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:13:24.993",
"Id": "481058",
"Score": "0",
"body": "@BurakSerdar Why do we need map, when we already have variable holding the printed sequence? map is not sorted as well. Is the value struct an empty struct? can you post the code in an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:17:23.840",
"Id": "481061",
"Score": "0",
"body": "No. You put the object you receive into the map, using the sequence as the key. You don't have a variable holding the sequence, you only have a variable holding the last printed sequence value (a single int). When you receive the next in sequence, you use map to lookup the objects you stored using the correct sequence. This way you only have to store minimal possible number of objects, you look them up with amortized-constant time, and you don't have to resize a slice."
}
] |
[
{
"body": "<p>First, observe that if you receive an out-of-sequence object, you have to potentially keep all the objects from the latest printed sequence number to the received number. Worst case, you receive the object in reverse order and have to keep them all in memory. There is no way around this. So, what you can optimize is first, when you are printing objects you can find them quickly, and second, you don't want to move them around, which will happen if you use a slice and grow it as necessary.</p>\n<p>So, a sketch of an algorithm that will use CPU and memory better than what you have is as follows:</p>\n<pre><code>var nextInSequence=0 // The next item you are expecting in the sequence\nvar storedObjects=map[int]SomeStruct{}\n\nfunc Print(seqNumber int, obj SomeStruct) {\n if seqNumber==nextInSequence {\n output obj\n nextInSequence++\n } else {\n storedObjects[seqNumber]=obj\n }\n for {\n if stored, ok:=storedObjects[nextInSequence] ; ok {\n output stored\n delete(storedObjects,nextInSequence)\n nextInSequence ++\n } else {\n break\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:39:32.600",
"Id": "245008",
"ParentId": "244978",
"Score": "3"
}
},
{
"body": "<p>Using Map, below is the code:</p>\n<pre><code>func (receiver *Receiver) Print(nextSequenceIn uint64, object *data.Object, outputFile io.Writer) bool {\n receiver.receivedObjects[nextSequenceIn] = object\n if receiver.nextSeqNumExpected == nextSequenceIn { // set the next sequence expected\n key := nextSequenceIn + 1\n delete(receiver.receivedObjects, nextSequenceIn)\n for {\n if _, ok := receiver.receivedObjects[key]; !ok {\n receiver.nextSeqNumExpected = key\n break\n }\n key++\n }\n }\n fmt.Fprintf(outputFile, "[ ")\n continu := receiver.printBatch(outputFile)\n fmt.Fprintf(outputFile, "]")\n receiver.printedSequences = 0\n fmt.Fprintf(outputFile, " ----------for input value %d\\n", nextSequenceIn)\n return continu\n}\n\nfunc (receiver *Receiver) printBatch(outputFile io.Writer) bool {\n sequenceNumber := uint64(0)\n batchSize := config.GetBatchSize()\n for sequenceNumber+(batchSize-1) < receiver.nextSeqNumExpected { // received unbroken sequences are [0, receiver.nextSeqNumExpected-1]\n if receiver.printedSequences+batchSize > receiver.maxObjectsToPrint {\n receiver.Log.Printf("****Max objects(%d) to print is reached\\n", receiver.maxObjectsToPrint)\n return false\n }\n for j := sequenceNumber; j < sequenceNumber+batchSize; j++ {\n fmt.Fprintf(outputFile, "%d, ", j)\n receiver.printedSequences++\n\n }\n sequenceNumber += batchSize\n }\n return true\n}\n</code></pre>\n<p>Ran below commands:</p>\n<pre><code>$ export BATCH_SIZE=3\n$ export MAX_OBJECTS_TO_PRINT=25\n$ \n$ ~/code/bin/threadapp \n*****Main exit\n$\n</code></pre>\n<hr />\n<p><a href=\"https://github.com/shamhub/threadapp/blob/master/receiver_output\" rel=\"nofollow noreferrer\">here</a> is the output</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T21:07:57.133",
"Id": "481090",
"Score": "0",
"body": "@BurakSerdar [here](https://github.com/shamhub/threadapp) is the complete code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T19:49:05.193",
"Id": "245012",
"ParentId": "244978",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T21:54:40.200",
"Id": "244978",
"Score": "1",
"Tags": [
"algorithm",
"go"
],
"Title": "How to make Print() method memory & CPU efficient?"
}
|
244978
|
<p>I built this basic in-memory database that can support some basic operations, like SET, GET, DELETE, COUNT, etc. As well as support transactions. Some of the constraints are as follows: GET, SET, DELETE, and COUNT should have a runtime of less than O (log n), if not better (where n is the number of items in the database). The memory usage shouldn't be doubled for every transaction.</p>
<p>One improvement I was thinking to apply is to use a data structure like <code>Map()</code> to store the data -- shouldn't that provide a runtime of O(1) for all basic operations?</p>
<p>I appreciate any advice on how to improve this code.</p>
<pre><code>export class Database {
constructor() {
this.database = {valuesCount: {}, names: {}};
this.transactions = [];
}
/**
* Set the name of the database entry
*
* @param {string} name The name to set
* @param {string} value The value to set the name to
*/
set(name,value) {
if(this.database.names[name] === undefined) {
this.updateValueCount(value);
this.database.names[name] = value;
} else if(!!this.database.names[name]) {
if(this.database.names[name] !== value) {
this.updateValueCountForExistingName(name, value);
this.database.names[name] = value;
}
}
}
/**
* Update the value count for a new name
*
* @param {string} value The value count to update
*/
updateValueCount(value){
this.setCountForValue(value);
}
/**
* Update the value count for an existing name
*
* @param {string} name The name of the value count to update
* @param {string} value The value count to update
*/
updateValueCountForExistingName(name, value){
this.deleteValuePropertyForName(name);
this.setCountForValue(value);
}
/**
* Sets the count of a particular value
*
* @param {string} value The value to set the count for
*/
setCountForValue(value) {
if(!!this.database.valuesCount[value]) {
this.database.valuesCount[value]++;
} else {
this.database.valuesCount[value] = 1;
}
}
/**
* Get the name of the database entry
*
* @param {string} name The name to get
*/
get(name) {
console.log(!!this.database.names[name] ? this.database.names[name] : null);
}
/**
* Delete entry from database
*
* @param {string} name The name to delete
*/
deleteFromDatabase(name) {
if(!!this.database.names[name]) {
this.deleteValuePropertyForName(name);
}
}
/**
* Counts the number of occurrences val is found in the database
*
* @param {string} value The value to count
*/
count(value) {
if(!!this.database.valuesCount[value]) {
console.log(this.database.valuesCount[value]);
} else {
console.log(0);
}
}
/**
* Begins a transaction
*/
beginTransaction() {
if(this.transactions.length === 0) {
this.transactions.push(this.database);
}
let shallowCopy = {valuesCount: {...this.database.valuesCount}, names: {...this.database.names}};
this.transactions.push(shallowCopy);
this.database = this.transactions[this.transactions.length-1];
}
/**
* Rollback a transaction
*/
rollback() {
if(this.transactions.length > 1) {
this.transactions.pop();
this.database = this.transactions[this.transactions.length-1];
} else {
console.log('TRANSACTION NOT FOUND');
}
}
/**
* Commit a transaction
*/
commit() {
this.database = this.transactions[this.transactions.length-1];
this.transactions = [];
}
/**
* Delete value property for a particular name
*
* @param {string} name The value to delete
*/
deleteValuePropertyForName(name) {
this.database.valuesCount[this.database.names[name]]--;
if(this.database.valuesCount[this.database.names[name]] === 0) {
delete this.database.valuesCount[this.database.names[name]];
}
delete this.database.names[name];
}
/**
* Handle User Input for Various Database Commands
*
* @param {string} input User command line input
* @returns {boolean}
*/
handleInput(input) {
const inputRaw = input.split(' ');
const action = inputRaw[0];
const arg1 = inputRaw[1];
const arg2 = inputRaw[2];
let name = '';
let value = '';
switch(action) {
case 'SET':
if(!!arg1 && !!arg2) {
name = arg1;
value = arg2;
this.set(name, value);
} else {
console.log('Invalid Input: the SET command must include a name and a value.');
}
break;
case 'GET':
name = inputRaw[1];
if(!!name) {
this.get(name);
} else {
console.log('Invalid Input: the GET command must include a name.');
}
break;
case 'DELETE':
name = inputRaw[1];
if(!!name) {
this.deleteFromDatabase(name);
} else {
console.log('Invalid Input: the DELETE command requires a name.');
}
break;
case 'COUNT':
value = inputRaw[1];
if(!!value) {
this.count(value);
} else {
console.log('Invalid Input: the COUNT command requires a value to count.');
}
break;
case 'BEGIN':
this.beginTransaction();
break;
case 'ROLLBACK':
this.rollback();
break;
case 'COMMIT':
this.commit();
break;
case 'END':
return true;
default:
console.log('Function is not valid.');
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A few points, most of these I have applied to your code here: <a href=\"https://stackblitz.com/edit/so-in-mem-db?file=index.js\" rel=\"nofollow noreferrer\">https://stackblitz.com/edit/so-in-mem-db?file=index.js</a></p>\n<p><strong>Potential use of Map and O(1) time</strong></p>\n<p>The javascript objects you are currently using are de-facto dictionaries, so it is unlikely you will gain anything here.</p>\n<p><strong>Unnecessary use of !!</strong></p>\n<p>You have used this frequently in your code, in all the places I checked it was unnecessary.</p>\n<p><strong>handleInput argument parsing</strong></p>\n<p>You can tidy this up considerably using array destructuring (see stackblitz for complete example) ie:</p>\n<pre><code>const [action, ...args] = inputRaw; \n...\nconst [name, value] = args;\n</code></pre>\n<p><strong>Use logical OR to simplify if..else</strong></p>\n<pre><code> if(!!this.database.valuesCount[value]) {\n console.log(this.database.valuesCount[value]);\n } else {\n console.log(0);\n }\n</code></pre>\n<p>can be simplified to:</p>\n<pre><code>console.log(this.database.valuesCount[value] || 0);\n</code></pre>\n<p>Similarly</p>\n<pre><code> get(name) {\n console.log(!!this.database.names[name] ? this.database.names[name] : null);\n }\n</code></pre>\n<p>can be simplified to:</p>\n<pre><code> get(name) {\n console.log(this.database.names[name] || null);\n }\n</code></pre>\n<p><strong>Over complicated logic in set(..) and when updating value counts</strong></p>\n<p>This could definitely be improved but it would also involve refactoring the way you are updating value counts (ideally there wouldn't be two different methods), so I'll leave it at that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T13:22:02.860",
"Id": "481113",
"Score": "0",
"body": "Hey there, I appreciate your reply. I gave using `Map` some thought and I am not seeing a benefit in terms of usage or performance. Correct me if I'm wrong but current performance with objects is already currently O(1) for GET, SET, DELETE, COUNT, is it not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T14:16:29.393",
"Id": "481117",
"Score": "0",
"body": "Yep, as I inferred in my answer its already O(1) as using a JavaScript object as you have is pretty much the same as a dictionary or map."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T22:17:22.103",
"Id": "481291",
"Score": "0",
"body": "Thanks for confirming this @wlf. Another question, if I want to write some tests for this code. Would I write unit tests or integration tests? also, for unit tests, what would I test exactly? say if I am testing the `set` function, what am I check for? do I need to assert that the database object contains the properties I passed in? also, what if the storage property isn't typically accessible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T21:20:09.897",
"Id": "481402",
"Score": "0",
"body": "If you're writing unit tests, you'll probably need to access the private `database` member. Accessing private members in tests is a controversial subject, but if you want to do it have a look at the PrivateObject class (https://visualstudiomagazine.com/blogs/tool-tracker/2018/08/testing-private-fields.aspx). Otherwise the tests will be more integration like where you set and get to verify results, or set and count etc. IMO don't get too concerned with what type of test they are, just ensure that however you do it there is adequate coverage. PS can you consider accepting my answer above."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:51:43.097",
"Id": "245009",
"ParentId": "244979",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-03T22:28:39.780",
"Id": "244979",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "In-memory database class"
}
|
244979
|
<p>I have a video component passing data from an async GET request to a child component:</p>
<pre><code>// Inside a v-for loop
<video
:title="video.title"
:id="video._uid"
>
// ...
<Controls :videoData="video" />
</code></pre>
<p>When receiving the prop in <code>Controls</code> I then use that data to select the video by it's <code>id</code> in the DOM and set data properties according to that element:</p>
<pre><code>created() {
setTimeout(() => {
this.video = document.getElementById(this.videoData._uid);
this.videoDuration = this.video.duration;
setInterval(() => {
this.videoCurrentTime = this.video.currentTime;
this.videoPlaying = !this.video.paused;
this.videoVolume = this.video.volume;
}, 1);
}, 1000);
}
</code></pre>
<p>The <code>setTimeout</code> is to get around the data being asynchronous and the <code>setInterval</code> is to continuously update the data, such as the current time of the video, whether it's paused or not, etc.</p>
<p>It works exactly as it should, but it seems really inefficient. What if someone has slow internet and it takes longer than 1000ms to fetch the data, for example.</p>
<p>I would think the fact it's in a <code>v-for</code> loop would prevent the need for <code>setTimeout</code> as the component wouldn't exist before the video has been fetched. I must be missing something.</p>
<p>Request:</p>
<pre><code>created() {
this.fetchVersion().then(async () => {
await Axios.get(
`https://api.storyblok.com/v1/cdn/stories/videos?version=published&token=<STORYBLOK_TOKEN>&cv=${this.getVersion}`
).then(res => {
res.data.story.content.body.forEach(i => {
this.storyblokVideos.push(i);
});
});
});
}
</code></pre>
<p>Does anyone have a better way of making the data reactive?</p>
<p><strong>UPDATE</strong></p>
<p>Thanks to @potato's answer:</p>
<p>I set a data property called <code>isLoading: true</code> then used the video's event <code>oncanplay</code> to conditionally load the controls: <code>@canplay="isLoading = false"</code>. No more async errors. Then I used the different events to pass data:</p>
<pre><code>@play="playing = true"
@pause="playing = false"
@timeupdate="updateCurrentTime()"
@volumechange="updateVolume()"
</code></pre>
<p>Much more efficient.</p>
|
[] |
[
{
"body": "<p>Use events and callbacks to react to things as they happen instead of repeatedly checking for changes.</p>\n<p>You can use the <code>.then</code> function to do whatever needs to be done once the data is received.</p>\n<p>You can learn about the <code><video></code> element events here: <a href=\"https://www.w3schools.com/tags/ref_av_dom.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/tags/ref_av_dom.asp</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T14:40:09.160",
"Id": "481119",
"Score": "2",
"body": "Good spot! Can always rely on a potato. I'll update my question to reference your answer"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T09:38:13.503",
"Id": "245026",
"ParentId": "244986",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T08:45:49.667",
"Id": "244986",
"Score": "2",
"Tags": [
"javascript",
"vue.js"
],
"Title": "Using setInterval() to make data reactive"
}
|
244986
|
<p>The question is from <a href="https://leetcode.com/explore/interview/card/top-interview-questions-easy/127/strings/880/" rel="nofollow noreferrer">Leetcode</a>.</p>
<p>Given a 32-bit signed integer, reverse digits of an integer.</p>
<pre><code>Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
</code></pre>
<blockquote>
<p>Note: 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>
<hr />
<p><strong>My solution</strong>:</p>
<pre><code>class Solution {
public int reverseInteger(int num) {
if(num >= 0) { // positive numbers
char[] arr = String.valueOf(num).toCharArray();
reverse(arr);
return Integer.parseInt(new String(arr));
} else { // negative numbers
num *= -1;
char[] arr = String.valueOf(num).toCharArray();
reverse(arr);
return -Integer.parseInt(new String(arr));
}
}
void reverse(char[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
char temp = arr[start];
arr[start++] = arr[end];
arr[end--] = temp;
}
}
}
</code></pre>
<hr />
<p>For one of the test cases, I am getting the following error:</p>
<pre><code> java.lang.NumberFormatException: For input string: "9646324351"
at line 68, java.base/java.lang.NumberFormatException.forInputString
at line 658, java.base/java.lang.Integer.parseInt
at line 776, java.base/java.lang.Integer.parseInt
at line 6, Solution.reverse
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
</code></pre>
<hr />
<p>I do not understand why the test case is failing? Any indications to resolve the exception or to improve the solution would be welcome. Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T12:58:08.763",
"Id": "481034",
"Score": "2",
"body": "Hi, codereview is for refactoring working code to even better code. [SO] can help you with bugs. Therefor, you should ask your question on codereview."
}
] |
[
{
"body": "<p>In Java and many others, <code>int</code> is a 32-bit data type which means it has the range $[-2^31, 2^31– 1]$. For the input "1534236569" which is reversed to "9646324351" is outside this range. As stated in the note, consider returning 0 when this occurs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T13:23:58.433",
"Id": "481037",
"Score": "5",
"body": "Don't answer _off-topic_ questions here please. Code Review is for already working code only."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T13:11:35.917",
"Id": "244994",
"ParentId": "244993",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "244994",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T12:35:28.173",
"Id": "244993",
"Score": "-3",
"Tags": [
"java",
"integer"
],
"Title": "Return reversed integer - Java"
}
|
244993
|
<p>I am slowly creating a flow field pathfinding solution for Unity3D. I'm trying to follow <a href="http://www.gameaipro.com/GameAIPro/GameAIPro_Chapter23_Crowd_Pathfinding_and_Steering_Using_Flow_Field_Tiles.pdf" rel="nofollow noreferrer">Elijah Emerson's description</a>, which appears in the book 'Game AI Pro' (volume 1).</p>
<p>The map is divided into sectors, and each sector houses three fields: cost, integration, flow, which need each other to calculate the flow field.</p>
<p>At one point I got fed up trying to reference locations in space between sectors and fields, so created a Coordinates object to handle this task. But I'm not sure if I've created an object which makes good sense for an optimal solution? I initially created a Struct, because the object is a data type which holds just world X and Y, along with a reference to the world this belongs to.</p>
<p>Because of this, I didn't want to load the object with more data fields, but I did need to reference various things described above. So I added get-only properties which call data from elsewhere. But is this fast and optimal? I don't know. I know there's an inevitable trade between memory and processing, but I just don't know what makes sense here for a fast solution.</p>
<pre><code>using UnityEngine;
public struct Coordinates
{
public readonly FlowFieldWorld world;
public readonly int worldX, worldY;
public int SectorX { get { return worldX % world.SectorSize; } }
public int SectorY { get { return worldY % world.SectorSize; } }
public FlowFieldSector Sector { get { return world.Sectors[worldX / world.SectorSize, worldY / world.SectorSize]; } }
public CostTile Cost { get { return Sector.CostField[SectorX, SectorY]; } }
public IntegrationTile Integration { get { return Sector.IntegrationField[SectorX, SectorY]; } }
public FlowTile Flow { get { return Sector.FlowField[SectorX, SectorY]; } }
public bool IsWalkable { get { return Cost.Value != 255; } }
public readonly static Coordinates zero = new Coordinates(0, 0, null);
public Vector3 Vector3 { get { return new Vector3(worldX, 0, worldY); } }
public Coordinates(int worldX, int worldY, FlowFieldWorld world)
{
this.worldX = worldX;
this.worldY = worldY;
this.world = world;
}
public Coordinates(Coordinates coordinates)
{
this.worldX = coordinates.worldX;
this.worldY = coordinates.worldY;
this.world = coordinates.world;
}
public static bool operator ==(Coordinates left, Coordinates right)
{
return left.worldX == right.worldX && left.worldY == right.worldY;
}
public static bool operator !=(Coordinates left, Coordinates right)
{
return left.worldX != right.worldX || left.worldY != right.worldY;
}
public override bool Equals(object obj)
{
return obj is Coordinates coordinates && Equals(coordinates);
}
public bool Equals(Coordinates other)
{
return worldX == other.worldX && worldY == other.worldY;
}
public override int GetHashCode()
{
int hashCode = 1845962855;
hashCode = hashCode * -1521134295 + worldX.GetHashCode();
hashCode = hashCode * -1521134295 + worldY.GetHashCode();
return hashCode;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have no knowledge about Unity3d, so here are some general comments.</p>\n<p>If <code>world.SectorSize</code> is constant throughout the session, you can change some of the properties to readonly fields and calculate them in the constructor:</p>\n<pre><code>public readonly int SectorX;\npublic readonly int SectorY;\npublic readonly FlowFieldSector Sector;\n...\n\n\npublic Coordinates(int worldX, int worldY, FlowFieldWorld world)\n{\n this.worldX = worldX;\n this.worldY = worldY;\n this.world = world;\n SectorX = worldX % world.SectorSize;\n SectorY = worldY % world.SectorSize;\n Sector = world.Sectors[worldX / world.SectorSize, worldY / world.SectorSize];\n}\n</code></pre>\n<p>Doing so with <code>Sector</code>, <code>Cost</code>, <code>Integration</code> and <code>Flow</code> requires of cause that these objects are reference types and not replaced - if they are updated while the <code>Coordinates</code> instance lives. It is probably just a micro optimization - but everything counts?</p>\n<hr />\n<blockquote>\n<pre><code>public bool Equals(Coordinates other)\n{\n return worldX == other.worldX && worldY == other.worldY;\n}\n</code></pre>\n</blockquote>\n<p>This is actually an implementation of <code>IEquatable<Coordinates></code> so you can add this interface to the inheritance list:</p>\n<pre><code>public struct Coordinates : IEquatable<Coordinates>\n</code></pre>\n<hr />\n<p>In respect to the DRY-principle you could do the following changes:</p>\n<p>The copy constructor can call the other constructor:</p>\n<pre><code>public Coordinates(Coordinates source) : this(source.worldX, source.worldY, source.world)\n{\n}\n</code></pre>\n<p>The comparison operators can call <code>Equals(Coordinates other)</code>:</p>\n<pre><code>public static bool operator ==(Coordinates left, Coordinates right)\n{\n return left.Equals(right);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T06:22:36.833",
"Id": "245022",
"ParentId": "244997",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245022",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T13:25:24.210",
"Id": "244997",
"Score": "3",
"Tags": [
"c#",
"pathfinding",
"unity3d"
],
"Title": "Coordinates Struct for Flow Field Pathfinding... am I doing this right?"
}
|
244997
|
<p>I've done my best to contrive an example of the problem I'm trying to simplify. I have a pool of workers, and each worker can do several tasks at a time. Each task takes an unspecified amount of time. The goal is to drain the task queue by keeping each each worker as busy as possible.</p>
<p>In order to accomplish this, once the taskQueue has a nonzero number of tasks, each Worker is given tasks up to maxTasks. When a worker completes any one task, he uses the callback he was given to return the result. The worker is then assigned a new task in that callback. Workers are continually given new tasks untilthe taskQueue is empty..</p>
<p>This doesn't feel like an elegant solution. Would this be better accomplished using a stream or an event emitter? Any thoughts would be greatly appreciated.</p>
<pre><code>function WorkerPool(numWorkers) {
const workers = [];
const taskQueue = [];
for (let i = 0; i < numWorkers; i += 1) {
workers.push(Worker());
}
function supplyNewTask(worker) {
if (taskQueue.length) {
const task = taskQueue.pop();
console.log(`task queue length decremented to ${taskQueue.length}`);
worker.work(task, supplyNewTask);
}
}
return {
work: function(task) {
for (const worker of workers) {
if (worker.availableTasks()) {
worker.work(task, supplyNewTask);
return;
}
}
// if couldn't find a buyer...
taskQueue.push(task);
console.log(`task queue length incremented to ${taskQueue.length}`);
}
}
}
function Worker() {
let activeTasks = 0;
let maxTasks = 5;
return {
availableTasks: () => maxTasks - activeTasks,
work: function(task, callback) {
activeTasks += 1;
console.log(`workers active tasks incremented to ${activeTasks}`);
// do some work that takes an unspecified
// amount of time, then callback with the
// result.
setTimeout(() => {
activeTasks -= 1;
console.log(`workers active tasks decremented to ${activeTasks}`);
callback(this);
}, Math.floor(Math.random() * 100));
},
};
}
const pool = WorkerPool(3);
for (let i = 0; i < 6000; i++) {
pool.work({ /* some work to be done */ });
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T15:25:17.903",
"Id": "245000",
"Score": "3",
"Tags": [
"node.js"
],
"Title": "Single Producer/Multiple Consumers in Node"
}
|
245000
|
<p>Given an object with unsorted numeric values, such as:</p>
<pre><code>const unsorted = {
green: 80,
blue: 90,
red: 30,
yellow: 100,
}
</code></pre>
<p>We want a data structure with the same key/value pairs sorted in descending order of the values, e.g.:</p>
<pre><code>const sorted = {
yellow: 100,
blue: 90,
green: 80,
red: 30,
}
</code></pre>
<p>My solution:</p>
<pre><code>function sortObjectByValue (obj) {
const sorted = Object.keys(obj)
.sort((a, b) => obj[b] - obj[a])
.reduce((acc, cur) => {
acc[cur] = obj[cur]
return acc
}, {})
return new Map(Object.entries(sorted))
}
</code></pre>
<p>What I hope could be improved:</p>
<ul>
<li>Two iterations, first <code>sort</code> then <code>reduce</code>; this seems inefficient.</li>
<li>Using <code>Map</code>. I wish we could just use objects, it would make using this elsewhere much easier. I doubt this can be avoided though, as we need to ensure that the order is preserved.</li>
</ul>
|
[] |
[
{
"body": "<p>Here's my proposal:</p>\n<pre><code>function sortObjectByValue (obj) {\n const map = new Map()\n\n Object.entries(obj)\n .sort((a, b) => obj[b][1] - obj[a][1])\n .forEach(([key, value]) => {\n map.set(key, value)\n });\n\n return map;\n}\n</code></pre>\n<p>You don't need to create a sorted object unless you want to use it, I understand that you are using a Map so that you can preserve the order of the elements, but keep in mind this:</p>\n<blockquote>\n<p>Note: Since ECMAScript 2015, objects do preserve creation order for\nstring and Symbol keys. In JavaScript engines that comply with the\nECMAScript 2015 spec, iterating over an object with only string keys\nwill yield the keys in order of insertion.</p>\n</blockquote>\n<p>Source: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map</a></p>\n<p>So with that in mind we can skip the Map and we have something like this:</p>\n<pre><code>function sortObjectByValue2 (obj) {\n return Object.keys(obj)\n .sort((a, b) => obj[b] - obj[a])\n .reduce((acc, cur) => {\n acc[cur] = obj[cur]\n return acc\n }, {})\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T18:17:35.257",
"Id": "481072",
"Score": "0",
"body": "Great that we can skip the `Map`! Thanks for pointing that out. Otherwise you think that a two-step `sort` + `reduce` is the most efficient way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T21:37:09.120",
"Id": "481091",
"Score": "2",
"body": "Yeah, 1 pass to convert object to array, 1 pass to sort, 1 pass to convert back to object. You may also be able to use the `Object.fromEntries` to do the conversion of sorted key-value pairs array to object, i.e. `Object.fromEntries(Object.entries(object).sort(/* sort function */))`, but it's still the same number of passes over the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T19:07:33.527",
"Id": "481145",
"Score": "0",
"body": "OK, that's what I was afraid of. Well at least we got rid of the `Map` (disclaimer: nothing against `Map`, just unneeded here)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:28:47.827",
"Id": "245007",
"ParentId": "245003",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "245007",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T16:14:32.830",
"Id": "245003",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6"
],
"Title": "Sorting an object by value w/ `sort` and `reduce`"
}
|
245003
|
<p>I'm beginning a redesign of the front end of my Flask app which currently generates Jinja2 template-based html pages. I am trying to develop a new front end in React, but I want the current front end to continue to exist. Much like Reddit, I want my current front end to exist at old.anno.wiki and the new front end to exist at anno.wiki, but I would like to continue to use all the same backend code.</p>
<p>There are several ways to achieve this and the idea that I most like is that I move the entire app to old.anno.wiki and write a React app at anno.wiki that queries old.anno.wiki's to-be-developed api. This runs into problems with CORS, and, more importantly, with issues of development vs production fetching.</p>
<p>(note: right now I'm temporarily using new.anno.wiki for the new react front end while I continue to use anno.wiki for the old one as I develop the new).</p>
<p>As I develop, while in dev I'd like to query the Flask api running in docker locally, in production I'd like to query the api currently at anno.wiki/api. To do this I set the <a href="https://github.com/malan88/icc-frontend/blob/master/package.json#L3" rel="nofollow noreferrer">React proxy to "http://localhost:5000"</a> and wrote a helper function to get the domain to query in my code:</p>
<pre><code>const URL = 'https://anno.wiki';
const getHome = () => {
const url = process.env.NODE_ENV === 'development' ? '' : URL;
return url
}
</code></pre>
<p>I then, in all my fetches, query this and use it to precede whatever route I query, like so:</p>
<pre><code> const [currentTime, setCurrentTime] = useState(0);
const url = getHome();
useEffect(() => {
fetch(url + '/api/time').then(res => res.json()).then(data => {
setCurrentTime(data.time);
});
}, [url]);
</code></pre>
<p>I am concerned that this might not be the way to do this. Is this secure? I imagine that by concatenating with <code>+</code> it is less efficient than using template literals, but that is not my concern. My concern is that this might have hidden consequences that I am unaware of, either security implications or efficiency problems.</p>
<p>Any advice would be very much appreciated.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T17:28:46.303",
"Id": "245006",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"cors"
],
"Title": "Cross domain fetch switching in prod vs dev"
}
|
245006
|
<p>Through my previous questions, I developed a web-scraper that gets tennis ranking data.</p>
<ul>
<li><a href="https://codereview.stackexchange.com/questions/244074/webscraping-tennis-data">Webscraping tennis data</a>: major refactor of code style and program modularity</li>
<li><a href="https://codereview.stackexchange.com/questions/244195/webscraping-tennis-data-1-1">Webscraping tennis data 1.1</a>: improving exception handling</li>
</ul>
<p>In this version, I'm back with some modifications for my scraper based on my goals for the overarching project I have in mind. <strong>I understand this is a longer post, so I've divided my question into thematic sections - hopefully this makes it easier for readers to follow and provide feedback where they can!</strong></p>
<hr />
<h2>What's changed in the code?</h2>
<ol>
<li><p>Rather than scrape ALL the weeks, and return a list of <code>WeeklyResult</code>s, the scraper now returns a result for a given week. This enables the scraper to scrape a week, pass it on to another function that utilizes the scraped result. Note that it is not truly "asynchronous" yet - <em>more on that later</em>.</p>
<ul>
<li>To facilitate this, <code>Scraper</code> and <code>MyProject</code> have been modified accordingly.</li>
</ul>
</li>
<li><p><code>Scraper</code> bug fix #1: certain weeks did not have actual ranking data for the No.1 on the website. Previously, each weekly result was loaded as an <code>Optional</code> in case the player-cell element was empty. However, I had overlooked a case where the first available player-cell was non-empty, but didn't actually belong to the No.1 player.</p>
<ul>
<li><code>selectNumberOneRankCell</code> in <code>scrapeWeekly</code> resolves this.</li>
</ul>
</li>
<li><p><code>Scraper</code> bug fix #2: Further inspection showed that the empty <code>WeeklyResults</code> would be between stretches of the reign of a given player. With that trend in mind, plus the general likelihood that the current week's No.1 has a good chance to remain No.1 for the next week (generally), I changed the code to retain the No.1 player from the past week, in the case of an empty scraped result.</p>
<ul>
<li>Added a new field <code>latestResult</code> and modified <code>scrape</code>.</li>
</ul>
</li>
<li><p><strong><code>WeeklyResult</code> & <code>ScraperException</code> remain unchanged.</strong></p>
</li>
</ol>
<hr />
<h2>Code:</h2>
<p><strong><code>scraper</code> Package:</strong></p>
<p><em>WeeklyResult.java</em></p>
<pre><code>package scraper;
// A POJO that encapsulates a ranking week and the name of the corresponding No.1 player
public class WeeklyResult {
private final String week;
private final String playerName;
public WeeklyResult(final String week, final String playerName) {
this.week = week;
this.playerName = playerName;
}
public String getWeek() {
return week;
}
public String getPlayerName() {
return playerName;
}
}
</code></pre>
<p><em>ScraperException.java</em></p>
<pre><code>package scraper;
public class ScraperException extends Exception {
final String message;
public ScraperException (String message) {
this.message = message;
}
public ScraperException (String message, Throwable cause) {
super(cause);
this.message = message;
}
@Override
public String toString() {
return this.message;
}
}
</code></pre>
<p><em>Scraper.java</em></p>
<pre><code>package scraper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
public class Scraper {
private static final Logger logger = LogManager.getLogger(Scraper.class);
private final String urlPrefix;
private final String urlSuffix;
private final Duration timeout;
private final int totalTries;
private WeeklyResult latestResult;
public Scraper(final String urlPrefix, final String urlSuffix, final Duration timeout, final int totalTries) {
this.urlPrefix = urlPrefix;
this.urlSuffix = urlSuffix;
this.timeout = timeout;
this.totalTries = totalTries;
this.latestResult = new WeeklyResult("1973-08-16","N/A");
}
public WeeklyResult scrape(final String week) throws ScraperException {
// in the case the latest scraped data returns an "empty" weekly result, simply retain the latest No.1
// since it is likely he wouldn't have changed. A weekly result is deemed empty if no player or week info
// can be found on the ATP page.
this.latestResult = scrapeWeekly(week)
.orElse(new WeeklyResult(updateLatestWeekByOne(), this.latestResult.getPlayerName()));
return this.latestResult;
}
private Optional<WeeklyResult> scrapeWeekly(final String week) throws ScraperException {
final Document document = loadDocument(weeklyResultUrl(week));
final boolean numberOneDataExists = selectNumberOneRankCell(document).isPresent();
final Element playerCell = numberOneDataExists ? selectPlayerCellElement(document) : null;
return Optional.ofNullable(playerCell)
.map(element -> new WeeklyResult(week, element.text()));
}
public List<String> loadWeeks() throws ScraperException {
final Document document = loadDocument(urlPrefix);
final Elements elements = selectRankingWeeksElements(document);
final List<String> weeks = extractWeeks(elements);
return noEmptyElseThrow(weeks);
}
private Document loadDocument(final String url) throws ScraperException {
Document document = null;
for (int tries = 0; tries < this.totalTries; tries++) {
try {
document = Jsoup.connect(url).timeout((int) timeout.toMillis()).get();
break;
} catch (IOException e) {
if (tries == this.totalTries) {
throw new ScraperException("Error loading ATP website: ", e);
}
}
}
return document;
}
private static Elements selectRankingWeeksElements(final Document document) {
// extract ranking weeks from the dropdown menu
final Elements result = document.getElementsByAttributeValue("data-value", "rankDate")
.select("ul li");
Collections.reverse(result);
return result;
}
private static List<String> extractWeeks(final Collection<Element> elements) {
// refer to https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
// and https://www.baeldung.com/java-maps-streams.
return elements.stream()
.map(Scraper::extractWeek)
.filter(week -> Optional.ofNullable(week).isPresent())
.collect(Collectors.toList());
}
private static List<String> noEmptyElseThrow(final List<String> weeks) throws ScraperException {
if (weeks.isEmpty()) {
throw new ScraperException("Cannot process empty data from the weeks calendar!");
} else {
return weeks;
}
}
private String weeklyResultUrl(final String week) {
return urlPrefix + "rankDate=" + week + urlSuffix;
}
private static Optional<Element> selectNumberOneRankCell(final Document document) {
final Element rankCell = selectPlayerRankCell(document);
return Optional.ofNullable(rankCell).filter(element -> numberOneRankCellExists(element));
}
private static Element selectPlayerCellElement(final Document document) {
return document.getElementsByClass("player-cell").first();
}
private static boolean numberOneRankCellExists(final Element rankCell) {
return rankCell.text().equals("1");
}
private static Element selectPlayerRankCell(final Document document) {
return document.getElementsByClass("rank-cell").first();
}
private static String extractWeek(final Element li) {
return li.text().replaceAll("\\.", "-");
}
private String updateLatestWeekByOne() {
return LocalDate.parse(this.latestResult.getWeek()).plusWeeks(1).toString();
}
}
</code></pre>
<p><strong><code>myproject</code> Package</strong>:</p>
<p><em>MyProject.java</em></p>
<pre><code>package myproject;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import scraper.Scraper;
import scraper.ScraperException;
import scraper.WeeklyResult;
import java.time.Duration;
import java.util.List;
// Main class to manage the visualization of player's legacy rankings
public class MyProject {
private static final Logger logger = LogManager.getRootLogger();
private static void utilizeScrapedResult(WeeklyResult weeklyResult) {
// pass the scraped result to the next stage of the visualization logic.
logger.info("Week: " + weeklyResult.getWeek() + " No.1: " + weeklyResult.getPlayerName());
}
public static void main(String[] args) {
Configurator.setRootLevel(Level.DEBUG);
final Scraper scraper =
new Scraper("https://www.atptour.com/en/rankings/singles?",
"&rankRange=0-100", Duration.ofSeconds(90), 3);
// The flow is as follows: scrape the latest weekly results (starting from 1973),
// then pass it to the ranking logic (IPR). Rinse and repeat
try {
final List<String> weeks = scraper.loadWeeks();
for (String week : weeks) {
WeeklyResult weeklyResult = scraper.scrape(week);
utilizeScrapedResult(weeklyResult);
}
} catch (ScraperException e) {
System.out.println(e.toString());
}
}
}
</code></pre>
<hr />
<h2><code>Scraper</code> Code: Optionals, Streams and Style Checks</h2>
<ol>
<li><p>I want to make sure I'm not abusing the concept of an <code>Optional</code>. I believe I'm not, since both the <em>player-cell</em> and <em>rank-cell</em> generally hold values relevant for us, but occasionally don't. One thing that was a bit sticky, though, was the fact that I didn't really have a neat way to relate <em>rank-cell</em> elements to <em>player-cell</em>s. Logically, I wanted to say: "The <code>rank-cell</code> element is empty if the first available one on the given page is not that of the actual No.1's. Select the <code>player-cell</code> element if the <code>rankCell</code> is actually present." This is the best I could come up with:</p>
<pre><code>
final boolean numberOneDataExists = selectNumberOneRankCell(document).isPresent();
final Element playerCell = numberOneDataExists ? selectPlayerCellElement(document) : null;
</code></pre>
<p>It'd be neat to know if there is a better way of achieving this.</p>
</li>
<li><p>Have I used Streams properly, specifically in the <code>selectNumberOneRankCell</code> & <code>extractWeeks</code> functions?</p>
</li>
<li><p>Any other style concerns would be appreciated. I think the addition of <code>latestResult</code> should be good, please let me know if I'm overlooking something!</p>
</li>
</ol>
<hr />
<h2><code>MyProject</code> Code - Optimizing the Scraper design, Asynchronicity & Callbacks.</h2>
<p><strong>NOTE: Since this involves looking at my design, which could be off-topic, I will keep it short. If it is off-topic, please let me know and I'll remove it and repost to a more appropriate site.</strong></p>
<p>In general, the code in <code>MyProject</code> involves chaining separate pieces of logic. Eg. scrape a <code>WeeklyResult</code>, pass it on to <code>utilizeScrapedResult</code>, which does its work and constructs something, say a <code>WeeklyRanking</code>, that is passed to the next logical section and so on. Would my current code structure be efficient to handle this as the number of separate pieces of logic increases, or should I switch to using callbacks as <a href="https://codereview.stackexchange.com/a/244087/223813">suggested</a>?</p>
<ul>
<li>In this context, a given piece of logic would only be dependent on its output in the preceding timestamp. Eg. the <code>WeeklyRanking</code> for week B would have to be preceded by the <code>WeeklyRanking</code> for week A, but the <code>WeeklyResult</code> for week B could be scraped (and stored somewhere) before the <code>WeeklyRanking</code> of week A is computed. On the flip side, a <code>WeeklyResult</code> for week A cannot be constructed <em>after</em> the <code>WeeklyResult</code> of week B. (I forget the mathematical term used to describe this relation...)</li>
</ul>
<hr />
<p>Feedback on any other aspects of the code that need to be addressed are welcome. If you made it this far, thank you for your time!</p>
|
[] |
[
{
"body": "<p>Reviewing this myself for the sake of completion.</p>\n<hr />\n<h2>Nits</h2>\n<ul>\n<li>Utilize the logger instead of System.out.println. Thus, use <code>logger.error(e.toString());</code> instead of <code>System.out.println(e.toString());</code></li>\n<li><code>loadDocument</code> has been updated with a try-catch to facilitate multiple connection tries. The try catch is thus a necessary evil, but upon revieiwng the code it would be slightly preferable to write it this way:</li>\n</ul>\n<pre><code> private Document loadDocument(final String url) throws ScraperException {\n for (int tries = 0; tries < this.totalTries; tries++) {\n try {\n return Jsoup.connect(url).timeout((int) timeout.toMillis()).get();\n } catch (IOException e) {\n if (tries == this.totalTries) {\n throw new ScraperException("Error loading ATP website: ", e);\n }\n }\n }\n return null;\n }\n</code></pre>\n<p>(Note that the final <code>return null</code> should never actually execute; it's only there to provide a compile error. A bit ugly but I prefer it over the anti-pattern of setting document null and then modifying it anyways).</p>\n<hr />\n<h2>Optionals & Streams</h2>\n<ul>\n<li><p>Double checking the code, the rationale between having <code>Optional<></code> type for <code>rankCell</code> elements is reasonable - we filter rankCell elements based on whether the rank value is No.1, and if not, the element should be considered empty for our purposes. Similarly, the boolean logic check for the <code>playerCell</code> element seems ok as well. We only want to consider <code>playerCell</code> if <code>rankCell</code> is non-empty, and even in that case, <code>playerCell</code> could return a null element, so the final return value of an <code>Optional</code> seems ok.</p>\n</li>\n<li><p>I have an issue with <code>extractWeeks</code>, specifically of the <code>filter</code>:</p>\n</li>\n</ul>\n<pre><code> return elements.stream()\n .map(Scraper::extractWeek)\n .filter(week -> Optional.ofNullable(week).isPresent())\n .collect(Collectors.toList());\n</code></pre>\n<p>This code is implying that you want to filter out weeks that are null. This doesn't make sense in light of your logic in <code>scrape</code>, where you seek to either scrape a week's result if it exists, or re-construct week data by using <code>updateLatestWeekByOne()</code>. If you are already handling the case for a week being <code>null</code>, it's pointless to filter out null weeks.</p>\n<ul>\n<li>Building on this, <strong>you end up hiding a serious functionality bug in your code</strong>. Note that the main loop in <code>MyProject</code> is passing each <code>week</code> in <code>weeks</code> to <code>scraper.scrape</code>. Some of these weeks could be <code>null</code>, OR the data we want for these could be non-existent on the ATP site. What ends up happening in this case is that you "de-synchronize" from <code>weeks</code> in the latter case, as a result you run the risk of your loop prematurely ending. Luckily, your loop "re-synchronizes" since the value of forthcoming weeks are non-empty, but this introduces a new bug: you still have jumps between your timeline! So your logic to get the <code>latestResult</code> is not quite right. You may wish to address this later or immediately, depending on how severe you feel this bug is (although it doesn't result in a fully correct program, 90+ % of the results are correct).</li>\n</ul>\n<hr />\n<h2>Unit Testing</h2>\n<p>Given such possible bugs, you may wish to look into unit testing the scraper. Moving forward, test-driven development (TDD) may be worth the initial time investment as it can help avoid wasting time on correcting subtle mistakes like this.</p>\n<hr />\n<h2>Scraper 'Chaining' Design</h2>\n<p>(Disclaimer: still not fully sure about this, and I am considering posting this question to another site: eg. Software Engineering StackExchange)</p>\n<ul>\n<li>The chaining design can be made to work, however it might make the driver in <code>MyProject</code> unwieldy if you scale the number of such tasks to be chained.</li>\n<li>Look into <code>Future</code>s in Java; it seems like you can wrap a partially asynchronous operation into a syncrhonous one, since (I believe) 'get's are blocking. Refer to <a href=\"https://stackoverflow.com/questions/2180419/wrapping-an-asynchronous-computation-into-a-synchronous-blocking-computation\">this</a> for more research.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T20:33:19.053",
"Id": "245243",
"ParentId": "245010",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245243",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T18:00:42.913",
"Id": "245010",
"Score": "3",
"Tags": [
"java"
],
"Title": "Webscraping tennis data 1.2: Optionals, Streams, Callbacks(?)"
}
|
245010
|
<p>Following takes a range & copies, pastes, transposes & links.
There doesn't seem a way in vba to do this in 1 go that I've been able to find.</p>
<p>Questions are;</p>
<ol>
<li>Is there a more efficient or safer way to do this. Keeping in mind;<br>
-needing to do this for large ranges ie. over 100K cells. <br>
-source & destination are in different worksheets or workbooks. So not the same worksheet.</li>
<li>What issues if any may exist & how to safeguard.</li>
</ol>
<p>Thank you</p>
<br>
<pre><code>Sub Foo()
'Example1
Call CopyPaste(Sheet1.Range("C10:D20"), Sheet2.Range("C1"))
'Example2
Dim wbNew As Workbook
Set wbNew = Workbooks.Add
Call CopyPaste(ThisWorkbook.Sheets(1).Range("C10:D20"), wbNew.Sheets(1).Range("C1"))
End Sub
Sub CopyPaste(rngSrc As Range, rngDest As Range)
Application.ScreenUpdating = False
ActiveWorkbook.Sheets.Add.Name = "_wsDummy_Temp_"
Dim wsDummy As Worksheet
Set wsDummy = ActiveWorkbook.Sheets("_wsDummy_Temp_")
rngSrc.Copy
wsDummy.Activate
wsDummy.Range("A1").Select
ActiveSheet.Paste Link:=True
Dim vTransposed As Variant
Dim rngSrcSrcRng As Range
Dim vSrcSrc As Variant
Dim rngDummy As Range
Set rngDummy = wsDummy.Range("A1")
Set rngDummy = rngDummy.Resize(rngSrc.Rows.Count, rngSrc.Columns.Count)
rngDummy.Formula = Application.ConvertFormula(rngDummy.Formula, xlA1, xlA1, 1)
Set rngSrcSrcRng = rngDummy
vSrcSrc = rngSrcSrcRng.Formula
vTransposed = Application.Transpose(vSrcSrc)
Set rngDest = rngDest.Resize(rngDummy.Columns.Count, rngDummy.Rows.Count)
rngDest.Formula = vTransposed
rngDummy.ClearContents
Application.DisplayAlerts = False
wsDummy.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
</code></pre>
<br>
<p><strong>EDIT</strong>:</p>
<p>With the answer provided <a href="https://codereview.stackexchange.com/a/245058/227168">@TinMan</a> I decided to fill over a 1M cells in a worksheet with numbers & do some benchmarking.</p>
<p>Original OP function: 33 to 39 seconds. <br>
Refactored CopyPaste function: 20 to 26 seconds. <br>
Alternate Approach TransposeLink function: 11 to 13 seconds. <br></p>
<p>It appears the last one is the fastest in the tests I did but also removes the need to use another temporary worksheet, removes need to use select or the clipboard.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T23:44:27.900",
"Id": "481093",
"Score": "0",
"body": "Do you have calculations set to manual?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T20:25:23.073",
"Id": "481156",
"Score": "0",
"body": "No I haven't & I hadn't even thought of that. At the moment this is quite quick & haven't noticed any slowdown, but as the range grows I guess that may be an issue."
}
] |
[
{
"body": "<h2>Review</h2>\n<blockquote>\n<pre><code>Private Sub CopyPaste(rngSrc As Range, rngDest As Range)\n</code></pre>\n</blockquote>\n<p>Prefixing variables with their type is a bit dated. Of course there are times when it is invaluable such as working with forms where their is a designer and a code module. Using simple meaningful names will make you code easier to read.</p>\n<blockquote>\n<pre><code>Private Sub CopyPaste(Source As Range, Destination As Range)\n</code></pre>\n</blockquote>\n<p>There is no need to name temporary objects.</p>\n<blockquote>\n<pre><code>ActiveWorkbook.Sheets.Add.Name = "_wsDummy_Temp_"\nDim wsDummy As Worksheet\nSet wsDummy = ActiveWorkbook.Sheets("_wsDummy_Temp_")\n</code></pre>\n</blockquote>\n<p>It better to set your variables directly whenever possible.</p>\n<blockquote>\n<pre><code>Set wsDummy = ActiveWorkbook.Sheets.Add\n</code></pre>\n</blockquote>\n<p>Since the worksheet is just temporary and the code is short, I would use a <code>With</code> block and eliminate the <code>wsDummy</code> variable altogether.</p>\n<blockquote>\n<pre><code>With ActiveWorkbook.Sheets.Add\n .Paste Link:=True\n <more code>\nEnd With\n</code></pre>\n</blockquote>\n<p>Worksheets are activated with <code>Range("A1")</code> selected whenever they are added. So eliminate these lines:</p>\n<blockquote>\n<pre><code>wsDummy.Activate\nwsDummy.Range("A1").Select\n</code></pre>\n</blockquote>\n<p>Ay-ay-ay <code>rngSrcSrcRng!! This variable is just an alias for </code>rngDummy`. Pick a name and stick with it. I take this concept to the extreme. You will see the same names throughout all my code projects.\nIMO, consistently using simple names like data ( array ), results ( array ), result (scalar value), r (row index) , c (column index), n (generic index), text ( simple string ), contents ( simple string usually file contents), source (source object such as a range) , destination (destination object such as a range), cell, target don't just make it easier to read and modify your code but it also makes it far quicker to write the code, in the first place.</p>\n<p><code>vTransposed</code> isn't needed either. It would be better to reuse <code>vSrcSrc</code> then to keep both variables in memory.</p>\n<p>Clearing the contents of a temporary worksheet. I'm guessing this is a remnant of code from your earlier attempts.</p>\n<blockquote>\n<pre><code>rngDummy.ClearContents\n</code></pre>\n</blockquote>\n<p>After your macros complete <code>Application.DisplayAlerts</code> and <code>Application.ScreenUpdating</code> are automatically reset. So these lines can be removed:</p>\n<blockquote>\n<pre><code>Application.DisplayAlerts = True\nApplication.ScreenUpdating = True\n</code></pre>\n</blockquote>\n<p>It is best to set <code>Application.Calculation = xlCalculationManual</code> when changing values or formulas on a worksheet.</p>\n<h2>Refactored Code</h2>\n<pre><code>Private Sub CopyPaste(Source As Range, Destination As Range)\n Application.ScreenUpdating = False\n Application.DisplayAlerts = False\n \n Dim calculationMode As XlCalculation\n calculationMode = Application.Calculation\n \n Dim results As Variant\n\n Source.Copy\n With Worksheets.Add\n .Paste Link:=True\n With .Range("A1").CurrentRegion\n results = Application.ConvertFormula(.Formula, xlA1, xlA1, 1)\n Destination.Resize(.Columns.Count, .Rows.Count) = Application.Transpose(results)\n End With\n .Delete\n End With\n \n Application.Calculation = calculationMode\nEnd Sub\n</code></pre>\n<h2>Alternate Approach</h2>\n<p>A more efficient method create the formula array using <code>Range.Address(RowAbsolute:=True, ColumnAbsolute:=True, External:=True)</code>. This will eliminate the need for a temporary worksheet and avoid the copy and pasting.</p>\n<pre><code> Private Sub TransposeLink(Source As Range, Destination As Range)\n Application.ScreenUpdating = False\n Application.DisplayAlerts = False\n \n Dim calculationMode As XlCalculation\n calculationMode = Application.Calculation\n \n Dim results As Variant\n With Source\n ReDim results(1 To .Columns.Count, 1 To .Rows.Count)\n \n Dim r As Long, c As Long\n \n For r = 1 To .Rows.Count\n For c = 1 To .Columns.Count\n results(c, r) = "=" & .Cells(r, c).Address(RowAbsolute:=True, ColumnAbsolute:=True, External:=True)\n Next\n Next\n \n Destination.Resize(.Columns.Count, .Rows.Count).Formula = results\n End With\n \n Application.Calculation = calculationMode\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T21:11:57.337",
"Id": "481284",
"Score": "0",
"body": "After I posted I noticed some issues, thanks. I'll update my OP soon with some benchmarking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T21:17:28.730",
"Id": "481286",
"Score": "0",
"body": "@tnuba By the way, great concept! Excel should implement it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T21:33:29.060",
"Id": "481287",
"Score": "0",
"body": "Yes I don't know why MS don't, it's a much sought after functionality. I find myself needing to do this way too much hence my post. Knew there would be a better way & knew using select or activate isn't always good idea, just didn't know how as haven't been using vba that long. So thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:09:11.967",
"Id": "481421",
"Score": "0",
"body": "I noticed that your alternate method didn't handle ranges with multiple areas well, so I added another answer building on it. Cheers"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:51:56.787",
"Id": "245058",
"ParentId": "245014",
"Score": "3"
}
},
{
"body": "\n<h2>A modification if <a href=\"https://codereview.stackexchange.com/a/245058/219620\">Tinman's Alternate Approach</a></h2>\n<p>Because <code>.Rows.Count</code> and <code>.Columns.Count</code> do not encapsulate the entirety of ranges which have more than one area (that is, where <code>.Areas.Count</code> >1) <code>TransposeLink</code> as defined above needs some modifcation to handle these cases.</p>\n<p>Namely, we will have to define an helper function that gets the footprint of all of the areas of <code>source</code>, then iterate across the rows and columns of that footprint rather than of <code>source</code> directly. In doing so, we also must check if the footprint <code>Intersect</code>s with <code>source</code>, and only iff that is the case, transfer over the formula.</p>\n<p>Application of these changes renders code somewhere along the lines of the below.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Option Compare Binary\nOption Explicit\nOption Base 1\n\n\nPublic Sub TransposeLink(ByRef src As Range, ByRef dest As Range)\n Dim ASU As Boolean, _\n ADA As Boolean, _\n ACM As Excel.XlCalculation, _\n row As Long, _\n col As Long\n \n With Application\n Let ASU = .ScreenUpdating: Let .ScreenUpdating = False\n Let ADA = .DisplayAlerts: Let .DisplayAlerts = False\n Let ACM = .Calculation: Let .Calculation = Excel.XlCalculation.xlCalculationManual\n End With\n \n With footprint(src)\n ReDim res(1 To .Columns.Count, 1 To .Rows.Count) '' dim in as variant()\n Let res = dest.Resize(.Columns.Count, .Rows.Count).Formula '' to not overwrite data\n For row = 1 To .Rows.Count\n For col = 1 To .Columns.Count\n If Not Intersect(.Cells(row, col), src) Is Nothing Then _\n Let res(col, row) = "=" & .Cells(row, col).Address(RowAbsolute:=True, ColumnAbsolute:=True, External:=True)\n Next col, row\n Let dest.Resize(.Columns.Count, .Rows.Count).Formula = res\n End With\n \n With Application\n Let .ScreenUpdating = ASU\n Let .DisplayAlerts = ADA\n Let .Calculation = ACM\n End With\nEnd Sub\n\n\nPublic Function footprint(ByRef rng As Range) As Range\n\n Dim numAreas As Long, _\n rMin As Long, rMax As Long, _\n cMin As Long, cMax As Long, _\n iter As Long\n \n Let numAreas = rng.Areas.Count\n If numAreas = 1 Then Set footprint = rng: Exit Function\n \n For iter = 1 To numAreas\n With rng.Areas(iter)\n If iter = 1 Then\n Let rMin = .Item(1).row\n Let cMin = .Item(1).Column\n Let rMax = .Item(.Count).row\n Let cMax = .Item(.Count).Column\n Else\n If .Item(1).row < rMin Then Let rMin = .Item(1).row\n If .Item(1).Column < cMin Then Let cMin = .Item(1).Column\n If .Item(.Count).row > rMax Then Let rMax = .Item(.Count).row\n If .Item(.Count).Column > cMax Then Let cMax = .Item(.Count).Column\n End If\n End With\n Next iter\n \n With rng.Worksheet\n Set footprint = .Range(.Cells(rMin, cMin), .Cells(rMax, cMax))\n End With\nEnd Function\n</code></pre>\n<p>Note the addition of the <code>Option Explicit</code> module option at the top of this code segment - enabling this helps you to keep track of your what variables you are using by forcing you to <code>dim</code> them in before using them.</p>\n<h2>Testing</h2>\n<p>A simple test which illustrates the impact is</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Sub trans_test()\n [A1:U9] = "=Right(Address(Row(),Column(),4))&Left(Address(Row(),Column(),4))"\n ' yellow - source\n TransposeLink [A1,C3,E5], [I3] ' green - new\n OLD_TransposeLink [A1,C3,E5], [Q5] ' red - old\n \n Cells.Style = "normal"\n [A1,C3,E5].offset(0, 0).Style = "neutral"\n [A1,C3,E5].offset([I3].row - 1, [I3].Column - 1).Style = "good"\n [A1,C3,E5].offset([Q5].row - 1, [Q5].Column - 1).Style = "bad"\n \nEnd Sub\n</code></pre>\n<p>where <code>OLD_TransposeLink</code> is the original version of the subroutine and which generates the worksheet shown below. In this example, a background set of formulas is generated, and then <code>A1</code>, <code>C3</code>, and <code>E5</code> (highlighted in yellow) are selected as the data source. The green highlighted region represents the pasting operation completed by the changed script and the red highlighted region represents that of the original script. Note that in the original output, <code>3C</code> and <code>5E</code> are not properly copied over from the source.</p>\n<p><a href=\"https://i.stack.imgur.com/Bj438.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Bj438.png\" alt=\"test-output\" /></a></p>\n<p><em>Note: top left cell is cell A1</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T06:11:19.050",
"Id": "481432",
"Score": "2",
"body": "Very cleaver. I never would have thought to handle multiple areas."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:01:42.233",
"Id": "245166",
"ParentId": "245014",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245058",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T21:37:36.940",
"Id": "245014",
"Score": "2",
"Tags": [
"vba"
],
"Title": "vba Copy Paste Transpose Link"
}
|
245014
|
<p>I have this api endpoint where i want to lookup a user or multiple users schedule and also specify the month or/and the day when doing the query. My code works, but i feel like there is a better, cleaner way to do this.</p>
<p>From the frontend i do a get request that has the following query params.</p>
<pre><code>http://localhost:5000/api/schedule/?name=John Doe&name=Sam Smith&month=July 2020&day=Wed Jul 15 2020 00:00:00 GMT+0300
</code></pre>
<p>then this api controller will take the req.query obj and use it to do a custom query. I wanted the options like month or day to be optional and still get a result if they are omitted.</p>
<pre><code> exports.find_by_query = async (req, res) => {
let day;
let month;
let name;
const query = [{ $match: {} }];
const filter = { name: {} };
if (req.query.name) {
name = req.query.name;
filter.name = { $in: name };
query[0].$match = filter;
}
if (req.query.day) {
const date = new Date(req.query.day);
date.setHours(0, 0, 0, 0);
day = date.toString().split("(Eastern European Summer Time)")[0].trim();
}
if (req.query.month) {
month = req.query.month;
}
if (month !== undefined && day === undefined) {
query.push({
$group: {
_id: `$shifts.${month}`,
count: { $sum: 1 },
result: { $push: { name: "$name" } },
},
});
}
if (day !== undefined) {
query.push({
$group: {
_id: `$shifts.${month}.${day}`,
count: { $sum: 1 },
result: { $push: { name: "$name", shift: `$shifts.${month}.${day}` } },
},
});
}
Schedule.aggregate(query, function (err, user) {
if (err) {
res.send(err);
}
res.json(user);
});
};
</code></pre>
<p>This is what the returned json looks like for one user, without specifying the month or day.</p>
<pre><code>[
{
"_id": "5f00b12a1607ad69f866cc49",
"name": "John Doe",
"shifts": {
"July 2020": {
"Wed Jul 01 2020 00:00:00 GMT+0300": {
"start": "09:00 AM",
"end": "06:00 PM"
},
"Thu Jul 02 2020 00:00:00 GMT+0300": {
"start": "09:00 AM",
"end": "06:00 PM"
},
"Fri Jul 03 2020 00:00:00 GMT+0300": {
"start": "09:00 AM",
"end": "06:00 PM"
},
"Sat Jul 04 2020 00:00:00 GMT+0300": {
"start": "DO",
"end": "DO"
},
</code></pre>
<p>So while this works, i feel that there's too many steps and doesn't look readable enough.</p>
<p><strong>EDIT: I modified the original code so that i get something more organize sent back to the req. I'm only interested in getting back the names with their schedule and not the other fields. It looks very messy IMO but i don't know how else to clean it up.</strong></p>
<pre><code>exports.find_by_query = async (req, res) => {
let day;
let month;
let name;
const query = [{ $match: {} }];
const filter = { name: {} };
if (req.query.name) {
name = req.query.name;
filter.name = { $in: name };
query[0].$match = filter;
}
if (req.query.day) {
const date = new Date(req.query.day);
date.setHours(0, 0, 0, 0);
day = date.toString().split("(Eastern European Summer Time)")[0].trim();
}
if (req.query.month) {
month = req.query.month;
}
//code to get all in results
// count: { $sum: 1 },
// result: { $push: "$$ROOT" }
if (month !== undefined && day === undefined) {
query.push({
$group: {
_id: { name: "$name", shift: `$shifts.${month}` },
count: { $sum: 1 },
result: { $push: { name: "$name" } },
},
});
}
if (day !== undefined) {
query.push(
{
$group: {
_id: { name: "$name", shift: `$shifts.${month}.${day}` },
// count: { $sum: 1 },
// result: {
// $push: { name: "$name", shift: `$shifts.${month}.${day}` },
// },
},
},
{ $sort: { "_id.source": 1 } }
);
}
console.log(query);
Schedule.aggregate(query, function (err, user) {
count = 0;
result = [];
if (err) {
res.send(err);
}
for (let i of users) {
if (i._id.shift.start) {
if (i._id.shift.start === "DO" || i._id.shift.start === "CO") {
result.push({
[i._id.name]: i._id.shift.start,
});
} else {
result.push({
[i._id.name]: `${i._id.shift.start} - ${i._id.shift.end}`,
});
}
} else {
result.push({ [i._id.name]: [] });
for (const [key, value] of Object.entries(i._id.shift)) {
if (value.start === "DO" || value.start === "CO") {
result[count][i._id.name].push({
[key]: value.start,
});
} else {
result[count][i._id.name].push({
[key]: `${value.start} - ${value.end}`,
});
}
}
count++;
}
}
res.json(result);
});
};
</code></pre>
<p>With this query <code>http://localhost:5000/api/schedule/?month=July 2020&day=Wed Jul 06 2020 00:00:00 GMT+0300</code> will return this:</p>
<pre><code>[
{
"user1": "09:00 AM - 04:00 PM"
},
{
"user2": "09:00 PM - 01:00 AM"
},
{
"user3": "DO"
},
{
"user4": "DO"
},
{
"user5": "12:00 AM - 09:00 AM"
},
{
"user6": "DO"
},
</code></pre>
<p>which is exactly what i wanted. If i leave the day out and specify only the month, i get back their schedule for every day of the month in the above format. This data will be easier to use on my frontend but i wish the code to make it work was cleaner, more readable, maybe less steps.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-22T14:38:20.787",
"Id": "508674",
"Score": "0",
"body": "Don't re-invent the wheel, use libraries like [moment.js](https://momentjs.com/docs/). It makes your life much easier."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T22:34:50.490",
"Id": "245015",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"express.js",
"mongodb",
"mongoose"
],
"Title": "What's the proper way to do MongoDB aggregation query with optional parameters?"
}
|
245015
|
<p>I was trying to implement a queue implementing the small size optimization. I was wondering any ways I can make this code better (more performant, better code style, etc). It seems to work fine (in terms of correctness).</p>
<p>For reference, Global::specifyError is my error handling mechanism for the project, Global's allocate is right now just implemented with new.</p>
<p>Thank you!</p>
<p>Code:</p>
<pre><code>#ifndef QUEUE_HPP
#define QUEUE_HPP
#include "Error.h"
#include "Allocator.h"
#include <cstddef>
#include <algorithm>
namespace Utils {
template<typename T>
class Queue {
private:
static const int FLAG_POS = (sizeof(size_t)*8)-1;
static const size_t FLAG_SFT = 1ULL << FLAG_POS;
static const size_t MAX_CAPACITY = (1ULL << FLAG_POS-1)-1;
protected:
T* start;
size_t _front;
size_t _back;
size_t length;
size_t capacity; // bit manipulation to encode stack/heap.
Queue(T* st, size_t f, size_t b, size_t l, size_t c){
if(__builtin_expect(c > MAX_CAPACITY,false)){
Global::specifyError("Queue requested more than 1 << sizeof(size_t)-2 capacity.");
throw Global::MemoryRequestError;
}
_front = f;
_back = b;
start = st;
length = l;
capacity = c;
}
~Queue(){
}
public:
// no code reuse with Vector, too many different things.
void push_back(T val){
const bool heap = capacity>>FLAG_POS;
const bool leqc = (length&FLAG_SFT-1) >0 && _front == _back;
enum:char {STACK_PUSH, STACK_MOVE_HEAP, HEAP_PUSH, HEAP_GROW};
switch((heap<<1)+leqc){
case STACK_MOVE_HEAP:
case HEAP_GROW:
{
if(__builtin_expect(length*2 > MAX_CAPACITY,false)){
Global::specifyError("Vector requested more than (1 << sizeof(size_t)-2)-1 capacity.");
throw Global::MemoryRequestError;
}
T* aux = Global::getAllocator()->allocate<T>(length*2);
std::copy(start+_front, start+capacity, aux);
std::copy(start, start+_back, aux+capacity-_front);
capacity = FLAG_SFT+length*2;
if(__builtin_expect((heap<<1)+leqc==HEAP_GROW,true)){
Global::getAllocator()->deallocate<T>(start);
}
start = aux;
_front = 0;
_back = length;
}
case STACK_PUSH:
case HEAP_PUSH:
++length;
start[_back++] = val;
_back &= capacity-1;
break;
// no default case.
}
}
void pop_front(){
--length;
++_front;
_front &= capacity-1;
}
int size() const {
return length;
}
T front() const {
return start[_front];
}
};
/*based on Chandler Carruth's talk at CppCon 2016 */
/** Type T, threshold for stack allocation N.*/
template<typename T, size_t N>
class SmallQueue : public Queue<T> {
private:
static constexpr size_t nextPow2(const size_t curr){
size_t s = curr;
--s;
s |= s >> 1;
s |= s >> 2;
s |= s >> 4;
s |= s >> 8;
return s+1;
}
// should get replaced with literal value.
T buffer[nextPow2(N)];
public:
SmallQueue() : Queue<T> (buffer, 0, 0, 0, nextPow2(N)) {
}
~SmallQueue(){
if(this->capacity > nextPow2(N)){
Global::getAllocator()->deallocate<T>(this->start);
}
}
};
}
#endif
</code></pre>
<p>Code where it is used (a BFS)</p>
<pre><code>void Expr::print(const int width, std::ostream& out){
/* some code */
Utils::SmallQueue<QueueItem,100> queue;
QueueItem inp = {this,0,0};
queue.push_back(inp);
int currHeight = -1;
int currJustif = 0;
while(queue.size() > 0) {
QueueItem obj = queue.front();
//std::cerr << "xJust: " << obj.xJust << "h: " << obj.height << '\n';
queue.pop_front();
/* more code */
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T23:06:20.590",
"Id": "481092",
"Score": "1",
"body": "Can you please add any unit test code you have so that we can see how the queue is used. This helps us provide a better code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T01:50:00.607",
"Id": "481096",
"Score": "1",
"body": "Hi, I don't have any unit test code, I just have the code where it's being used. I'll post that on the question. Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T15:15:27.850",
"Id": "481123",
"Score": "1",
"body": "This is not a \"small size optimization\" like you get with `std::string()`, instead you are implementing a queue that does static allocation (as in, it does not dynamically allocate memory from the heap), so that it can live completely on the stack."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T22:59:17.703",
"Id": "245016",
"Score": "1",
"Tags": [
"c++",
"queue"
],
"Title": "Implementing a Queue with Small size optimization"
}
|
245016
|
<p>Please critique the following code on removing a node from a singly linked list, at the moment it seems to me like the code is quite clunky.</p>
<pre class="lang-c prettyprint-override"><code>typedef struct Node {
int data;
struct Node* next;
}Node;
Node* create(int A[], int n){
Node *head = malloc(sizeof(Node));
Node *temp = NULL;
Node *tail;
head->data = A[0];
head->next = NULL;
tail = head;
int i;
for (i = 1; i < n; i++){
temp = malloc(sizeof(Node));
temp->data = A[i];
temp->next = NULL;
tail->next = temp;
tail = temp;
}
return head;
}
void delete(Node** head, int index) {
Node* temp;
Node* curr;
Node* prev = NULL;
curr = *head;
int pos;
if (*head == NULL) {
return;
}
if (index == 0) {
temp = curr->next;
*head = temp;
free(curr);
}
else {
for (pos = 0; pos < index; pos++) {
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
free(curr);
}
}
int main(){
int A[] = {3, 5, 7, 9, 10};
Node *head = create(A, 5);
delete(&head, 1);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Mark variables that will remain constant as <code>const</code>.</li>\n<li>Initialise variables right away when they're created, if possible. You're just adding one extra line with no benefit.</li>\n<li>Limit the scope of variables by creating them only when they're required, not at the top. They'll go unused in certain conditions. Also one won't have to sanity check the whole function to see if the variable has been modified since it was created.</li>\n<li>Use a more descriptive function name. <code>del_node_at_index</code> is even better.</li>\n</ul>\n<pre><code>void delete_node(Node **head, const int index)\n{\n // Initialise curr when it's defined. \n Node *curr = *head;\n\n if (head == NULL) {\n return;\n }\n if (index == 0) {\n // Keep the scope of temp limited.\n // Initialise temp when it's defined.\n Node *temp = curr->next;\n *head = temp;\n free(curr);\n }\n else {\n // Keep the scope of prev limited. \n Node *prev;\n // Define pos if and when needed.\n for (int pos = 0; pos < index; pos++) { \n prev = curr;\n curr = curr->next;\n }\n prev->next = curr->next;\n\n free(curr);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T20:57:28.973",
"Id": "481157",
"Score": "1",
"body": "What does your code for 'delete' do if index is larger than the number of items in the list??? If it is negative?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T21:36:47.203",
"Id": "481162",
"Score": "0",
"body": "yes i have to fix that too"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T08:40:09.593",
"Id": "481206",
"Score": "0",
"body": "@user1666959 I suppose that is a question for PyWalker27 (which they replied to) . I didn't check the correctness of the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T08:41:33.137",
"Id": "481207",
"Score": "0",
"body": "@PyWalker27 Is the `index` a one-based indexing or zero-based ? i.e.: if you want to delete the first node, would you pass `0` or `1` as the `index` argument ? I'd suggest keeping it zero-based."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T08:55:42.593",
"Id": "481210",
"Score": "0",
"body": "I would pass 0."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T06:50:59.420",
"Id": "245023",
"ParentId": "245017",
"Score": "6"
}
},
{
"body": "<p>@akki covered most of what can be done, however, the best reason to rename the function is that C can be easily ported to C++, and <code>delete</code> is a key word in the C++ language. Avoid using C++ key words in C when possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T19:57:08.817",
"Id": "481148",
"Score": "1",
"body": "oo i didn't notice that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T20:06:17.780",
"Id": "481151",
"Score": "1",
"body": "@PyWalker27 that's what code reviews are for."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T13:50:50.487",
"Id": "245035",
"ParentId": "245017",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "245023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-04T23:04:44.007",
"Id": "245017",
"Score": "2",
"Tags": [
"c",
"linked-list"
],
"Title": "Deleting a node in a singly linked list?"
}
|
245017
|
<p>I have been working for a few days on writing <code>get</code>, <code>set</code>, and <code>clear</code> bitwise functions in JavaScript to clear not individual bits from an integer <code>n</code>, but to clear entire <em>ranges</em> of bits in <code>n</code>.</p>
<p>For example, using the functions below, I would expect this behavior:</p>
<pre><code>getNumBits(0b101) // 3
getNumBits(0b10100000) // 8
// getBitRange(integer, startIndex, size)
getBitRange(0b101110010001111, 1, 4) // 1110
getBitRange(0b101110010001111, 5, 7) // 1
// setBitRange(integer, startIndex, value)
setBitRange(0b101110010001111, 5, 0b1001) // 0b101111001001111
// clearBitRange(integer, startIndex, size)
clearBitRange(0b101110010001111, 5, 5) // 0b101110000001111
clearBitRange(0b101110010001111, 2, 3) // 0b100000000001111
</code></pre>
<p>How can I optimize these functions by removing or reordering any of the operations? Can we cut out any steps? I did my best to figure out how to just barely implement the function, but I am no master at bit operations yet. Wondering if one could rewrite these 4 functions to make them more optimal. Please keep each instruction on its own line so it's easier to see :)</p>
<pre><code>function getNumBits(n) {
let i = 0
while (n) {
i++
n >>= 1
}
return i
}
function getBitRange(n, l, s) {
let r = 8 - l - s
let p = 1 << p
let o = p - 1
let ol = o << r
let or = o >> l
let om = or & ol
let x = n & om
return x >> r
}
function setBitRange(n, i, x) {
let o = 0xff // 0b11111111
let c = getNumBits(x)
let j = 8 - i // right side start
let k = j - c // right side remaining
let h = c + i
let a = x << k // set bits
let b = a ^ o // set bits flip
let d = o >> h // mask right
let q = d ^ b //
let m = o >> j // mask left
let s = m << j
let t = s ^ q // clear bits!
let w = n | a // set the set bits
let z = w & ~t // perform some magic https://stackoverflow.com/q/8965521/169992
return z
}
function clearBitRange(n, i, c) {
let s = i + c
let r = 8 - s
let p = 1 << 8
let o = p - 1
let j = o >> i
let k = o << r
let h = j & k
let g = ~h
let z = n & g
return z
}
</code></pre>
<p>This is only concerned with 8-bit numbers.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T12:55:10.623",
"Id": "481111",
"Score": "1",
"body": "You have written this in JavaScript, so I am tagging it JavaScript. There is nuance around possible, assumed and undefined behaviour of bit-manipulation between various languages, so a review covering one language is unlikely to cover the rest of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T12:58:10.137",
"Id": "481112",
"Score": "1",
"body": "It looks like your start index assumes index from left-to-right starting with the most significant non-zero bit (?) or maybe starting with the most-significant bit assuming a 16-bit word (?) Which of these is it, and is it strictly necessary? This indexing may be your performance bottleneck and indexing from the right would simplify everything, if it is possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T15:20:36.873",
"Id": "481124",
"Score": "0",
"body": "Yes if I have to change anything to improve the performance that is welcome! I didn't think of indexing from the right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T16:45:38.820",
"Id": "481128",
"Score": "5",
"body": "\"As a side-note, asking for language-agnostic feedback is treading on thin ice, and the only reason I consider this on-topic is that it has a concrete implementation in JavaScript. To clarify a few things I've [asked in meta](https://codereview.meta.stackexchange.com/questions/10517/how-do-we-differentiate-language-agnostic-from-pseudocode).\" - taken from the answer by Reinderien"
}
] |
[
{
"body": "<ul>\n<li>For any of the following suggestions, please do profile them to test the performance difference. Performance is likely to vary across multiple browser implementations of the JavaScript interpretation engine.</li>\n<li>Rather than a loop for <code>getNumBits</code>, try <code>Math.floor(Math.log(n)/LN_2)</code> - or maybe <code>trunc</code> instead of <code>floor</code> - where <code>LN_2</code> is precomputed as <code>Math.log(2)</code>.</li>\n<li>Try to avoid single-letter variables. Your functions are very impenetrable and will be neither legible nor maintainable by anyone else, or by you in a few weeks. In other words, you should not be a human minifier.</li>\n<li>Rewrite your code to assume that the index is zero-based starting from the least-significant bit and going left. This will greatly simplify your code and will obviate calls to <code>getNumBits</code>.</li>\n</ul>\n<p>Example implementations:</p>\n<pre><code>const LN_2 = Math.log(2);\n\nfunction getNumBits(n) {\n return Math.trunc(Math.log(n) / LN_2) + 1;\n}\n\nfunction getBitRange(n, startIndex, size) {\n return (n >> startIndex) & ((1 << size) - 1);\n} \n\nfunction setBitRange(n, startIndex, size, value) {\n const mask = (1 << size) - 1;\n return (\n n & ~(mask << startIndex)\n ) | ((value & mask) << startIndex);\n}\n\nfunction clearBitRange(n, startIndex, size) {\n const mask = (1 << size) - 1;\n return n & ~(mask << startIndex);\n}\n</code></pre>\n<p>A comment about <code>getNumBits</code> and the alternate implementation offered by @potato. That one is indeed faster than calls to <code>log</code>; a local test of mine using Node and 10,000,000 iterations indicates by a factor of about 16. But that needs to be taken with a grain of salt.</p>\n<p>If you're (for some reason) doing a massive amount of client-side data processing and needing to call this function many thousands of times, it might be justified (with HEAVY commenting) to use the bit-twiddle method. In all other cases, I don't recommend using something that's so obscure and difficult-to-understand.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T17:30:06.830",
"Id": "481135",
"Score": "0",
"body": "Writing the variables is outside of what my question was. Besides, I find what I did more readable than every example I've seen, such as `return (n & ~((0xff << (8 - c)) >> i)) | (x << (8 - c - i))`, which is definitely impenetrable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T17:53:06.580",
"Id": "481136",
"Score": "0",
"body": "Wow you greatly simplified that! Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T18:35:12.650",
"Id": "481140",
"Score": "0",
"body": "Could I be right, if I claim that you don't need the `mask` in this section: `((value & mask) << startIndex` of `setBitRange()`, so that you could simplify it to: `return clearBitRange(n, startIndex, size) | (value << startIndex);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T18:37:12.853",
"Id": "481141",
"Score": "0",
"body": "It's unsafe. If you accept a `size`, then the implication (that you should document) is that `value` will be masked to `size`. The inverse will produce a slower function: do not accept a `size`, in which case you would not need to mask this but you would need to figure out the size of `value`. The implementation shown here could also be a feature: someone might want the explicit `size`-based mask."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T16:35:38.150",
"Id": "245041",
"ParentId": "245027",
"Score": "8"
}
},
{
"body": "<p>There is a more efficient way to implement <code>getNumBits</code> (compared to @Reinderien's answer), if you use some bitwise magic:</p>\n<pre><code>function getNumBits(x){\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x -= (x >> 1) & 0x55555555;\n x = ((x >> 2) & 0x33333333) + (x & 0x33333333);\n return (((x >> 4) + x) & 0x0f0f0f0f) * 0x01010101 >> 24;\n}\n</code></pre>\n<p>The first part (the <code>|=</code> operations) overlay the number with it's own bit shifts in order to turn all the bits into 1-bits except the bits to the left of the left-most 1-bit. Then the second part counts these 1-bits using <a href=\"https://www.playingwithpointers.com/blog/swar.html\" rel=\"nofollow noreferrer\">this algorithm</a>.</p>\n<p>If you know that the number of bits is going to have an upper limit in some specific cases, then you can write even shorter functions to use in these cases. All you need is to understand how this bit count algorithm works.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T22:36:02.823",
"Id": "481166",
"Score": "0",
"body": "Aside from the comments I wrote about this approach contrasting to use of `log` in my own answer - this will fall over for 64-bit numbers, or indeed anything above 32."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T07:36:29.813",
"Id": "481197",
"Score": "0",
"body": "@Reinderien Yeah I wrote a 32 bit integer solution, but this can be modified to work with 64 bit integers too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T08:11:39.677",
"Id": "481201",
"Score": "0",
"body": "Though I should add to this: javascript doesn't actually support 64 bit integers. (see `Number.MAX_SAFE_INTEGER`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-11T12:27:27.373",
"Id": "502010",
"Score": "0",
"body": "This counts the number of set bits, while Lance Pollard's (and \"the log approach\") yield the number of indispensable bits/position of most significant 1."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T20:27:29.023",
"Id": "245047",
"ParentId": "245027",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245041",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T10:37:45.937",
"Id": "245027",
"Score": "5",
"Tags": [
"javascript",
"performance",
"algorithm",
"integer",
"bitwise"
],
"Title": "How to optimize bitwise get/set/clear of ranges of bits on 8-bit integers in JavaScript?"
}
|
245027
|
<p>The task is to write a simplified version of <a href="https://ruby-doc.org/core-2.4.0/String.html#method-i-count" rel="nofollow noreferrer">Ruby's String#count method</a> oneself. Simplified because it doesn't have to have the negation and sequence parts of the original.</p>
<p>Here my solution:</p>
<pre><code>def custom_count(string, search_char)
sum = 0
seg_string = string.split("")
seg_char = search_char.split("")
for i in seg_string
for j in seg_char
if i == j
sum += 1
end
end
end
sum
end
p custom_count("Hello, World!", "l") # => 3
p custom_count("Hello, World!", "lo") # => 5
p custom_count("Hello, World!", "le") # => 4
p custom_count("Hello, World!", "x") # => 0
p custom_count("Hello, World!", "w") # => 0
p custom_count("Hello, World!", "W") # => 1
</code></pre>
<p>Is there a better way to solve the task? Perhaps without using nested loops?</p>
|
[] |
[
{
"body": "<p>If you can use some ruby <code>String</code> method I would suggest</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def custom_count(string, search_char)\n search_char.split("").inject(0) do |count,pattern|\n string.scan(pattern).size + count\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:36:29.553",
"Id": "481452",
"Score": "0",
"body": "Great! Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T16:56:57.177",
"Id": "245042",
"ParentId": "245029",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245042",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T10:51:00.250",
"Id": "245029",
"Score": "1",
"Tags": [
"algorithm",
"ruby"
],
"Title": "Write your implementation of Ruby's String#count method"
}
|
245029
|
<p>My goal is to make a class that wraps the complexity of OpenCvSharp implementation to show a webcam streaming into a <code>WPF</code> <code>Image</code>. You can find the complete code with a running example (just clone and compile) on <a href="https://github.com/FrancescoBonizzi/WebcamControl-WPF-With-OpenCV" rel="nofollow noreferrer">my Github repository</a>.</p>
<p>The important code is this:</p>
<pre><code>public sealed class WebcamStreaming : IDisposable
{
private System.Drawing.Bitmap _lastFrame;
private Task _previewTask;
private CancellationTokenSource _cancellationTokenSource;
private readonly Image _imageControlForRendering;
private readonly int _frameWidth;
private readonly int _frameHeight;
public int CameraDeviceId { get; private set; }
public byte[] LastPngFrame { get; private set; }
public WebcamStreaming(
Image imageControlForRendering,
int frameWidth,
int frameHeight,
int cameraDeviceId)
{
_imageControlForRendering = imageControlForRendering;
_frameWidth = frameWidth;
_frameHeight = frameHeight;
CameraDeviceId = cameraDeviceId;
}
public async Task Start()
{
// Never run two parallel tasks for the webcam streaming
if (_previewTask != null && !_previewTask.IsCompleted)
return;
var initializationSemaphore = new SemaphoreSlim(0, 1);
_cancellationTokenSource = new CancellationTokenSource();
_previewTask = Task.Run(async () =>
{
try
{
// Creation and disposal of this object should be done in the same thread
// because if not it throws disconnectedContext exception
var videoCapture = new VideoCapture();
if (!videoCapture.Open(CameraDeviceId))
{
throw new ApplicationException("Cannot connect to camera");
}
using (var frame = new Mat())
{
while (!_cancellationTokenSource.IsCancellationRequested)
{
videoCapture.Read(frame);
if (!frame.Empty())
{
// Releases the lock on first not empty frame
if (initializationSemaphore != null)
initializationSemaphore.Release();
_lastFrame = BitmapConverter.ToBitmap(frame);
var lastFrameBitmapImage = _lastFrame.ToBitmapSource();
lastFrameBitmapImage.Freeze();
_imageControlForRendering.Dispatcher.Invoke(() => _imageControlForRendering.Source = lastFrameBitmapImage);
}
// 30 FPS
await Task.Delay(33);
}
}
videoCapture?.Dispose();
}
finally
{
if (initializationSemaphore != null)
initializationSemaphore.Release();
}
}, _cancellationTokenSource.Token);
// Async initialization to have the possibility to show an animated loader without freezing the GUI
// The alternative was the long polling. (while !variable) await Task.Delay
await initializationSemaphore.WaitAsync();
initializationSemaphore.Dispose();
initializationSemaphore = null;
if (_previewTask.IsFaulted)
{
// To let the exceptions exit
await _previewTask;
}
}
public async Task Stop()
{
// If "Dispose" gets called before Stop
if (_cancellationTokenSource.IsCancellationRequested)
return;
if (!_previewTask.IsCompleted)
{
_cancellationTokenSource.Cancel();
// Wait for it, to avoid conflicts with read/write of _lastFrame
await _previewTask;
}
if (_lastFrame != null)
{
using (var imageFactory = new ImageFactory())
using (var stream = new MemoryStream())
{
imageFactory
.Load(_lastFrame)
.Resize(new ResizeLayer(
size: new System.Drawing.Size(_frameWidth, _frameHeight),
resizeMode: ResizeMode.Crop,
anchorPosition: AnchorPosition.Center))
.Save(stream);
LastPngFrame = stream.ToArray();
}
}
else
{
LastPngFrame = null;
}
}
public void Dispose()
{
_cancellationTokenSource?.Cancel();
_lastFrame?.Dispose();
}
}
</code></pre>
<p>The usage is this:</p>
<ul>
<li>Create a WPF page, put an <code>Image</code> control in it</li>
<li>On a "Start" button, create the <code>WebcamStreaming</code> class and <code>await</code> its initialization:</li>
</ul>
<pre><code>_webcamStreaming = new WebcamStreaming(
imageControlForRendering: imageControlReference,
frameWidth: 300,
frameHeight: 300,
cameraDeviceId: cameraDeviceId);
await _webcamStreaming.Start();
</code></pre>
<ul>
<li>To stop it, just call: <code>await _webcamStreaming.Stop();</code></li>
</ul>
<p>Some considerantions:</p>
<ul>
<li>I used a <code>Semaphore</code> to let the caller await for the first frame, useful to show some loading</li>
<li>To render the frame to the <code>WPF</code> <code>Image</code> control I used a synchronous <code>Dispatcher</code>, to avoid frame overlapping, but I'm not sure about that. I think it could cause dealocks, but I never noticed one. Maybe could be better to <strong>run & forget</strong> an <code>InvokeAsync</code> task?</li>
<li>I think I should wait for <code>_previewTask</code> to complete in <code>Dispose</code> method, to avoid disposing something that is in use, but I don't know how to do it without causing deadlocks. Waiting for it would generate deadlock when also waiting for the <code>Dispatcher.Invoke</code> operation to complete.</li>
</ul>
<p>What do you think? Would you make something different? Thanks!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T11:58:04.573",
"Id": "245030",
"Score": "3",
"Tags": [
"c#",
"multithreading",
"wpf",
"opencv"
],
"Title": "OpenCv webcam streaming class for WPF"
}
|
245030
|
<p>I've made a Python Flask app and I have some questions about the structure of the main module (equivalent of <code>index.py</code>).</p>
<p>Here is what it looks like:</p>
<pre><code>from flask import Flask, render_template
import database as db
import weather_forecast as wf
import os
app = Flask(__name__)
@app.route("/")
@app.route("/home")
def home():
return render_template('home.html',
sites=db.create_site_list_sqlite(),
api_key=os.environ.get('GOOGLE_MAPS_JS_API_KEY'))
@app.route("/contact")
def contact():
return render_template('contact.html')
@app.route("/weather_forecast/<climbing_area>/<city_id>/<lat>/<lon>/<weather_site>")
#creates url using climbing area name, city id, lat, lon, and location of weather site
def weather_forecast(climbing_area, city_id, lat, lon, weather_site):
return render_template('weather_forecast.html',
climbing_area=climbing_area,
city_id=city_id,
daily_forecast=wf.format_daily_forecast(city_id),
extended_forecast=wf.format_extended_forecast(city_id),
historical_forecast=wf.get_historical_weather(lat, lon),
dates=wf.get_date_range(),
lat=lat,
lon=lon,
weather_site=weather_site,
sites=db.create_site_list_sqlite(),
api_key=os.environ.get('GOOGLE_MAPS_JS_API_KEY'),
image_url=wf.image_choice(lat, lon, city_id))
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p>I have three pages in my application, <code>home</code>, <code>contact</code>, and a dynamically created <code>weather_forecast</code> url.</p>
<p>Basically, when the <code>home()</code> function runs and renders the home page template, it runs this line: <code>sites=db.create_site_list_sqlite()</code>
The <code>create_site_list_sqlite()</code> function returns a bunch of data from an SQLite database, which is used to populate some <code>a href</code> hyperlinks. When a user clicks on one of those links, it goes to a weather forecast page, created by the <code>def weather_forecast()</code> route. That same data is then used to populate the URL in the proceeding weather forecast page.</p>
<p>My reason for doing this is, it was the best way I could figure out to run the <code>create_site_list_sqlite()</code> function. I could have populated the <code>weather_forecast</code> url by re-running that function but it seemed redundant.</p>
<p>Is this good practice to run the <code>create_site_list_sqlite()</code> function (or any others) as few times as possible?</p>
<p>Also, because I needed several pieces of data from what that function returns (<code>climbing_area</code>, <code>city_id</code>, <code>lat</code>, <code>lon</code>, and <code>weather_site</code>), the url for a weather forecast page is rather long. I personally think its fine but is there some reason to tighten this up if possible, just as an example, here is what one of the weather forecast page URLs looks like:</p>
<pre><code>http://localhost:5000/weather_forecast/Ibex/5538080/38.881/-113.461/Delta
</code></pre>
<p>Thank you for any input.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T13:31:01.420",
"Id": "481114",
"Score": "0",
"body": "Please show your template code."
}
] |
[
{
"body": "<h2>URL</h2>\n<p>URL components should generally appear from "broadest to narrowest" left-to-right. I'm not totally convinced that this is currently the case - the weather site is probably "broader" than the latitude and longitude.</p>\n<p>Is the city within a climbing area, or vice versa? If a climbing area is within (or smaller than) a city, their positions should be reversed.</p>\n<p>How many of those parameters can be inferred from other parameters? If you only specify the city, could default coordinates be inferred? Try to omit as many optional parameters as possible from the path, and move them to query parameters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T13:31:11.423",
"Id": "245034",
"ParentId": "245033",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T13:16:58.733",
"Id": "245033",
"Score": "4",
"Tags": [
"python",
"flask"
],
"Title": "Weather Forecast Web Application"
}
|
245033
|
<p>I have created a program where I first set the size of the array and
how many times I will look for consecutive values, then I fill in the
array and finally I insert the consecutive values, it should look for
the least consecutive value it finds in the array.</p>
<p>consecutive value means the sum of the elements in the array
consecutively.</p>
<p>example:</p>
<pre><code>7 4 // Array size and consecutive values
6 4 2 7 10 5 1 // arrangement
1 3 4 2 // Consecutive values
Answer = 1,12,19,6
</code></pre>
<p>Explanation</p>
<blockquote>
<p>The lowest element of the array is the one in the last position which
is 1, the answer is equal to 1.</p>
<p>the lowest segment is the one furthest to the left 6 4 2, the sum of
which equals 12.</p>
<p>the answer is obtained by choosing segment 6 4 2 7, which equals 19.</p>
<p>there are two segments with a minimum cost equal to 6, segments 4 2
and 5 1.</p>
</blockquote>
<p>How can it be improved?</p>
<pre class="lang-c++ prettyprint-override"><code>#include<iostream>
#include<vector>
using namespace std;
void suma_elementos(int elemento);
vector<int>elementos, consecutivos;
int n, q, consecutivo, total, final = 99999999;
int main()
{
cin >> n >> q;
elementos.resize(n);
consecutivos.resize(q);
for (int i = 0; i < n; i++)
{
cin >> elementos[i];
}
for (int i = 0; i < q; i++)
{
cin >> consecutivos[i];
}
for (int i = 0; i < q; i++)
{
suma_elementos(consecutivos[i]);
for (int j = 0; j < consecutivo; j++)
{
for (int c = 0; c < consecutivos[i]; c++)
{
total += elementos[c + j];
}
if (total < final)
{
final = total;
}
total = 0;
}
cout << final << " ";
//reset
consecutivo = 0;
final = 99999999;
total = 0;
}
return 0;
}
//Suma de elementos
void suma_elementos(int elemento)
{
int proporcion = n;
while (proporcion >= elemento)
{
proporcion--;
consecutivo++;
}
}
</code></pre>
<p>edit 1:The program in small arrangements works well, but in large ones it's very slow</p>
<p>edit 2:must not have negative numbers in the sequence</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T17:20:57.317",
"Id": "481133",
"Score": "2",
"body": "Since you want to optimise it, can you provide a file with the input values which can give measurable and consistent timings in the profiler ? Also to save the manual typing, and the delay introduced because of that, please add the code that reads from a file. Right now, `cin >> valor; \n recorrido.push_back(valor);` this block cannot be profiled correctly, since time taken by a human to enter a number is far more than the time a `push_back` takes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T18:58:34.103",
"Id": "481144",
"Score": "2",
"body": "If this is a programming challenge, can you please add the `programming-challenge` flag and add a link to the challenge. Nice question otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T21:42:28.123",
"Id": "481163",
"Score": "1",
"body": "Please post a samlpe, or two, input that shows that the program is slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T21:49:50.053",
"Id": "481165",
"Score": "1",
"body": "Also, is it possible to have negative numbers in the sequence?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T22:49:25.343",
"Id": "481167",
"Score": "1",
"body": "@akki That is not quite correct, as the contents of a file can be piped in to stdin. Reading from stdin with cin is a better choice, as you can profile with many different input files without recompiling, whereas reading from a hardcoded file makes testing and profiling much more cumbersome."
}
] |
[
{
"body": "<ul>\n<li><p>Avoid globals. <code>consecutivo</code> is particularly confusing. It is too easy to miss the fact that it is reset to 0 at each iteration. Always prefer returning a value:</p>\n<pre><code>int suma_elementos(int elemento)\n{\n int proporcion = n;\n int consecutivo = 0;\n while (proporcion >= elemento)\n {\n proporcion--;\n consecutivo++;\n }\n return consecutivo;\n}\n</code></pre>\n<p>and use it in your loop as</p>\n<pre><code> int consecutivo = suma_elementos(consecutivos[i]);\n</code></pre>\n</li>\n<li><p>Now it is obvious that <code>suma_elementos</code> does not really need to loop. You have an invariant <code>proporcion + consecutivo == n</code>. At the end of the last iteration you also have <code>proporcion == elemento</code>, which means that <code>consecutivo = n - elemento</code>. In other words,</p>\n<pre><code>int suma_elementos(int elemento)\n{\n return n - elemento;\n}\n</code></pre>\n</li>\n<li><p>Now I would rather not bother to have <code>suma_elementos</code> at all (besides, with my poor Spanish I have an impression that the name is rather misleading). The loop would become</p>\n<pre><code> for (int j = 0; j < n - consecutivos[i]; j++)\n</code></pre>\n<p>Honestly, it is much easier to understand.</p>\n</li>\n<li><p><code>final = 99999999;</code> is very fragile. Consider a ramp-up loop:</p>\n<pre><code> final = 0;\n for (int j = 0; j < consecutivos[i]; j++) {\n total += elementos[j];\n }\n</code></pre>\n</li>\n<li><p>Your code complexity is <span class=\"math-container\">\\$O(n*k)\\$</span> (<code>k</code> being a width of the window). Notice that after the ramp-up you don't need to recompute the sums of <code>k</code> elements: as the window shifts, one element enters, another leaves:</p>\n<pre><code> final = total;\n for (int leave = 0, enter = base[i]; enter < n; leave++, enter++) {\n total += elementos[enter] - elementos[leave];\n if (total < final) {\n final = total;\n }\n }\n</code></pre>\n<p>obtaining <span class=\"math-container\">\\$O(n + k)\\$</span> complexity.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:57:34.060",
"Id": "245059",
"ParentId": "245038",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "245059",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T15:09:52.883",
"Id": "245038",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"array",
"vectors"
],
"Title": "Find lowest consecutive value"
}
|
245038
|
<p>I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!</p>
<h3>Problem</h3>
<blockquote>
<p>A message containing letters from A-Z is being encoded to numbers
using the following mapping way:</p>
<pre><code>'A' -> 1
'B' -> 2
...
'Z' -> 26
</code></pre>
<p>Beyond that, now the encoded string can also contain the character
'*', which can be treated as one of the numbers from 1 to 9.</p>
<p>Given the encoded message containing digits and the character '*',
return the total number of ways to decode it.</p>
<p>Also, since the answer may be very large, you should return the output
mod <span class="math-container">\$10^9 + 7\$</span>.</p>
<h3>Example 1:</h3>
<ul>
<li>Input: "*"</li>
<li>Output: 9</li>
<li>Explanation: The encoded message can be decoded to the string: "A", "B", "C", "D", "E", "F", "G", "H", "I".</li>
</ul>
<h3>Example 2:</h3>
<ul>
<li>Input: "1*"</li>
<li>Output: 9 + 9 = 18</li>
</ul>
<h3>Example 3:</h3>
<ul>
<li>Input: "2*"</li>
<li>Output: 15</li>
</ul>
<h3>Example 4:</h3>
<ul>
<li>Input: "3*"</li>
<li>Output: 9</li>
</ul>
<h3>Example 5:</h3>
<ul>
<li>Input: "44*4"</li>
<li>Output: 11</li>
</ul>
<h3>Note:</h3>
<ul>
<li>The length of the input string will fit in range [1, 105].</li>
<li>The input string will only contain the character '*' and digits '0' - '9'.</li>
</ul>
</blockquote>
<h3>Code</h3>
<pre><code>#include <string>
#include <vector>
class Solution {
static constexpr size_t MOD = 1e9 + 7;
public:
static size_t numDecodings(const std::string message);
static size_t decode(const char a_num_ast);
static size_t decode(const char a_num_ast, const char b_num_ast);
};
inline size_t Solution::decode(const char a_num_ast) {
if (a_num_ast == '*') {
return 9;
} else if (a_num_ast == '0') {
return 0;
} else {
return 1;
}
}
inline size_t Solution::decode(const char a_num_ast, const char b_num_ast) {
if (a_num_ast == '1') {
if (b_num_ast == '*') {
return 9;
} else if (b_num_ast >= '0' && b_num_ast <= '9') {
return 1;
}
} else if (a_num_ast == '2') {
if (b_num_ast == '*') {
return 6;
} else if (b_num_ast >= '0' && b_num_ast <= '6') {
return 1;
}
} else if (a_num_ast == '0') {
return 0;
} else if (a_num_ast == '*') {
return decode('1', b_num_ast) + decode('2', b_num_ast);
}
return 0;
}
inline size_t Solution::numDecodings(const std::string message) {
const size_t length = message.size();
std::vector<size_t> decodes_dp(3, 0);
decodes_dp[0] = 1;
decodes_dp[1] = decode(message[0]);
for (size_t index = 2; index <= length; index++) {
decodes_dp[index % 3] = (decodes_dp[(index - 1) % 3] * decode(message[index - 1]) % MOD +
decodes_dp[(index - 2) % 3] * decode(message[index - 2], message[index - 1]) % MOD) % MOD;
}
return decodes_dp[length % 3];
}
</code></pre>
<h3>References</h3>
<ul>
<li><p><a href="https://leetcode.com/problems/decode-ways-ii/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/decode-ways-ii/solution/" rel="nofollow noreferrer">Solution</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/decode-ways-ii/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Make helper functions <code>private</code></h1>\n<p>Member functions that are not part of the public API should be marked <code>private</code>.\nYou should know that by now :)</p>\n<h1>Use <code>uint64_t</code> instead of <code>size_t</code></h1>\n<p>There is no guarantee that <code>size_t</code> is big enough for the calculations you are doing. While you might only need 32 bits to store the results, you need to do the calculations using 64 bit integers (because you are multiplying two numbers that are each up to 30 bits in size). So to be safe, I would use <code>uint64_t</code>. You could use <code>uint32_t</code> as well, but then you need to explicitly cast to <code>uint64_t</code> before doing the multiplications inside <code>numDecodings()</code>.</p>\n<p>Use <code>size_t</code> for sizes and counts, but not for other purposes.</p>\n<h1>Make the <code>decode()</code> functions <code>constexpr</code></h1>\n<p>I see you made <code>MOD</code> <code>constexpr</code>, which is great, but you can make the <code>decode()</code> functions <code>constepxr</code> as well.</p>\n<h1>Naming things</h1>\n<p><code>a_num_ast</code> and <code>b_num_ast</code> are weird looking names. I'm guessing by <code>a_num_ast</code> you mean "<strong>a</strong> variable that can hold a <strong>num</strong>ber or an <strong>ast</strong>erisk". But you shouldn't try to encode the type in the variable name. Just use <code>a</code> and <code>b</code> here.</p>\n<p>What does <code>decodes_dp</code> mean? I would try to give it a better name. Use nouns for variables. Perhaps <code>number_of_possibilities</code>, or <code>num_decodings</code> (although that almost clashes with the function name).</p>\n<h1>Use <code>std::array</code> for fixed-length vectors</h1>\n<p>This avoids unnecessary heap allocations. So:</p>\n<pre><code>std::array<uint64_t, 3> decodes_dp{1, decode(message[0]), 0};\n</code></pre>\n<h1>Remove unnecessary modulo operations</h1>\n<p>In the following expression:</p>\n<pre><code>decodes_dp[index % 3] = (\n decodes_dp[(index - 1) % 3] * decode(message[index - 1]) % MOD +\n decodes_dp[(index - 2) % 3] * decode(message[index - 2], message[index - 1]) % MOD\n ) % MOD;\n</code></pre>\n<p>Since you already need to use <code>uint64_t</code> for the result of the multiplications to not wrap, you don't need the modulo operations inside the outermost parentheses.</p>\n<h1>Consider using <code>switch</code>-statements</h1>\n<p>Your <code>decode()</code> functions can be rewritten as follows:</p>\n<pre><code>inline uint64_t Solution::decode(const char a) {\n switch(a) {\n case '0':\n return 0;\n case '*':\n return 9;\n default:\n return 1;\n }\n}\n\ninline uint64_t Solution::decode(const char a, const char b) {\n switch(a) {\n case '0':\n return 0;\n case '1':\n return b == '*' ? 9 : 1;\n case '2':\n switch(b) {\n case '0'...'6':\n return 1;\n case '*':\n return 6;\n default:\n return 0;\n }\n case '*':\n return decode('1', b) + decode('2', b);\n default:\n return 0;\n }\n}\n</code></pre>\n<p>It's more compact and avoids repeating a lot of <code>if (a_num_ast ...)</code>, making it easier to see the structure of your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T07:52:09.857",
"Id": "481318",
"Score": "1",
"body": "Single-letter variable names are fine in some cases. For example, `i`, `j` and `k` for loop indices, `x`, `y` and `z` for coordinates, and even `a` and `b` when you have some generic inputs for which there really is no more descriptive name. Those are commonly used, so they should not be surprising to others reading your code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T14:55:59.087",
"Id": "245083",
"ParentId": "245040",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245083",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T16:25:40.003",
"Id": "245040",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 639: Decode Ways II"
}
|
245040
|
<p>I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!</p>
<h3>Problem</h3>
<blockquote>
<p>Convert a non-negative integer to its English words representation.
Given input is guaranteed to be less than <code>2^31 - 1</code>.</p>
</blockquote>
<h3>Inputs</h3>
<pre><code>123
1234567891
151
1414312
1234
1241234113
</code></pre>
<h3>Outputs</h3>
<pre><code>"One Hundred Twenty Three"
"One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
"One Hundred Fifty One"
"One Million Four Hundred Fourteen Thousand Three Hundred Twelve"
"One Thousand Two Hundred Thirty Four"
"One Billion Two Hundred Forty One Million Two Hundred Thirty Four Thousand One Hundred Thirteen"
</code></pre>
<h3>Code</h3>
<pre><code>#include <string>
class Solution {
std::string zero_to_twenty[20] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
std::string tens_and_zero[10] = {"Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
std::string SPACE = " ";
std::string BILLION = "Billion";
std::string MILLION = "Million";
std::string THOUSAND = "Thousand";
std::string HUNDRED = "Hundred";
std::string ZERO = "Zero";
std::string EMPTY_STRING = "";
static inline constexpr int one_billion = 1e9;
static inline constexpr int one_million = 1e6;
static inline constexpr int one_thousand = 1e3;
static inline constexpr int one_hundred = 100;
static inline constexpr int twenty = 20;
static inline constexpr int ten = 10;
public:
inline std::string numberToWords(int num) {
if (num == 0) {
return ZERO;
} else {
std::string words = int2string(num);
return words.substr(1, words.length() - 1);
}
}
private:
inline std::string int2string(const int n) {
if (n >= one_billion) {
return int2string(n / one_billion) + SPACE + BILLION + int2string(n % one_billion);
} else if (n >= one_million) {
return int2string(n / one_million) + SPACE + MILLION + int2string(n % one_million);
} else if (n >= one_thousand) {
return int2string(n / one_thousand) + SPACE + THOUSAND + int2string(n % one_thousand);
} else if (n >= one_hundred) {
return int2string(n / one_hundred) + SPACE + HUNDRED + int2string(n % one_hundred);
} else if (n >= twenty) {
return SPACE + tens_and_zero[n / ten] + int2string(n % ten);
} else if (n >= 1) {
return SPACE + zero_to_twenty[n];
} else {
return EMPTY_STRING;
}
}
};
</code></pre>
<h3>References</h3>
<ul>
<li><p><a href="https://leetcode.com/problems/integer-to-english-words/" rel="nofollow noreferrer">Problem</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/integer-to-english-words/solution/" rel="nofollow noreferrer">Solution</a></p>
</li>
<li><p><a href="https://leetcode.com/problems/integer-to-english-words/discuss/" rel="nofollow noreferrer">Discuss</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<pre><code>inline std::string int2string(const int n) {\n if (n >= one_billion) {\n return int2string(n / one_billion) + " "+ BILLION + int2string(n % one_billion);\n\n } else if (n >= one_million) {\n return int2string(n / one_million) + " " + MILLION + int2string(n % one_million);\n\n } else if (n >= one_thousand) {\n return int2string(n / one_thousand) + " " + THOUSAND + int2string(n % one_thousand);\n\n } else if (n >= 100) {\n return int2string(n / 100) + " " + HUNDRED + int2string(n % 100);\n\n } else if (n >= 20) {\n return " " + tens_and_zero[n / ten] + int2string(n % 10);\n\n } else if (n >= 1) {\n return " " + zero_to_twenty[n];\n\n } \n return ""; \n}\n</code></pre>\n<p>There isn't much wrong structurally, but i think the changes I made improves readability somewhat.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T02:52:28.243",
"Id": "245064",
"ParentId": "245045",
"Score": "1"
}
},
{
"body": "<p>Take a look at what translating</p>\n<pre><code>1241234113\n</code></pre>\n<p>results in when aligned slightly differently</p>\n<pre><code> One Billion \nTwo Hundred Forty One Million \nTwo Hundred Thirty Four Thousand \nOne Hundred Thirteen \n</code></pre>\n<p>you can see that there are several patterns here.</p>\n<ol>\n<li><p>Every number can be chunked into groups of 3 digits like this <code>1,241,234,113</code>.</p>\n</li>\n<li><p>Each chunk has a different value for the last column, which is one of "Billion", "Million", etc.</p>\n</li>\n<li><p>Within each chunk, there is one digit at the hundreds place.</p>\n</li>\n<li><p>Within each chunk, the last 2 digits have a special case till 20, otherwise it's a special word for the ten's place, and the one's place.</p>\n</li>\n</ol>\n<p>So the only variables you need are just</p>\n<pre><code>std::string const till_twenty[20] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};\nstd::string const tens_place[10] = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};\nstd::string const thousands[4] = {"", "Thousand", "Million", "Billion"};\n</code></pre>\n<p>Note that I've renamed the variables slightly, and made them <code>const</code>. Also, there's no need for the word <code>Zero</code>, since that will only be written if the entire number is 0.</p>\n<p>Now you can build up the functions for the 3 digit chunks</p>\n<pre><code>//for the first digit \nstd::string hundreds_place(int n) {\n return n ? till_twenty[n] + " Hundred " : "";\n}\n \n// for the 2nd and 3rd digit \nstd::string ones_and_tens_place(int n) {\n return n <= 20 ? till_twenty[n] : tens_place[n / 10] + \n (n % 10 ? " " + till_twenty[n % 10] : "")\n}\n\n// putting all 3 digits together\nstd::string by_hundreds(int n) {\n return hundreds_place(n / 100) + ones_and_tens_place(n % 100);\n}\n</code></pre>\n<p>Now you can recursively build the 3 digit numbers by keeping track of which power of 1000 is being currently processed</p>\n<pre><code>std::string by_thousands(int n, int i) { // i keeps track of the chunk\n return n ? by_thousands(n / 1000, i + 1) + \n by_hundreds(n % 1000) + " " \n + thousands[i] + " "\n : "";\n}\n</code></pre>\n<p>and then finally it can all be put together</p>\n<pre><code>std::string numberToWords(int num) {\n std::string res = num ? by_thousands(num, 0) : "Zero ";\n // with a bit of processing to get rid of trailing spaces\n return res.substr(0, res.length() - 2); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T20:25:17.340",
"Id": "245206",
"ParentId": "245045",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245206",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T19:43:00.840",
"Id": "245045",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 273: Integer to English Words"
}
|
245045
|
<p>I am creating a social network and I want to know how secure and clean this code is. I had to update it to prepared statements because I was following a tutorial and even though it was made in 2019 it was using 15 year old code. So can someone tell me if it's good or needs improvement ? Thanks.</p>
<pre><code><?php
include("includes/header.php");
//calls class. You can specify parameters when you define your function to accept input values at run time
$message_obj = new Message($con, $userLoggedIn);
if(isset($_GET['u']))
$user_to = $_GET['u'];
else {
// calls function inside of class
$user_to = $message_obj->getMostRecentUser();
if($user_to == false)
$user_to = 'new';
}
if($user_to != "new")
$user_to_obj = new User($con, $user_to);
if(isset($_POST['post_message'])) {
if(isset($_POST['message_body'])) {
$body = mysqli_real_escape_string($con, $_POST['message_body']);
$date = date("Y=m-d H:i:s");
$message_obj->sendMessage($user_to, $body, $date);
}
}
$user_data_query = $con->prepare('SELECT first_name, last_name, num_likes FROM users WHERE username = ?');
$user_data_query->bind_param("s", $userLoggedIn);
$user_data_query->execute();
$user_data_query_result = $user_data_query->get_result();
while ($row = $user_data_query_result->fetch_assoc()) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$num_likes = $row['num_likes'];
}
$user_data_query_result->close();
$stmt = $con->prepare("SELECT profile_pic FROM users WHERE username = ? ");
$stmt->bind_param("s", $userLoggedIn);
$stmt->execute();
$stmt->bind_result($img);
$stmt->fetch();
$stmt->close();
?>
<style type="text/css">
.convos_column {
background-color: #fff;
padding: 10px;
border: 1px solid #f2f2f2;
border-radius: 7px;
box-shadow: 2px 2px 1px #f2f2f2;
z-index: -1;
word-wrap: normal;
}
#convos {
background-color: #fff;
padding: 10px;
border: 1px solid #f2f2f2;
border-radius: 7px;
box-shadow: 2px 2px 1px #f2f2f2;
z-index: -1;
word-wrap: normal;
width: 30%;
height: 400px;
overflow: scroll;
float: left;
left: -16%;
top: 350px;
position: relative;
}
#convos img {
width: 50px;
height: 50px;
}
#convos p {
top: 10px;
}
.user_detailss {
width: 20%;
height: 310px;
float: right;
position: relative;
right: 95%;
top: 4%;
}
</style>
<head>
<link rel="shortcut icon" type="image/png" href="favicon.ico"/>
</head>
<div class="user_detailss column">
<a href="<?php echo $userLoggedIn; ?>">
<img src="<?php echo $img; ?>" style="border-radius: 5px;" width="130px" height="130px">
</a>
<br><br>
<div class="user_details_left_right">
<a href="<?php echo $userLoggedIn; ?>">
<?php
echo $first_name . " " . $last_name;
?>
</a>
<br>
<br>
<?php echo "Likes: " . $num_likes; ?>
</div>
</div>
<div class="main_column column" id="main_column">
<?php
if($user_to != "new") {
echo "<h4>You and <a href='$user_to'>" . $user_to_obj->getFirstAndLastName() . "</a></h4><hr><br>";
echo "<div class='loaded_messages' id='scroll_messages'>";
echo $message_obj->getMessages($user_to);
echo "</div>";
}
else {
echo "<h4>New Message</h4>";
}
?>
<div class="message_post">
<form action="" method="POST">
<?php
if($user_to == "new") {
echo"Select the friend you would like to message <br><br>";
?>
To: <input type='text' onkeyup='getUsers(this.value, "<?php echo $userLoggedIn; ?>")' name='q' placeholder='Name' style='padding-left: 5px;' autocomplete='off' id='search_text_input'>
<?php
echo "<div class='results'></div>";
} else {
echo "<textarea placeholder='Enter your message...' name='message_body' id='message_textarea'></textarea>";
echo "<input type='submit' name='post_message' class='info' id='message_submit' value='Send Message'>";
}
?>
</form>
<br><br><br>
</div>
<script type="text/javascript">
var div = document.getElementById("scroll_messages");
if(div != null) {
div.scrollTop = div.scrollHeight;
}
</script>
</div>
<div class="user_convos convos_column" id="convos">
<h4>Conversations</h4>
<br>
<div class='loaded_conversations'>
<?php echo $message_obj->getConvos(); ?>
</div>
<a href="messages.php?u=new">New Message</a>
<br><br>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T05:19:32.323",
"Id": "481183",
"Score": "2",
"body": "\"Security\" is meaningless without a detailed threat model. What are you protecting? How much is it worth? Who are you protecting it against? What resources do your attackers have? How much are they willing to spend? How much are *you* willing to spend defending against attacks? For example, there is no point in securing your server, if an attacker can simply kidnap your girlfriend and force you to give them root access. There is no point in having a firewall if an attacker can simply bribe the cleaning lady in the server room and get physical access. https://xkcd.com/538/"
}
] |
[
{
"body": "<ol>\n<li><p>Users can pass whatever they wish into the <code>u</code> field of your form. Even the word <code>new</code> -- there is no defense against someone tricking your script and breaking the intended flow. You will either need to blacklist the <code>u</code> value <code>new</code> or alter your script to not rely on it (use a different flagging mechanism).</p>\n</li>\n<li><p>When determining the value of <code>$user_to</code>, you can use more modern syntax. This will make the step more concise and hopefully you won't find the syntax confusing.</p>\n<pre><code>$user_to = $_GET['u'] ?? $message_obj->getMostRecentUser() ?: 'new';\n</code></pre>\n</li>\n<li><p>When testing if multiple/all specified variables are set and not null, you can write multiple arguments into an <code>isset()</code> call.</p>\n<pre><code>if (isset($_POST['post_message'], $_POST['message_body'])) {\n</code></pre>\n<p>but you should probably put a bit more effort into validating and sanitizing the submission data before allowing it into your system.</p>\n</li>\n<li><p>I do not like your call of <code>mysqli_real_escape()</code>, all of your queries should be relying on prepared statements and bound parameters. This indicates that you probably need to adjust your <code>sendMessage()</code> method.</p>\n</li>\n<li><p><code>date("Y=m-d H:i:s")</code> has a typo, but I don't even recommend that you fix it in php. It will be better that you simply declare that column in your db table to have a default value of the current datetime -- this way you never need to pass a value to that column when you execute an insert query.</p>\n</li>\n<li><p><code>$user_data_query->get_result()</code> produces a result set object, so you can feed it directly into a <code>foreach()</code> and avoid making iterated calls of <code>$user_data_query->get_result()</code>. You can access the associative elements in the same fashion inside the loop.</p>\n</li>\n<li><p>I don't see where <code>$userLoggedIn</code> is coming from. As I work my way down the code, I must assume that this script is being run inside a password protected section of your application. I have to assume that your <code>username</code> values are all unique in this project -- this means there is not a lot of reason to perform a loop on the SELECT query that fetches <code>first_name, last_name, num_likes</code>. Furthermore, I don't see any reason to make a second trip to the same table in the database just to grab the <code>profile_pic</code>. Just add <code>first_name, last_name, num_likes</code> to the <code>profile_pic</code> SELECT and bind all of the column values to variables.</p>\n</li>\n<li><p>Time to clean up the DOM producing portion. Move all of your internal stylesheet to an external stylesheet. Move all of your inline styling to the external stylesheet as well.</p>\n</li>\n<li><p>This doesn't look good to me: <code>getUsers(this.value, "<?php echo $userLoggedIn; ?>")</code>. Am I correct that the end user can just manipulate your source code and fetch data by hardcoding a different value into the 2nd parameter? I think this needs a rethink.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:29:23.470",
"Id": "481169",
"Score": "0",
"body": "So put this in an associative array and then access it using `$rows['']` ?`$body = mysqli_real_escape_string($con, $_POST['message_body']);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:33:37.493",
"Id": "481170",
"Score": "1",
"body": "First, I do not recommend that you accept an answer in the first 24 hours on CodeReview. The person who best reviews your script may be asleep in their timezone when you post. I am perfectly fine with you removing the green tick from my answer. If no better review comes, you can always put it back. I'm recommending using `bind_result()` for your result set variable declarations. `sendMessage()` should be refactored to use a prepared statement (unless it already is -- in which case you don't need to call `real_escape_string()` on values fed to a prepared statement.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:44:59.450",
"Id": "481171",
"Score": "1",
"body": "Yeah it's already in a prepared statement so I did this `$body = $_POST['message_body'];` and it works fine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:46:01.063",
"Id": "481172",
"Score": "0",
"body": "So when do I use `bind_result` and `get_result` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T00:04:00.070",
"Id": "481173",
"Score": "1",
"body": "Kill off the first prepared statement (that whole 13-line block of code) in this script entirely. Only use `SELECT first_name, last_name, num_likes, profile_pic FROM users WHERE username = ?` and assign all 4 variables using the binding technique that you used for `$img`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T00:25:13.960",
"Id": "481175",
"Score": "0",
"body": "If the user types in `u=new` in the URL it just gives them the option to send a new message to someone"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T00:50:10.240",
"Id": "481177",
"Score": "0",
"body": "Is this a good way to validate and sanitize the input ? `$message_body = $_POST['message_body'];\n $body = filter_var($message_body, FILTER_SANITIZE_STRING);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T00:51:32.510",
"Id": "481178",
"Score": "0",
"body": "Or should I use this one ? `$newstr = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T00:55:08.690",
"Id": "481179",
"Score": "0",
"body": "That's a start (you don't need to create new variables). You might like to `strip_tags()` -- it depends on what you are willing to tolerate from your users and what messages you expect to handle. You might do: `$body = trim(htmlentities(strip_tags(filter_var($_POST['message_body'], FILTER_SANITIZE_STRING))));` It's a very subjective decision. Whoops, I should say that `htmlentities()` should only be used when displaying, not when storing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T12:53:00.913",
"Id": "481230",
"Score": "0",
"body": "Ok so what do you recommend I substitute this with ? `getUsers(this.value, \"<?php echo $userLoggedIn; ?>\")`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T14:04:32.483",
"Id": "481240",
"Score": "0",
"body": "Is this good ? `$body = htmlspecialchars(strip_tags(filter_var($_POST['message_body'], FILTER_SANITIZE_STRING )));`"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T21:57:07.777",
"Id": "245053",
"ParentId": "245046",
"Score": "3"
}
},
{
"body": "<h1>Ifs and nesting control loops</h1>\n<p>Maybe this is just me but I would always enclose all <code>if</code> blocks within brackets <code>{}</code> to avoid <strong>ambiguity</strong> and possible logic errors:</p>\n<pre><code>if($user_to != "new")\n $user_to_obj = new User($con, $user_to);\n\n if(isset($_POST['post_message'])) {\n\n if(isset($_POST['message_body'])) {\n\n $body = mysqli_real_escape_string($con, $_POST['message_body']);\n $date = date("Y=m-d H:i:s");\n $message_obj->sendMessage($user_to, $body, $date);\n\n }\n }\n</code></pre>\n<p>Try not to <strong>nest</strong> control loops. Here you have three levels of ifs but it is unnecessary, see below.</p>\n<hr />\n<h1>Expect the unexpected</h1>\n<p>Remember that any site is going to be subjected to automated (and sometimes manual) <strong>attacks</strong>. You have to assume that requests can be tainted.\nWhat I would do first in the code:</p>\n<ol>\n<li>verify that all expected form fields are present in the POST or GET requests</li>\n<li>validate them</li>\n<li>if one or more expected, non-optional fields are missing, then stop execution. This is more likely a malicious attempt (SQL injection, fuzzing) or a truncated request that should be considered corrupt. Your script should not continue if required fields are missing.</li>\n</ol>\n<p>I cannot test your code but I have the impression that it could behave unpredictably if the form submission is manipulated. Not necessarily a security risk but you should test.</p>\n<p>You validate the fields <em>if they are present</em>, which is a good thing. But if they are not, certain parts of your code are not executed. You have to be sure this is what you want and the execution flow will not yield unpleasant surprises.</p>\n<p>So, if you rewrite your code as suggested by doing early validation, you can simplify it. The three levels of nested ifs are no longer necessary: you can get rid of <code>if(isset($_POST['post_message'])) {</code> and <code>if(isset($_POST['message_body'])) {</code> since you've checked for those earlier in your code. And the code suddenly becomes more simple and readable don't you think ?</p>\n<p>Do not repeat stuff like <code>$_POST['message_body']</code>, assign all your $_POST fields to variables instead.</p>\n<hr />\n<h1>Formatting</h1>\n<p>Line spacing is not always consistent, sometimes too much:</p>\n<pre><code>$user_data_query_result->close();\n\n$stmt = $con->prepare("SELECT profile_pic FROM users WHERE username = ? ");\n\n$stmt->bind_param("s", $userLoggedIn);\n\n$stmt->execute();\n\n$stmt->bind_result($img);\n\n$stmt->fetch();\n\n$stmt->close();\n</code></pre>\n<p>Or here:</p>\n<pre><code><div class="user_details_left_right">\n \n <a href="<?php echo $userLoggedIn; ?>">\n\n <?php\n\n echo $first_name . " " . $last_name;\n\n ?>\n\n </a>\n \n <br>\n <br>\n\n <?php echo "Likes: " . $num_likes; ?>\n\n</div>\n</code></pre>\n<p>You can save a few lines = shorter code = less scrolling. Readability and good formatting are important. When the code is hard to understand, bugs or logic errors are more difficult to spot.</p>\n<hr />\n<h1>CSS</h1>\n<p>You have a CSS class named <code>user_detailss</code> but there is <code>user_details_left_right</code>. I am not sure if this is intended or this is a typo. I would call it <code>user_details</code>. I don't see the definition of <code>user_details_left_right</code> in your code so I guess there is a separate style sheet already. Avoid inline CSS.</p>\n<p>Indeed, the style sheet has to be kept separate. Remember, you'll probably have more than one style sheet. Also, users like to customize appearance. Having a choice of layouts and colors is an expected feature. Some sites also have high-contrast style sheets for visually-impaired people.</p>\n<hr />\n<h1>Localization</h1>\n<p>Since you mentioned you are building a social network, <strong>localization</strong> is important. You are going to have users from different countries, with different languages and times zones. I would store all datetime values as UTC and render them to the user in the proper language, with the appropriate offset for their location.</p>\n<p>This is a basic feature that is found in any forum software.</p>\n<hr />\n<h1>Templating</h1>\n<p>You should consider using some sort of <strong>template</strong> system for your pages. Because evolution and maintenance is going to be tedious, unless your project will be no more than a dozen pages (which I doubt). Try to separate code (logic) from layout (presentation) as much as possible.</p>\n<p>Some users will be using a desktop computer, other will be coming from a mobile device. Either go for <strong>responsive design</strong> or be prepared to serve different templates based on the user device. The style sheet can address some of these concerns.</p>\n<p>A very long time ago, I was using HTML pages with tags like %USER_NAME% inside, and a PHP script would load the desired page and replace the tags with appropriate values. Then came solutions like smarty etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T00:17:07.567",
"Id": "481174",
"Score": "0",
"body": "A couple of notes. There are not 3 levels of ifs. There is the first, unbraced one which conditionally executes a single line of code, then there are the 2nd and 3rd ifs which can be converted to a single `isset()` check. I completely agree about consistently using braces. I disagree about declaring variables to store redundant `$_POST` data. There is no overhead saved because there is no processing done. This advice will needlessly bloat the list of variables in the scope with no performance advantage. Leaving the data in the POST array speaks clearly of the origin of the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T13:06:33.783",
"Id": "481234",
"Score": "0",
"body": "Thanks for your answer. I am creating a different site altogether called m.mysite.com"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:48:03.040",
"Id": "245057",
"ParentId": "245046",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245053",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T20:02:57.213",
"Id": "245046",
"Score": "3",
"Tags": [
"php",
"mysql",
"mysqli"
],
"Title": "messages.php file security and efficiency"
}
|
245046
|
<p><strong>Background:</strong><br />
I'm implementing an algorithm from the paper <a href="http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=51D9679503B28E964F70480B9167426D?doi=10.1.1.55.7496&rep=rep1&type=pdf" rel="nofollow noreferrer">Polygon Area Decomposition for Multiple-Robot Workspace Division</a> and one of the steps is to represent a polygon as a graph. This is done by splitting a polygon to convex parts that will become the nodes of the graph, and the edges of the graph will represent those parts that touch each other:</p>
<p><a href="https://i.stack.imgur.com/5DhaD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5DhaD.png" alt="enter image description here" /></a></p>
<p>What I'm required to do by the algorithm is:</p>
<ol>
<li>to have the nodes of the graph ordered as in <a href="https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search_of_binary_tree" rel="nofollow noreferrer">post-order</a> traversal;</li>
<li>to be able to get for a given node all the nodes that go before it in the ordering and that are accessible from the given node without entering the nodes that go after in the ordering (NetworkX calls these nodes <a href="https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.dag.ancestors.html" rel="nofollow noreferrer">ancestors</a>);</li>
<li>to keep information about the touching sides of the polygon parts in some manner so that I wouldn't have to recalculate them again every time.</li>
</ol>
<p>To convert a polygon to a graph was fairly simple. The problems arise when I want to satisfy the given requirements. I wrote the following function that would convert a simple graph to a directed graph with the necessary ordering and which would allow me to easily get ancestors of any given node.</p>
<p><strong>Code:</strong></p>
<pre><code>import networkx as nx
def to_ordered(graph: nx.Graph) -> nx.Graph:
"""
Makes a directed graph out of the input graph.
Nodes will be ordered in a depth-first-search post-ordering.
:param graph: graph representing convex parts of a polygon
:return: directed graph with touching sides as edges' attributes
"""
ordered_graph = nx.DiGraph()
ordered_nodes = list(nx.dfs_postorder_nodes(graph))
ordered_graph.add_nodes_from(ordered_nodes)
directed_edges = (sorted(edge, key=ordered_nodes.index)
for edge in graph.edges)
ordered_graph.add_edges_from(directed_edges)
for *edge, side in graph.edges.data('side'):
if edge in ordered_graph.edges:
ordered_graph.edges[edge]['side'] = side
else:
ordered_graph.edges[edge[::-1]]['side'] = side
return ordered_graph
</code></pre>
<p><strong>Usage example:</strong></p>
<pre><code>import networkx as nx
# Creating an example input graph:
edges = [(5, 4), (5, 1), (3, 5), (2, 3), (6, 2), (1, 6)]
sides = list(map(str, edges)) # example data to keep as attributes
graph = nx.Graph()
for edge, side in zip(edges, sides):
graph.add_edge(*edge, side=side)
nx.draw(graph, with_labels=True)
</code></pre>
<p><a href="https://i.stack.imgur.com/0cRUa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0cRUa.png" alt="enter image description here" /></a></p>
<pre><code># converting to a directed graph with desired characteristics
ordered_graph = to_ordered(graph)
nx.draw(ordered_graph, with_labels=True)
</code></pre>
<p><a href="https://i.stack.imgur.com/veR3a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/veR3a.png" alt="enter image description here" /></a></p>
<pre><code># new graph is ordered according to the post-order graph traversal:
print(ordered_graph.nodes)
# [4, 3, 2, 6, 1, 5]
# finding nodes' ancestors:
for node in ordered_graph.nodes:
print(node, nx.ancestors(ordered_graph, node))
# 4 set()
# 3 set()
# 2 {3}
# 6 {2, 3}
# 1 {2, 3, 6}
# 5 {1, 2, 3, 4, 6}
# accessing edges' attributes:
for edge in ordered_graph.edges:
print(edge, ordered_graph.edges[edge])
# (4, 5) {'side': '(5, 4)'}
# (3, 5) {'side': '(3, 5)'}
# (3, 2) {'side': '(2, 3)'}
# (2, 6) {'side': '(6, 2)'}
# (6, 1) {'side': '(1, 6)'}
# (1, 5) {'side': '(5, 1)'}
</code></pre>
<p><strong>What I want reviewed:</strong><br />
As you can see from the given example the code works correctly, but I find my code too complicated for such a simple task. I especially dislike the part with copying the attributes from one graph to another. Most probably I simply miss some NetworkX functionality that would help me write it much more concisely. Any comments on this or any other matter are welcome.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T20:54:03.633",
"Id": "245049",
"Score": "4",
"Tags": [
"python",
"graph"
],
"Title": "Converting a graph to a directed graph with order of the nodes defined by post-order traversal"
}
|
245049
|
<p>I teach programming, and I currently teach my class about inheritance, abstract classes, and mixins.</p>
<p>I wrote this code as an example, and I want to be sure it is as good as possible before I release it as a code example.</p>
<p>Few assumptions:</p>
<ol>
<li>The code should only handle piece movements and not manage an entire game.</li>
<li>The code shouldn't handle special moves like en-passant, castling, or pawn promotion.</li>
<li>The code shouldn't force the king to move if another piece threatens it.</li>
</ol>
<pre class="lang-py prettyprint-override"><code>from abc import ABC, abstractmethod
class Color:
BLACK = 0
WHITE = 1
def enemy_of(color):
if color == Color.BLACK:
return Color.WHITE
return Color.BLACK
class Board:
BOARD_SIZE = (8, 8)
def __init__(self):
self.reset()
def get_square(self, row, col):
if not self.is_valid_square((row, col)):
return None
return self.board[row][col]
def set_square(self, row, col, piece):
self.board[row][col] = piece
def is_valid_square(self, square):
return (
square[0] in range(self.BOARD_SIZE[0])
and square[1] in range(self.BOARD_SIZE[1])
)
def is_empty_square(self, square):
return self.get_square(*square) is None
def _generate_first_row(self, color):
row_by_color = {Color.BLACK: 0, Color.WHITE: self.BOARD_SIZE[0] - 1}
row = row_by_color[color]
order = (Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook)
params = {'color': color, 'row': row}
return [order[i](col=i, **params) for i in range(self.BOARD_SIZE[0])]
def _generate_pawns_row(self, color):
row_by_color = {Color.BLACK: 1, Color.WHITE: self.BOARD_SIZE[0] - 2}
row = row_by_color[color]
params = {'color': color, 'row': row}
return [Pawn(col=i, **params) for i in range(self.BOARD_SIZE[0])]
def get_pieces(self, color=None):
for row in self.board:
for col in row:
if col is not None and (color is None or col.color == color):
yield col
def get_possible_moves(self, color, with_king=False):
"""Return all player's possible moves."""
pieces = self.get_pieces(color=color)
if not with_king:
pieces = [p for p in pieces if not isinstance(p, King)]
for piece in pieces:
for move in piece.get_valid_moves(self):
yield move
def reset(self):
self.board = [
self._generate_first_row(Color.BLACK),
self._generate_pawns_row(Color.BLACK),
[None] * self.BOARD_SIZE[0],
[None] * self.BOARD_SIZE[0],
[None] * self.BOARD_SIZE[0],
[None] * self.BOARD_SIZE[0],
self._generate_pawns_row(Color.WHITE),
self._generate_first_row(Color.WHITE),
]
def move(self, source, destination):
piece = self.get_square(*source)
return piece.move(board=self, destination=destination)
def __str__(self):
printable = ""
for row in self.board:
for col in row:
if col is None:
printable = printable + " ▭ "
else:
printable = printable + f" {col} "
printable = printable + '\n'
return printable
class Piece(ABC):
def __init__(self, color, row, col, **kwargs):
super().__init__(**kwargs)
self.color = color
self.row = row
self.col = col
def is_possible_target(self, board, target):
is_target_valid = board.is_valid_square(target)
is_empty_square = board.is_empty_square(target)
is_hitting_enemy = self.is_enemy(board.get_square(*target))
return is_target_valid and (is_empty_square or is_hitting_enemy)
@abstractmethod
def get_valid_moves(self, board):
pass
def get_position(self):
return self.row, self.col
def is_enemy(self, piece):
if piece is None:
return False
return piece.color == Color.enemy_of(self.color)
def move(self, board, destination):
if not self.is_possible_target(board, destination):
return False
if destination not in self.get_valid_moves(board):
return False
board.set_square(*self.get_position(), None)
board.set_square(*destination, self)
self.row, self.col = destination
return True
@abstractmethod
def __str__(self):
pass
class WalksDiagonallyMixin:
def __init__(self, **kwargs):
super().__init__(**kwargs)
if not hasattr(self, 'directions'):
self.directions = set()
self.directions.update({
(-1, -1), (1, -1),
(-1, 1), (1, 1),
})
class WalksStraightMixin:
def __init__(self, **kwargs):
super().__init__(**kwargs)
if not hasattr(self, 'directions'):
self.directions = set()
self.directions.update({
(0, -1),
(-1, 0), (1, 0),
(0, 1),
})
class WalksMultipleStepsMixin:
def get_valid_moves(self, board):
for row_change, col_change in self.directions:
steps = 1
stop_searching_in_this_direction = False
while not stop_searching_in_this_direction:
new_row = self.row + row_change * steps
new_col = self.col + col_change * steps
target = (new_row, new_col)
is_valid_target = self.is_possible_target(board, target)
if is_valid_target:
yield target
steps = steps + 1
is_hit_enemy = self.is_enemy(board.get_square(*target))
if not is_valid_target or (is_valid_target and is_hit_enemy):
stop_searching_in_this_direction = True
class Pawn(Piece):
DIRECTION_BY_COLOR = {Color.BLACK: 1, Color.WHITE: -1}
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.moved = False
self.forward = self.DIRECTION_BY_COLOR[self.color]
def _get_regular_walk(self):
src_row, src_col = self.get_position()
return (src_row + self.forward, src_col)
def _get_double_walk(self):
src_row, src_col = self.get_position()
return (src_row + self.forward * 2, src_col)
def _get_diagonal_walks(self):
src_row, src_col = self.get_position()
return (
(src_row + self.forward, src_col + 1),
(src_row + self.forward, src_col - 1),
)
def is_possible_target(self, board, target):
is_valid_move = board.is_valid_square(target)
is_step_forward = (
board.is_empty_square(target)
and target == self._get_regular_walk()
)
is_valid_double_step_forward = (
board.is_empty_square(target)
and not self.moved
and target == self._get_double_walk()
and self.is_possible_target(board, self._get_regular_walk())
)
is_hitting_enemy = (
self.is_enemy(board.get_square(*target))
and target in self._get_diagonal_walks()
)
return is_valid_move and (
is_step_forward or is_valid_double_step_forward or is_hitting_enemy
)
def move(self, **kwargs):
is_success = super().move(**kwargs)
self.moved = True
return is_success
def get_valid_moves(self, board):
targets = (
self._get_regular_walk(),
self._get_double_walk(),
*self._get_diagonal_walks(),
)
for target in targets:
if self.is_possible_target(board, target):
yield target
def __str__(self):
if self.color == Color.WHITE:
return '♙'
return '♟'
class Bishop(WalksDiagonallyMixin, WalksMultipleStepsMixin, Piece):
def __str__(self):
if self.color == Color.WHITE:
return '♗'
return '♝'
class Rook(WalksStraightMixin, WalksMultipleStepsMixin, Piece):
def __str__(self):
if self.color == Color.WHITE:
return '♖'
return '♜'
class Queen(
WalksStraightMixin, WalksDiagonallyMixin, WalksMultipleStepsMixin, Piece,
):
def __str__(self):
if self.color == Color.WHITE:
return '♕'
return '♛'
class Knight(Piece):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.directions = [
(-2, 1), (-1, 2), (1, 2), (2, 1), # Upper part
(-2, -1), (-1, -2), (1, -2), (2, -1), # Lower part
]
def get_valid_moves(self, board):
for row_change, col_change in self.directions:
row, col = self.get_position()
target = (row + row_change, col + col_change)
if self.is_possible_target(board, target):
yield target
def __str__(self):
if self.color == Color.WHITE:
return '♘'
return '♞'
class King(WalksStraightMixin, WalksDiagonallyMixin, Piece):
def _get_threatened_squares(self, board):
enemy = Color.enemy_of(self.color)
enemy_moves = list(board.get_possible_moves(enemy, with_king=False))
enemy_pieces = board.get_pieces(color=enemy)
king = next(p for p in enemy_pieces if isinstance(p, King))
for move in king.get_squares_threatens(board):
yield move
for move in enemy_moves:
yield move
def is_possible_target(self, board, target):
is_regular_valid = super().is_possible_target(board, target)
threatened_squares = self._get_threatened_squares(board)
return is_regular_valid and target not in threatened_squares
def get_valid_moves(self, board):
for add_row, add_col in self.directions:
target = (add_row + self.row, add_col + self.col)
if self.is_possible_target(board, target):
yield target
def get_squares_threatens(self, board):
for direction in self.directions:
row, col = self.get_position()
row = row + direction[0]
col = col + direction[1]
if board.is_valid_square((row, col)):
yield (row, col)
def __str__(self):
if self.color == Color.WHITE:
return '♔'
return '♚'
</code></pre>
<p>Things I know I can improve, but I leave as-is because of my current student's knowledge:</p>
<ol>
<li>I can use <code>yield from</code> instead of <code>for x in y: yield x</code>.</li>
<li>Color can inherit <code>enum.Enum</code> and use <code>enum.auto()</code> for the class variables.</li>
<li>I can raise exceptions instead of returning <code>True</code> or <code>False</code>.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T06:18:41.863",
"Id": "481515",
"Score": "3",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a new question with the revised code, self-answer indicating what you improved and why or share your code in another way. Feel free to add links. But don't add it to the question itself, please. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T12:45:35.363",
"Id": "481547",
"Score": "0",
"body": "Regarding your last point, Returning True or False is likely better than raising errors anyways"
}
] |
[
{
"body": "<p>I would include a comment at the top of the file indicating the version of the relevant software you've used. A quick comment stating "Tested with Python 3.6 (installed through Anaconda)" or something to that effect is nice to make sure everyone is on the same page.</p>\n<hr />\n<p>Since this is intended as teaching example, I will focus on minimizing the current code. I think that it is a reasonable assumption that more code gives more room for potential confusion.</p>\n<pre><code>class Board:\n BOARD_SIZE = (8, 8)\n</code></pre>\n<p>Will you ever have a non-square board? Can this be a simple int? Changing this reduces the overall amount of code by a non-trivially amount.</p>\n<pre><code> def get_square(self, row, col):\n if not self.is_valid_square((row, col)):\n return None\n return self.board[row][col]\n\n def set_square(self, row, col, piece):\n self.board[row][col] = piece\n</code></pre>\n<p>Getters and setters are rare in Python, and since the board is public facing (it isn't prefixed with an underscore like later functions are), the setter doesn't really add much to the code. The getter smells a little bit, since a getter returning None is unexpected, and none of the provided code that uses the getter checks for None. I would remove both.</p>\n<pre><code> def is_valid_square(self, square):\n return (\n square[0] in range(self.BOARD_SIZE[0])\n and square[1] in range(self.BOARD_SIZE[1])\n )\n</code></pre>\n<p>This function is not pleasant to debug if it is used incorrectly. An example of this is the error given if the input parameter 'square' is empty.</p>\n<pre><code>>>> board.is_valid_square([])\nTraceback (most recent call last):\n...\n square[0] in range(self.BOARD_SIZE[0])\nIndexError: list index out of range\n</code></pre>\n<p>Which list is indexed out of range? There are two index operations on the same line. There are also two different uses of the word range, each with different meanings. That could be confusing to a beginner.</p>\n<p>Strictly speaking, the parameter square can be any size, but we expect it to be two elements big. I would make this assumption explicit with code through either an unpacking, an assert, or by changing the function signature.</p>\n<pre><code>def is_valid_square(self, row, col):\n return row in range(self.BOARD_SIZE) and col in range(self.BOARD_SIZE)\n</code></pre>\n<hr />\n<pre><code>def _generate_first_row(self, color):\n row_by_color = {Color.BLACK: 0, Color.WHITE: self.BOARD_SIZE[0] - 1}\n row = row_by_color[color]\n\n order = (Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook)\n params = {'color': color, 'row': row}\n return [order[i](col=i, **params) for i in range(self.BOARD_SIZE[0])]\n</code></pre>\n<p>As a small thing, I would change the name to _generate_back_row. I think that is a slightly more clear name. A quick <a href=\"https://en.wikipedia.org/wiki/Glossary_of_chess#B\" rel=\"noreferrer\">wikipedia search</a> tells me that the exact term to use would be first-rank or back-rank, but that might might not be well enough known.</p>\n<p>This function has a lot going on in it. I think this could be simplified a little, taking advantage of the fact there are only two colours. The dictionary lookup and expanding kwargs from a dictionary are overkill (but are both great things to teach, I would leave them in _generate_pawn). The code could look something like</p>\n<pre><code>def _generate_back_row(self, color):\n row = 0 if color == Color.BLACK else self.BOARD_SIZE - 1\n\n order = (Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook)\n return [\n order[i](col=i, row=row, color=color)\n for i in range(self.BOARD_SIZE[0])\n ]\n</code></pre>\n<hr />\n<pre><code>def get_pieces(self, color=None):\n for row in self.board:\n for col in row:\n if col is not None and (color is None or col.color == color):\n yield col\n</code></pre>\n<p>I think the variable col should be named square. What does color=None mean? Get both colours pieces? The feature isn't used anywhere in the code. I think this function should be made simpler, removing the default parameter. I think it would be more reasonable for the code to look like</p>\n<pre><code>def get_color_pieces(self, color):\n for row in self.board:\n for square in row:\n if square is not None and square.color == color:\n yield square\n</code></pre>\n<hr />\n<pre><code>def get_possible_moves(self, color, with_king=False):\n """Return all player's possible moves."""\n</code></pre>\n<p>The comment is a little confusing. Which player are we talking about? What does with_king mean? I would have expected all possible moves to include those of the king by default. I would suggest something like below, which flips the default, including the possible king moves, but highlighting that the function can optionally not include them.</p>\n<pre><code>def get_possible_moves(self, color, exclude_king=False):\n """Return all possible moves using the pieces of the specified color."""\n</code></pre>\n<hr />\n<pre><code>def is_possible_target(self, board, target):\n is_target_valid = board.is_valid_square(target)\n is_empty_square = board.is_empty_square(target)\n is_hitting_enemy = self.is_enemy(board.get_square(*target))\n return is_target_valid and (is_empty_square or is_hitting_enemy)\n</code></pre>\n<p>This is a good function. The names of the functions it calls make the logic clear and easy to follow. I would consider changing the definition to <code>return is_target_valid and not is_hitting_self</code>, since that would be less work for the computer, but overall this looks really good.</p>\n<pre><code>def is_enemy(self, piece):\n if piece is None:\n return False\n return piece.color == Color.enemy_of(self.color)\n</code></pre>\n<p>This could be slightly more obvious by ending with <code>return piece.color != self.color</code>.</p>\n<hr />\n<pre><code>def get_valid_moves(self, board):\n for row_change, col_change in self.directions:\n steps = 1\n stop_searching_in_this_direction = False\n while not stop_searching_in_this_direction:\n new_row = self.row + row_change * steps\n new_col = self.col + col_change * steps\n target = (new_row, new_col)\n is_valid_target = self.is_possible_target(board, target)\n if is_valid_target:\n yield target\n steps = steps + 1\n is_hit_enemy = self.is_enemy(board.get_square(*target))\n if not is_valid_target or (is_valid_target and is_hit_enemy):\n stop_searching_in_this_direction = True\n</code></pre>\n<p>I would make some small changes to the logic of this function. It has quite a bit of complexity (3 indents, a yield, and an if statement that directly affects the next if statement), so giving it more space whitespace, and inverting some of the booleans might make it a little cleaner and more importantly, easier to parse.</p>\n<p>The first thing to change is to move the inner logic to its own function. This has two benefits, it makes the code a little easier to parse, and it allows the inner logic to stop whenever it needs to, rather than tracking the loop condition explicitly.</p>\n<pre><code>def get_valid_moves(self, board):\n for row_change, col_change in self.directions:\n for move in moves_in_a_direction(self, row_change, col_change):\n yield move\n\ndef moves_in_a_direction(self, row_change, col_change):\n steps = 1\n stop_searching_in_this_direction = False\n while not stop_searching_in_this_direction:\n new_row = self.row + row_change * steps\n new_col = self.col + col_change * steps\n target = (new_row, new_col)\n is_valid_target = self.is_possible_target(board, target)\n if is_valid_target:\n yield target\n steps = steps + 1\n is_hit_enemy = self.is_enemy(board.get_square(*target))\n if not is_valid_target or (is_valid_target and is_hit_enemy):\n stop_searching_in_this_direction = True\n</code></pre>\n<p>is_hit_enemy is only set in the first if statement, it doesn't even exist before then. I would try and keep the logic to the one place (and change the name to has_hit_enemy, as that would be more accurate). To do this, invert the condition to make it a guard clause</p>\n<pre><code>if not is_valid_target:\n return\n\nyield target\nsteps += 1\nhas_hit_enemy = ...\n...\n</code></pre>\n<p>This facilitates the removal of stop_searching_in_this_direction, as it was only used to stop the loop. Since we can return, it becomes unnecessary.</p>\n<pre><code>def moves_in_a_direction(self, row_change, col_change):\n steps = 1\n while True:\n new_row = self.row + row_change * steps\n new_col = self.col + col_change * steps\n target = (new_row, new_col)\n is_valid_target = self.is_possible_target(board, target)\n if not is_valid_target:\n return\n\n yield target\n steps = steps + 1\n\n has_hit_enemy = self.is_enemy(board.get_square(*target))\n if has_hit_enemy:\n return\n</code></pre>\n<hr />\n<pre><code>def _get_regular_walk(self):\n src_row, src_col = self.get_position()\n return (src_row + self.forward, src_col)\n</code></pre>\n<p>This looks ok, but src doesn't really mean anything here. I'd say drop it</p>\n<pre><code>def _get_regular_walk(self):\n row, col = self.get_position()\n return row + self.forward, col\n</code></pre>\n<p>In fact, since each piece knows its own row and column, why do we need self.get_position() anyway? It might be a candidate for deletion.</p>\n<pre><code>def _get_regular_walk(self):\n return self.row + self.forward, self.col\n</code></pre>\n<hr />\n<pre><code>def is_possible_target(self, board, target):\n is_valid_move = board.is_valid_square(target)\n is_step_forward = (\n board.is_empty_square(target)\n and target == self._get_regular_walk()\n )\n is_valid_double_step_forward = (\n board.is_empty_square(target)\n and not self.moved\n and target == self._get_double_walk()\n and self.is_possible_target(board, self._get_regular_walk())\n )\n is_hitting_enemy = (\n self.is_enemy(board.get_square(*target))\n and target in self._get_diagonal_walks()\n )\n return is_valid_move and (\n is_step_forward or is_valid_double_step_forward or is_hitting_enemy\n )\n</code></pre>\n<p>The logic looks good, but it is hard to find it in amongst the code. The more I see is_valid_square, the less I like the name. Consider other names that let you know what the function checks for, such as is_within_bounds or is_inside. I have also noticed that every function which returns a boolean has been prefixed with is_, to an almost pathological degree. There are other prefixes which would be much better suited, like has, can, will, or simply leaving out the prefix. With a guard clause, and changing the prefixes to make more sense, the code might look like</p>\n<pre><code>def is_possible_target(self, board, target):\n is_valid_move = board.is_valid_square(target)\n if not is_valid_move:\n return False\n\n can_step_forward = (\n board.is_empty_square(target)\n and target == self._get_regular_walk()\n )\n\n can_double_step_forward = (\n can_step_forward and\n not self.moved and\n board.is_empty_square(target) and\n target == self._get_double_walk()\n )\n\n can_capture = (\n self.is_enemy(board.get_square(*target))\n and target in self._get_diagonal_walks()\n )\n\n return can_step_forward or can_double_step_forward or can_capture\n</code></pre>\n<hr />\n<pre><code>class King(WalksStraightMixin, WalksDiagonallyMixin, Piece):\n def _get_threatened_squares(self, board):\n enemy = Color.enemy_of(self.color)\n enemy_moves = list(board.get_possible_moves(enemy, with_king=False))\n enemy_pieces = board.get_pieces(color=enemy)\n king = next(p for p in enemy_pieces if isinstance(p, King))\n for move in king.get_squares_threatens(board):\n yield move\n for move in enemy_moves:\n yield move\n</code></pre>\n<p>This is okay, but not as clear as it could be. Rearranging the lines and renaming king to enemy king improves the code.</p>\n<pre><code>class King(WalksStraightMixin, WalksDiagonallyMixin, Piece):\n def _get_threatened_squares(self, board):\n enemy = Color.enemy_of(self.color)\n enemy_moves = list(board.get_possible_moves(enemy, exclude_king=True))\n for move in enemy_moves:\n yield move\n\n enemy_pieces = board.get_pieces(color=enemy)\n enemy_king = next(p for p in enemy_pieces if isinstance(p, King))\n for move in enemy_king.get_squares_threatens(board):\n yield move\n</code></pre>\n<p>But this brings up the question of "Why is the enemy king treated differently?" Surely it is just another enemy piece that has a set of possible moves, each of which threatens this king? If there is something of note here, a comment explaining it would be helpful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T01:50:30.893",
"Id": "481180",
"Score": "10",
"body": "You are awesome. Thank you for the non-trivial amount of effort and the good spirit. I'm sure I'll take many of your advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T17:54:26.627",
"Id": "481673",
"Score": "0",
"body": "*Will you ever have a non-square board?* Will US zip codes ever be more than 5 digits? Will there ever be a need to specify century in dates? Will a person or place name ever be more than *arbitrary number here* characters? Will the customer ever want empty number fields to be null instead of zero? Will a social security number ever be legitimately reused?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-11T20:59:33.847",
"Id": "481773",
"Score": "0",
"body": "@radarbob Zipcodes can be nine digits long, called ZIP+4's, used when specifying a street address or Post Office Box."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T01:13:21.473",
"Id": "245062",
"ParentId": "245050",
"Score": "38"
}
},
{
"body": "<p>Since @spyr03's <a href=\"https://codereview.stackexchange.com/a/245062/98493\">extensive (and awesome) answer</a> did not include it, here are some small comments.</p>\n<p>You want this to be an example for your students of how code should look like. You should include a <code>docstring</code> with every class, method and function to detail what it does and what it's arguments and return value are. Although your code <em>is</em> rather self-documenting, this sets the precedent for when they write their own code. If you consistently do it (and require it of them), some may learn to do it.</p>\n<p>Don't forget to teach them about writing (good) tests either, at least eventually. Especially the pieces would be a good easy candidate for tests. They have complex non-trivial behavior which you could mess up when changing something, so having full test coverage on them would be very helpful.</p>\n<p>On a practical note, I was slightly surprised when I came to the <code>Pawn</code> class. First, you define these nice mixins for the movement types. But then, the <code>Pawn</code> class does not to use any of them! I understand that the pawn is probably the first piece you want to define, and also that it is a bit hard to use the mixins in this case, but I would consider if it wouldn't be better to start with a piece that actually uses one of the mixins. Or define them later, when you actually need them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T04:50:58.710",
"Id": "245066",
"ParentId": "245050",
"Score": "18"
}
},
{
"body": "<p>When I think back to my student days, the most crucial point for me to understand code was always the entry point. In my experience, it takes a lot of experience to understand a code concept as a whole. The untrained is used to step by step thinking and evaluation through step by step progression. I would not have understood that code because it describes the game and does not PLAY the game. I understood, that the code is not meant to play. But a clearly marked <code>start()</code> function initializing the board and doing some sample moves so the student can see and visualize how the code come together and what it can actually do, would help a lot. At least it would have helped me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T03:55:30.767",
"Id": "481312",
"Score": "3",
"body": "\"Yes, and...\" If you take that code that \"initializes the board and does some sample moves\" and then add a few `assert`s at the end — ta-da, you have your first unit test! Unit tests can help the reader understand the behavior of the code, *and* its intended usage, *and* serve as, well, *tests*, all at the same time. Highly recommended."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:45:48.270",
"Id": "245071",
"ParentId": "245050",
"Score": "14"
}
},
{
"body": "<p>One thing I don't see mentioned in spyr03's excellent review: I think it's unnecessarily inconsistent (and thus confusing) for you to use mixin classes to implement 100% of the <code>get_valid_moves</code> routine for <code>Rook</code>, <code>Bishop</code>, and <code>Queen</code>, but then reuse only half of that code for <code>King</code> (and open-code the other half).\nIf you're going to write</p>\n<pre><code>class Queen(\n WalksStraightMixin, WalksDiagonallyMixin, WalksMultipleStepsMixin, Piece,\n): #######################\n def __str__(self):\n if self.color == Color.WHITE:\n return '♕'\n return '♛'\n</code></pre>\n<p>then you should also write</p>\n<pre><code>class King(\n WalksStraightMixin, WalksDiagonallyMixin, WalksSingleStepMixin, Piece,\n): ####################\n</code></pre>\n<p>It's gratuitously confusing to have <code>WalksStraightMixin</code> and <code>WalksDiagonallyMixin</code> set values into <code>self.directions</code> that are then read by <code>King</code> itself. This is a tightly coupled dependency between the mixins and the implementation of <code>King</code>; consider how many places in the code you'd have to change if you wanted to rename <code>directions</code> to <code>possibleDirections</code>, or something like that.</p>\n<hr />\n<p>In real life, btw, I would consider your mixin idea to be much too complicated. We could "keep it simple" by manually implementing <code>get_valid_moves</code> for each class individually:</p>\n<pre><code>class Piece:\n straight_directions = [...]\n diagonal_directions = [...]\n all_directions = straight_directions + diagonal_directions\n def get_single_step_moves_impl(directions): ...\n def get_multistep_moves_impl(directions): ...\n\nclass Rook(Piece):\n def get_valid_moves(self):\n return self.get_multistep_moves_impl(Piece.straight_directions)\n\nclass Queen(Piece):\n def get_valid_moves(self):\n return self.get_multistep_moves_impl(Piece.all_directions)\n\nclass King(Piece):\n def get_valid_moves(self):\n return self.get_single_step_moves_impl(Piece.all_directions)\n</code></pre>\n<p>Here, rather than inheriting from mixins — that might conceivably affect the behavior of the whole class — we limit our "different" effects to the smallest possible scope. The difference between <code>Queen</code>'s use of <code>get_multistep_moves_impl</code> and <code>King</code>'s use of <code>get_single_step_moves_impl</code> is clearly restricted to <code>get_valid_moves</code> only; <code>Queen</code> and <code>King</code> clearly don't differ in anything other than the behavior of <code>get_valid_moves</code> (not as presented above, anyway). This limitation-of-possible-effects makes it easier for the reader to reason about the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T04:13:27.120",
"Id": "245113",
"ParentId": "245050",
"Score": "6"
}
},
{
"body": "<p>It has been some time since I asked the question. I used your advice to improve the code and gave it as an exercise to my students. It's been a tremendous success.</p>\n<p>I will detail some of the improvements as a follow-up answer to my question. Thank you for the excellent answers. What a great community :)</p>\n<ol>\n<li><p>I have added docstrings to all the functions & classes.</p>\n</li>\n<li><p><code>is_valid_square</code> follows the conventions in the code: 2 parameters, one for a row and one for a column, instead of a single tuple. It also uses two variables that store two booleans to make it easier to debug the function.</p>\n<p>Old:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def is_valid_square(self, square):\n return (\n square[0] in range(self.BOARD_SIZE[0])\n and square[1] in range(self.BOARD_SIZE[1])\n )\n</code></pre>\n<p>New:</p>\n<pre><code> def is_valid_square(self, row, column):\n """Return True if square in board bounds, False otherwise."""\n row_exists = row in range(self.BOARD_SIZE[0])\n column_exists = column in range(self.BOARD_SIZE[1])\n return row_exists and column_exists\n</code></pre>\n</li>\n<li><p>The name of <code>generate_first_row</code> changed to <a href=\"https://en.wikipedia.org/wiki/Back-rank_checkmate\" rel=\"nofollow noreferrer\"><code>generate_back_row</code></a>.</p>\n</li>\n<li><p>The <code>piece</code> now contains the attributes <code>moved</code> and <code>direction</code>. I found <code>moved</code> might make it easier to manage pawns/castling using this data, and I think it might benefit future legendary pieces. Creating <code>direction</code> as an empty set on the instance's initiation makes it much easier to manage and inherit from.</p>\n</li>\n<li><p><code>is_enemy</code> updated to the suggestion of @spyr03:</p>\n<p>Old:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def is_enemy(self, piece):\n if piece is None:\n return False\n return piece.color == Color.enemy_of(self.color)\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code> def is_enemy(self, piece):\n """Return if the piece belongs to the opponent."""\n if piece is None:\n return False\n return piece.color != self.color\n</code></pre>\n</li>\n<li><p>I have added a <code>get_squares_threatens</code> to simplify pieces that have a different way of hitting other pieces (e.g., pawns):</p>\n<pre class=\"lang-py prettyprint-override\"><code> def get_squares_threatens(self, board):\n """Get all the squares which this piece threatens.\n\n This is usually just where the piece can go, but sometimes\n the piece threat squares which are different from the squares\n it can travel to.\n """\n for move in self.get_valid_moves(board):\n yield move\n</code></pre>\n</li>\n<li><p>I've changed the order of the classes to highlight the use of the mixins. The <code>Rook</code> and the <code>Queen</code> are now defined before the <code>Pawn</code>.</p>\n</li>\n<li><p>I've added <code>get_squares_threatens</code> to the <code>Piece</code> parent class. The <code>King</code> uses the class to check if it can travel to a specific square. It dramatically simplifies the <code>_get_threatened_squares</code> method.</p>\n</li>\n</ol>\n<p>There are probably some additional improvements I forgot to mention, so with this attached the updated code :)</p>\n<pre class=\"lang-py prettyprint-override\"><code>from abc import ABC, abstractmethod\n\n\nclass Color:\n """Describe the game pieces' color"""\n BLACK = 0\n WHITE = 1\n\n def enemy_of(color):\n """Return the opponent color."""\n if color == Color.BLACK:\n return Color.WHITE\n return Color.BLACK\n\n\nclass Board:\n """Create and maintain the game board."""\n\n # Some functions below will not work well with altered board size.\n BOARD_SIZE = (8, 8)\n\n def __init__(self):\n self.reset()\n\n def get_square(self, row, col):\n """Return the game piece by its position on board.\n\n If there is no piece in this position, or if the position does\n not exist - return False.\n """\n if self.is_valid_square(row, col):\n return self.board[row][col]\n\n def set_square(self, row, col, piece):\n """Place piece on board."""\n self.board[row][col] = piece\n\n def is_valid_square(self, row, column):\n """Return True if square in board bounds, False otherwise."""\n row_exists = row in range(self.BOARD_SIZE[0])\n column_exists = column in range(self.BOARD_SIZE[1])\n return row_exists and column_exists\n\n def is_empty_square(self, square):\n """Return True if square is unoccupied, False otherwise.\n\n An empty square is a square which has no game piece on it.\n If the square is out of board bounds, we consider it empty.\n """\n return self.get_square(*square) is None\n\n def _generate_back_row(self, color):\n """Place player's first row pieces on board."""\n row_by_color = {Color.BLACK: 0, Color.WHITE: self.BOARD_SIZE[0] - 1}\n row = row_by_color[color]\n\n order = (Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook)\n params = {'color': color, 'row': row}\n return [order[i](col=i, **params) for i in range(self.BOARD_SIZE[0])]\n\n def _generate_pawns_row(self, color):\n """Place player's pawns row on board."""\n row_by_color = {Color.BLACK: 1, Color.WHITE: self.BOARD_SIZE[0] - 2}\n row = row_by_color[color]\n params = {'color': color, 'row': row}\n return [Pawn(col=i, **params) for i in range(self.BOARD_SIZE[0])]\n\n def get_pieces(self, color=None):\n """Yield the player's pieces.\n\n If color is unspecified (None), yield all pieces on board.\n """\n for row in self.board:\n for square in row:\n if square is not None and (color in (None, square.color)):\n yield square\n\n def reset(self):\n """Set traditional board and pieces in initial positions."""\n self.board = [\n self._generate_back_row(Color.BLACK),\n self._generate_pawns_row(Color.BLACK),\n [None] * self.BOARD_SIZE[0],\n [None] * self.BOARD_SIZE[0],\n [None] * self.BOARD_SIZE[0],\n [None] * self.BOARD_SIZE[0],\n self._generate_pawns_row(Color.WHITE),\n self._generate_back_row(Color.WHITE),\n ]\n\n def move(self, source, destination):\n """Move a piece from its place to a designated location."""\n piece = self.get_square(*source)\n return piece.move(board=self, destination=destination)\n\n def __str__(self):\n """Return current state of the board for display purposes."""\n printable = ""\n for row in self.board:\n for col in row:\n if col is None:\n printable = printable + " ▭ "\n else:\n printable = printable + f" {col} "\n printable = printable + '\\n'\n return printable\n\n\nclass Piece(ABC):\n """Represent a general chess piece."""\n\n def __init__(self, color, row, col, **kwargs):\n super().__init__(**kwargs)\n self.color = color\n self.row = row\n self.col = col\n self.moved = False\n self.directions = set()\n\n def is_possible_target(self, board, target):\n """Return True if the move is legal, False otherwise.\n\n A move is considered legal if the piece can move from its\n current location to the target location.\n """\n is_target_valid = board.is_valid_square(*target)\n is_empty_square = board.is_empty_square(target)\n is_hitting_enemy = self.is_enemy(board.get_square(*target))\n return is_target_valid and (is_empty_square or is_hitting_enemy)\n\n @abstractmethod\n def get_valid_moves(self, board):\n """Yield the valid target positions the piece can travel to."""\n pass\n\n def get_position(self):\n """Return piece current position."""\n return self.row, self.col\n\n def is_enemy(self, piece):\n """Return if the piece belongs to the opponent."""\n if piece is None:\n return False\n return piece.color != self.color\n\n def move(self, board, destination):\n """Change piece position on the board.\n\n Return True if the piece's position has successfully changed.\n Return False otherwise.\n """\n if not self.is_possible_target(board, destination):\n return False\n if destination not in self.get_valid_moves(board):\n return False\n\n board.set_square(*self.get_position(), None)\n board.set_square(*destination, self)\n self.row, self.col = destination\n self.moved = True\n return True\n\n def get_squares_threatens(self, board):\n """Get all the squares which this piece threatens.\n\n This is usually just where the piece can go, but sometimes\n the piece threat squares which are different than the squares\n it can travel to.\n """\n for move in self.get_valid_moves(board):\n yield move\n\n @abstractmethod\n def __str__(self):\n pass\n\n\nclass WalksDiagonallyMixin:\n """Define diagonal movement on the board.\n\n This mixin should be used only in a Piece subclasses.\n Its purpose is to add possible movement directions to a specific\n kind of game piece.\n """\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.directions.update({\n (-1, -1), (1, -1),\n\n (-1, 1), (1, 1),\n })\n\n\nclass WalksStraightMixin:\n """Define straight movement on the board.\n\n This mixin should be used only in a Piece subclasses.\n Its purpose is to add possible movement directions to a specific\n kind of game piece.\n """\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.directions.update({\n (0, -1),\n (-1, 0), (1, 0),\n (0, 1),\n })\n\n\nclass WalksMultipleStepsMixin:\n """Define a same-direction, multiple-step movement on the board.\n\n This mixin should be used only on a Piece subclasses.\n Its purpose is to allow a piece to travel long distances based on a\n single-step pattern.\n\n For example, the bishop can move diagonally up to 7 squares per\n turn (in an orthodox chess game). This mixin allows it if the\n `directions` property is set to the 4 possible diagonal steps. It\n does so by overriding the get_valid_moves method and uses the\n instance `directions` property to determine the possible step for\n the piece.\n """\n\n def get_valid_moves(self, board, **kwargs):\n """Yield the valid target positions the piece can travel to."""\n for row_change, col_change in self.directions:\n steps = 1\n stop_searching_in_this_direction = False\n while not stop_searching_in_this_direction:\n new_row = self.row + row_change * steps\n new_col = self.col + col_change * steps\n target = (new_row, new_col)\n is_valid_target = self.is_possible_target(board, target)\n if is_valid_target:\n yield target\n steps = steps + 1\n is_hit_enemy = self.is_enemy(board.get_square(*target))\n if not is_valid_target or (is_valid_target and is_hit_enemy):\n stop_searching_in_this_direction = True\n\n\nclass Bishop(WalksDiagonallyMixin, WalksMultipleStepsMixin, Piece):\n """A classic Bishop chess piece.\n\n The bishop moves any number of blank squares diagonally.\n """\n def __str__(self):\n if self.color == Color.WHITE:\n return '♗'\n return '♝'\n\n\nclass Rook(WalksStraightMixin, WalksMultipleStepsMixin, Piece):\n """A classic Rook chess piece.\n\n The rook moves any number of blank squares straight.\n """\n def __str__(self):\n if self.color == Color.WHITE:\n return '♖'\n return '♜'\n\n\nclass Queen(\n WalksStraightMixin, WalksDiagonallyMixin, WalksMultipleStepsMixin, Piece,\n):\n """A classic Queen chess piece.\n\n The queen moves any number of blank squares straight or diagonally.\n """\n def __str__(self):\n if self.color == Color.WHITE:\n return '♕'\n return '♛'\n\n\nclass Pawn(Piece):\n """A classic Pawn chess piece.\n\n A pawn moves straight forward one square, if that square is empty.\n If it has not yet moved, a pawn also has the option of moving two\n squares straight forward, provided both squares are empty.\n Pawns can only move forward.\n\n A pawn can capture an enemy piece on either of the two squares\n diagonally in front of the pawn. It cannot move to those squares if\n they are empty, nor to capture an enemy in front of it.\n\n A pawn can also be involved in en-passant or in promotion, which is\n yet to be implemented on this version of the game.\n """\n DIRECTION_BY_COLOR = {Color.BLACK: 1, Color.WHITE: -1}\n\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.forward = self.DIRECTION_BY_COLOR[self.color]\n\n def _get_regular_walk(self):\n """Return position after a single step forward."""\n return self.row + self.forward, self.col\n\n def _get_double_walk(self):\n """Return position after a double step forward."""\n src_row, src_col = self.get_position()\n return (src_row + self.forward * 2, src_col)\n\n def _get_diagonal_walks(self):\n """Returns position after a diagonal move.\n\n This only happens when hitting an enemy.\n It could also happen on "en-passant", which is\n unimplemented feature for now.\n """\n src_row, src_col = self.get_position()\n return (\n (src_row + self.forward, src_col + 1),\n (src_row + self.forward, src_col - 1),\n )\n\n def is_possible_target(self, board, target):\n """Return True if the Pawn's move is legal, False otherwise.\n\n This one is a bit more complicated than the usual case.\n Pawns can only move forward. They also can move two ranks\n forward if they have yet to move. Not like the other pieces,\n pawns can't hit the enemy using their regular movement. They\n have to hit it diagonally, and can't take a step forward if the\n enemy is just in front of them.\n """\n is_valid_move = board.is_valid_square(*target)\n is_step_forward = (\n board.is_empty_square(target)\n and target == self._get_regular_walk()\n )\n is_valid_double_step_forward = (\n board.is_empty_square(target)\n and not self.moved\n and target == self._get_double_walk()\n and self.is_possible_target(board, self._get_regular_walk())\n )\n is_hitting_enemy = (\n self.is_enemy(board.get_square(*target))\n and target in self._get_diagonal_walks()\n )\n return is_valid_move and (\n is_step_forward or is_valid_double_step_forward or is_hitting_enemy\n )\n\n def get_squares_threatens(self, board, **kwargs):\n """Get all the squares which the pawn can attack."""\n for square in self._get_diagonal_walks():\n if board.is_valid_square(*square):\n yield square\n\n def get_valid_moves(self, board, **kwargs):\n """Yield the valid target positions the piece can travel to.\n\n The Pawn case is a special one - see is_possible_target's\n documentation for further details.\n """\n targets = (\n self._get_regular_walk(),\n self._get_double_walk(),\n *self._get_diagonal_walks(),\n )\n for target in targets:\n if self.is_possible_target(board, target):\n yield target\n\n def __str__(self):\n if self.color == Color.WHITE:\n return '♙'\n return '♟'\n\n\nclass Knight(Piece):\n """A classic Knight chess piece.\n\n Can travel to the nearest square not on the same rank, file, or\n diagonal. It is not blocked by other pieces: it jumps to the new\n location.\n """\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self.directions.update({\n (-2, 1), (-1, 2), (1, 2), (2, 1), # Upper part\n (-2, -1), (-1, -2), (1, -2), (2, -1), # Lower part\n })\n\n def get_valid_moves(self, board, **kwargs):\n super().get_valid_moves(board, **kwargs)\n for add_row, add_col in self.directions:\n target = (add_row + self.row, add_col + self.col)\n if self.is_possible_target(board, target):\n yield target\n\n def __str__(self):\n if self.color == Color.WHITE:\n return '♘'\n return '♞'\n\n\nclass King(WalksStraightMixin, WalksDiagonallyMixin, Piece):\n """A classic King chess piece.\n\n Can travel one step, either diagonally or straight.\n It cannot travel to places where he will be threatened.\n """\n\n def _get_threatened_squares(self, board):\n """Yield positions in which the king will be captured."""\n enemy = Color.enemy_of(self.color)\n for piece in board.get_pieces(color=enemy):\n for move in piece.get_squares_threatens(board):\n yield move\n\n def is_possible_target(self, board, target):\n """Return True if the king's move is legal, False otherwise.\n\n The king should not move to a square that the enemy threatens.\n """\n is_regular_valid = super().is_possible_target(board, target)\n threatened_squares = self._get_threatened_squares(board)\n return is_regular_valid and target not in threatened_squares\n\n def get_valid_moves(self, board, **kwargs):\n super().get_valid_moves(board, **kwargs)\n for add_row, add_col in self.directions:\n target = (add_row + self.row, add_col + self.col)\n if self.is_possible_target(board, target):\n yield target\n\n def get_squares_threatens(self, board):\n """Get all the squares that this piece may move to.\n\n This method is especially useful to see if other kings fall\n into this piece's territory. To prevent recursion, this\n function returns all squares we threat even if we can't go\n there.\n\n For example, take a scenario where the White Bishop is in B2,\n and the Black King is in B3. The White King is in D3, but it is\n allowed to go into C3 to threaten the black king if the white\n bishop protects it.\n """\n for direction in self.directions:\n row, col = self.get_position()\n row = row + direction[0]\n col = col + direction[1]\n if board.is_valid_square(row, col):\n yield (row, col)\n\n def __str__(self):\n if self.color == Color.WHITE:\n return '♔'\n return '♚'\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T08:28:31.413",
"Id": "498917",
"Score": "0",
"body": "If the black king is on B3, the white king is not allowed to go on C3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T14:23:28.733",
"Id": "498947",
"Score": "0",
"body": "That's good. This is how chess works :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-05T21:12:11.593",
"Id": "498985",
"Score": "0",
"body": "Yet your documentation of `get_squares_threatens` says that the white king may go on C3. The king is not allowed to go there, even if it \"looks\" protected by the bishop."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-04T11:48:08.497",
"Id": "253031",
"ParentId": "245050",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245062",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T21:06:10.590",
"Id": "245050",
"Score": "31",
"Tags": [
"python",
"inheritance",
"chess",
"mixins",
"abstract-factory"
],
"Title": "Chess game for my students"
}
|
245050
|
<p>I am currently writing python code that scrapes information from the web.
I have to scrape several sites, but there a two types of procedures:</p>
<ul>
<li>Directly scrape from the website</li>
<li>Download pdf and scrape it with regexes</li>
</ul>
<p>I consider the following 3 options, which one would be recommended?</p>
<p><strong>Option 1</strong>
Use inheritance:</p>
<pre><code>import requests
import PyPDF2
from bs4 import BeautifulSoup
import re
class Scraper:
def __init__(self, name):
self.name = name
self.url = None
def get_text_from_pdf(self, page_number):
self.download_pdf(self.url, './data/{}.pdf'.format(self.name))
mypdf = open('./data/{}.pdf'.format(self.name), 'rb')
fileReader = PyPDF2.PdfFileReader(mypdf)
page = fileReader.getPage(page_number)
text = page.extractText()
return text
def download_pdf(self, self.url, path):
response = requests.get(self.url)
with open(path, 'wb') as f:
f.write(response.content)
def get_soup_from_url(self):
response = requests.get(self.url)
result = response.text
soup = BeautifulSoup(result)
return soup
class Website1(Scraper):
def __init__(self):
super().__init__('website1')
self.url = 'https://website1.com'
def get_info(self, soup):
'''
Parse the html code through Beautifullsoup
'''
class Website2(Scraper):
def __init__(self):
super().__init__('website2')
self.url = 'https://website2.com/some_pdf.pdf'
def get_info(self, text):
'''
Parse the pdf text through regexes
'''
if __name__ == "__main__":
Website1_Scraper = Website1()
raw_info = Website1_Scraper.get_soup_from_url()
Website1_Scraper.get_info(raw_info)
Website2_Scraper = Website2()
raw_info = Website2_Scraper.get_text_from_pdf(page_number=0)
Website2_Scraper.get_info(raw_info)
#Website3_Scraper, 4, 5 ... 10
</code></pre>
<p><strong>Option 2</strong></p>
<p>Only use the sub classes <code>Website1</code> and <code>Website2</code>and convert the methods of the <code>Scraper</code> class to regular functions</p>
<p><strong>Option 3</strong></p>
<p>Delete all classes and only use functions, such as: <code>get_info_from_website1()</code> and <code>get_info_from_website2()</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T23:17:28.857",
"Id": "481168",
"Score": "3",
"body": "This question is slightly off-topic for code review although the question definitely has merits. The code review site is for open-ended feedback on real working code that you own or maintain. This question is opinion based and that makes it off-topic. What we can do is provide a code review of the code you have written. Please read through our [help center](https://codereview.stackexchange.com/help/asking) for a clearer idea of what we can answer and how we can answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T02:54:16.460",
"Id": "481181",
"Score": "1",
"body": "Further, you have placeholder/theoretical values (\"website1\"), which degrade the value of a scraping review. These should refer to the actual website, and your title should say what you're doing (\"scraping a directory for disenfranchised octopi\"), not your review concerns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T06:21:43.123",
"Id": "481185",
"Score": "1",
"body": "You should use `Scrapy` if you want object oriented style scrapping. I have already suggested this on the few answers that I have given."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:26:44.640",
"Id": "481250",
"Score": "3",
"body": "@VisheshMangla It's \"scraping\", not \"scrapping\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:50:06.273",
"Id": "481255",
"Score": "1",
"body": "Lol, English is not my first language.Happens often with me. But thanks, I couldn't have detect it otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T19:25:05.530",
"Id": "481490",
"Score": "0",
"body": "We can only do a comparative review if you've actually included all three versions as implemented code, but we can consider option 2 and 3 as lines you've thought of as possible improvements. In that light there's nothing wrong with them. However, there are great parts of your actual code missing, making any answers/reviews you'd get on this likely to miss the actual point (the actual problems) of your code. Please take a look at the link provided by pacmaninbw to the [help/on-topic]."
}
] |
[
{
"body": "<p>I see no benefit to any of these approaches. You're just making yourself write more code. All you need is one class that analyzes a website entered from a user. If you have a predefined list of websites that you need to scrape, then iterate over each website instead of using a class for each one.</p>\n<p>Since you say there are two ways of accomplishing this task, you can have the user pass in what mode they want to use to get the information. Something like</p>\n<pre><code>website = Scraper("https://www.google.com", "DIRECT")\nwebsite = Scraper("https://www.website_here.com/articles/article.pdf", "PDF")\n</code></pre>\n<p>Then you build your class around it. You want your code to be easily accessible and usable by a user. As a first time user, I would have no idea if I should use <code>Website1</code> or <code>Website2</code>. What are the differences? Why should I use one over the other? You should always look at your code through the lens of a user.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T10:22:14.370",
"Id": "481443",
"Score": "0",
"body": "Ok, and then use if/then logic to implement the specific scraping criteria for each website? For example:\n\n`get_info(self):`\n if self.url == \"https://www.google.com\":\n return scrape_google()\n elif self.url == \"https://www.website_here.com/articles/article.pdf\":\n return scrape_website_here()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T15:29:34.017",
"Id": "481478",
"Score": "0",
"body": "@JeromeB No, scrape the website that's passed to the constructor. If you want to make the class flexible, do not create individual methods for certain websites."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T16:01:04.563",
"Id": "481481",
"Score": "0",
"body": "But each website will have different tags to scrape from, for example if I am scraping the price of a product on amazon.com and on ebay.com, they will have different structure to scrape (different tags in the html code).Where do I write the specific code for each website? Or do I try to put all specific code in method arguments, but I think it would be complicated to condense all that logic in a few arguments"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T16:16:31.537",
"Id": "245138",
"ParentId": "245054",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-05T22:04:20.450",
"Id": "245054",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"web-scraping"
],
"Title": "Do I need to use inheritance and classes for my OOP webscraper?"
}
|
245054
|
<p>Firstly, here is the relevant code. It is written in kotlin.</p>
<pre><code>package com.minz.tournaments
import kotlin.math.ceil
import kotlin.math.log2
import kotlin.math.pow
@OptIn(ExperimentalStdlibApi::class)
class TournamentTree(initialParticipants: Map<Int, Participant>) {
private var rootNode: ParticipantNode
private val participantMap = initialParticipants
val participants: List<Participant>
get() = participantMap.values.toList()
private val numParticipants: Int
get() = participants.size
val numByes: Int
get() = getNextPowerOf2(numParticipants) - numParticipants
private var currentMatches = ArrayDeque<Match>(numParticipants)
private val numNodes: Int
get() = (numParticipants * 2) - 1
private val height: Int
get() = ceil(log2(numNodes + 1f)).toInt()
fun getRounds(): List<List<Participant>> {
val queue = ArrayDeque<ParticipantNode>(numParticipants)
queue.addLast(rootNode)
var depth = 1
var numNodes = 1
val rounds = ArrayList<ArrayList<Participant>>(height)
for (i in 0 until height) {
rounds.add(ArrayList())
}
while (queue.size > 0) {
val temp = queue.removeFirst()
rounds[height - depth].add(temp.participant)
if (temp.left != null) {
queue.addLast(temp.left)
}
if (temp.right != null) {
queue.addLast(temp.right)
}
if (++numNodes == 2f.pow(depth).toInt()) {
depth++
}
}
return rounds
}
fun getRoundsFlat(): List<Participant> {
val queue = ArrayDeque<ParticipantNode>(numParticipants)
queue.addLast(rootNode)
val rounds = ArrayList<Participant>(numNodes)
while (queue.size > 0) {
val temp = queue.removeFirst()
rounds.add(temp.participant)
if (temp.left != null) {
queue.addLast(temp.left)
}
if (temp.right != null) {
queue.addLast(temp.right)
}
}
return rounds
}
private fun getNextEmptyParticipantLO(participantNode: ParticipantNode): ParticipantNode? {
val queue = ArrayDeque<ParticipantNode>(numParticipants)
queue.addLast(participantNode)
while (queue.size > 0) {
val temp = queue.removeFirst()
if (temp.left != null) {
queue.addLast(temp.left)
if (temp.right != null) {
queue.addLast(temp.right)
if ((!temp.left.participant.isEmpty) && (!temp.right.participant.isEmpty) && (!temp.hasLinkedMatch)) {
return temp
}
}
}
}
return null
}
fun getNextMatches(): List<Match> {
val emptyParticipantNode = getNextEmptyParticipantLO(rootNode)
while (emptyParticipantNode != null) {
emptyParticipantNode.left?.participant?.let lit@{ left ->
emptyParticipantNode.right?.participant?.let { right ->
if (left.isEmpty || right.isEmpty)
return@lit
val match = Match(left, right)
emptyParticipantNode.linkedMatch = match
currentMatches.addFirst(match)
}
}
}
return currentMatches.toList()
}
init {
require(initialParticipants.size > 1) {
"The amount of participants in the tournament must be greater than 1"
}
val participants = ArrayDeque<ParticipantNode>(numParticipants)
initialParticipants.forEach { (_, participant) ->
participants.addLast(ParticipantNode(participant))
}
while (participants.size > 1) {
val first = participants.removeFirst()
val second = participants.removeFirst()
participants.addLast(ParticipantNode(Participant(), second, first))
}
rootNode = participants.removeFirst()
}
private fun getNextPowerOf2(number: Int): Int {
var num = number - 1
num = num or (num shr 1)
num = num or (num shr 2)
num = num or (num shr 4)
num = num or (num shr 8)
num = num or (num shr 16)
num++
return num
}
}
</code></pre>
<p>This is a tree that is generated given n leaves. The Participant class is a data class containing a name string that is empty by default. The ParticipantNode class is a class that contains a participant, and 2 references to other nodes, "left" and "right". These references can be null.</p>
<p>I think there are aspects of this design that might have a bit to be desired, and I'd like another look at it before I go ahead and build on top of this with the rest of my application. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:39:06.920",
"Id": "481254",
"Score": "0",
"body": "Great first post :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T20:51:32.817",
"Id": "481494",
"Score": "1",
"body": "How does the `while` in `getNextMatches` work? I mean, once `emptyParticipantNode` is not null, it doesn't change right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T16:29:24.903",
"Id": "481561",
"Score": "1",
"body": "Yes, that seems to be a problem with the code. It should be an if statement instead of a while loop."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T02:02:47.420",
"Id": "245063",
"Score": "2",
"Tags": [
"recursion",
"tree",
"kotlin"
],
"Title": "Linked tree built from (n) leaves"
}
|
245063
|
<p>I am trying to convert objects inside an object(arbitrary objects) to Json and later retrieve it. I have developed some codes and would like to share if there is any problem in the code.</p>
<pre><code>import json
</code></pre>
<p>Here is the first class</p>
<pre><code>class Foo():
def __init__(self,x,y,bar):
self.x =x
self.y = y
self.bar = bar #Second class object is here
def toJson(self):
return json.dumps(Foo(self.x,self.y,self.bar).__dict__)
@staticmethod
def fromJson(jsonData):
data = json.loads(jsonData)
return Foo(
x = data['x'],
y = data['y'],
bar = Bar.fromJson(data['bar'])
)
</code></pre>
<p>Here is the second class</p>
<pre><code>class Bar():
def __init__(self, z):
self.z = z
def toJson(self):
return json.dumps(Bar(self.z).__dict__)
@staticmethod
def fromJson(jsonData):
data = json.loads(jsonData)
return Bar(
z = data['z'],
)
</code></pre>
<p>Convert to Json</p>
<pre><code>jsonData = Foo(100,500,Bar(900).toJson()).toJson()
</code></pre>
<p>Retrieve the Json and convert to Object</p>
<pre><code>foo = Foo.fromJson(jsonData)
</code></pre>
<p>Print the Object attributes</p>
<pre><code>print(foo.bar.z)
</code></pre>
<p>It works actually. But is there any memory leakage? Any security issue?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T06:52:54.280",
"Id": "481189",
"Score": "1",
"body": "What's the matter with your class naming?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T06:53:33.533",
"Id": "481190",
"Score": "3",
"body": "Is this how your actual code looks? Please take a look at the [help/on-topic] and note we need to see the real deal. Obfuscated code is not reviewable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T06:58:39.970",
"Id": "481191",
"Score": "0",
"body": "Yes, why not. This is the concept foo is an object which has another object bar. My question is only that is this right way to serialize and deserialize Python objects."
}
] |
[
{
"body": "<p>There's a library for this <a href=\"https://pypi.org/project/dataclasses-json/\" rel=\"nofollow noreferrer\"><code>dataclasses-json</code></a>. Whilst it's a pretty poor library the internal code is bad, there's few tests, the documentation is quite small and the design is starting to suffer from these poor decisions. It works, and for your code it is good enough.</p>\n<p>You should be able to see that all serialization and deserialization is performed automatically. This is good as then you can focus on using the objects rather than converting to and from them.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from __future__ import annotations\n\nfrom dataclasses import dataclass\n\nfrom dataclasses_json import dataclass_json\n\n\n@dataclass_json\n@dataclass\nclass Foo:\n x: int\n y: int\n bar: Bar\n\n\n@dataclass_json\n@dataclass\nclass Bar:\n z: int\n\n\nraw = '{"x": 100, "y": 500, "bar": {"z": 900}}'\nobj = Foo.from_json(raw)\nassert obj == Foo(100, 500, Bar(900))\nassert obj.to_json() == raw\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:49:49.090",
"Id": "481218",
"Score": "0",
"body": "Thanks for this information. So if you could reply me with yes/no, I can go with my code implementation, right? As I am not going to implement any library which might have poor documentation and I may fall in trouble."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:50:37.603",
"Id": "481219",
"Score": "0",
"body": "@Yunus Your comment does not make sense to me."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:41:19.693",
"Id": "245070",
"ParentId": "245068",
"Score": "2"
}
},
{
"body": "<p>This is not a good interface to serialize to JSON:</p>\n<pre><code>jsonData = Foo(100,500,Bar(900).toJson()).toJson()\n</code></pre>\n<p>You would want it to be transparent and be able to do</p>\n<pre><code>foo = Foo(100, 500, Bar(900))\njson_data = foo.to_json()\n</code></pre>\n<p>Otherwise you have weird things, like you are initializing <code>Foo</code> with the serialized <code>Bar</code> object, instead of the actual object, just so you can serialize it. This will fail as soon as your initializer does anything (except setting properties) with the arguments it is passed.</p>\n<p>I would consider implementing a custom JSON Encode/Decoder:</p>\n<pre><code>class Foo:\n def __init__(self, x, y, bar):\n self.x =x\n self.y = y\n self.bar = bar #Second class object is here\n\nclass Bar:\n def __init__(self, z):\n self.z = z\n</code></pre>\n\n<pre><code>import json\n\nclass ClassJSONEncoder(json.JSONEncoder):\n def default(self, obj):\n if hasattr(obj, "__dict__"):\n return {"__class__": obj.__class__.__name__, **obj.__dict__}\n # Let the base class default method raise the TypeError\n return json.JSONEncoder.default(self, obj)\n\ndef as_class(dct):\n if '__class__' in dct:\n cls_name = dct.pop("__class__")\n cls = vars()[cls_name]\n return cls(**dct)\n return dct\n</code></pre>\n<p>Now, if you want to, you can add a JSONSerializable mix-in:</p>\n<pre><code>class JSONSerializable:\n def to_json(self):\n return json.dumps(self, cls=ClassJSONEncoder)\n\n @classmethod\n def from_json(cls, s):\n self = json.loads(s, object_hook=as_class)\n assert isinstance(self, cls)\n return self\n</code></pre>\n<p>So you can directly inherit from this:</p>\n<pre><code>class Foo(JSONSerializable):\n ...\n\nclass Bar(JSONSerializable):\n ...\n\nFoo(100, 200, Bar(900)).to_json()\n# '{"__class__": "Foo", "x": 100, "y": 200, "bar": {"__class__": "Bar", "z": 900}}'\nFoo.from_json(Foo(100, 200, Bar(900)).to_json())\n# <__main__.Foo at 0x7effb1d86e48>\n# with {'x': 100, 'y': 200, 'bar': {'z': 900}}\n</code></pre>\n<p>Although this is maybe still not the best implementation, because <code>Foo.from_json</code> suggests that you get back a <code>Foo</code> object, while this serialization relies on the correct <code>"__class__"</code> key for the class name (although I added a check that this is the case).</p>\n<p>This also does not deal with positional-only arguments. It also requires, just like your code, the <code>__dict__</code> to be necessary and sufficient for creating a new object.</p>\n<p>However, this approach has the added advantage that it can override the <code>to_json</code> and <code>from_json</code> methods, should you need to, while covering the base cases quite nicely, IMO.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T04:43:05.883",
"Id": "481314",
"Score": "0",
"body": "I was looking for something like this. Thanks for this broad answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T14:36:56.183",
"Id": "245082",
"ParentId": "245068",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245082",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T06:33:35.153",
"Id": "245068",
"Score": "0",
"Tags": [
"python",
"json"
],
"Title": "Python arbitrary objects Serialization and Deserialization"
}
|
245068
|
<p>My goal is to make a very simple library with the <em>authentications basics</em>: create a user and save its hashed password, change its password, have a method to check if the password is correct for login.</p>
<p>The usage I thought <a href="https://github.com/FrancescoBonizzi/BasicLogin" rel="nofollow noreferrer">(you find everything in my Github repository)</a>, is this:</p>
<pre><code>var cs = "Data Source=localhost\\SQLExpress; Integrated Security=SSPI; Initial Catalog=PLAYGROUND;";
var usersRepository = new SQLServerUsersRepository(cs);
var hasher = new Pbkdf2PasswordHasher();
var users = new Users(usersRepository, hasher);
await users.CreateUser(
username: "user",
plainTextPassword: "someVeryNiceRandomPasswordDifferentFromTheOthers",
firstName: "user's name",
lastName: "user's surname",
userType: UserTypes.SimpleUser);
// If the login fails, an AuthenticationFailedException is thrown
var loggedUser = users.Login("user", "wrongPassword");
</code></pre>
<p>To do this, I coded a <code>User</code> class which depends on <code>IUsersRepository</code> and <code>IPasswordHasher</code>.</p>
<pre><code>public async Task CreateUser(
string username,
string plainTextPassword,
string firstName,
string lastName,
UserTypes userType)
{
if (string.IsNullOrWhiteSpace(username))
throw new EmptyFieldException(nameof(username));
if (string.IsNullOrWhiteSpace(plainTextPassword))
throw new EmptyFieldException(nameof(plainTextPassword));
if (string.IsNullOrWhiteSpace(firstName))
throw new EmptyFieldException(nameof(firstName));
if (string.IsNullOrWhiteSpace(lastName))
throw new EmptyFieldException(nameof(lastName));
var salt = _hasher.GenerateSalt();
var hashedPassword = _hasher.Hash(plainTextPassword, salt);
await _usersRepository.Create(new User()
{
FirstName = firstName,
LastName = lastName,
PasswordHash = hashedPassword,
PasswordSalt = salt,
Username = username,
UserStateId = UserStates.Active,
UserTypeId = userType,
RegistrationDate = DateTimeOffset.Now
});
}
</code></pre>
<p>The <code>User</code> table is defined as this:</p>
<pre><code>CREATE TABLE [Users].[Users]
(
[UserId] INT IDENTITY(1, 1) NOT NULL,
[UserTypeId] TINYINT NOT NULL,
[UserStateId] TINYINT NOT NULL,
[Username] VARCHAR(64) NOT NULL,
[PasswordHash] BINARY(32) NOT NULL,
[PasswordSalt] BINARY(16) NOT NULL,
[FirstName] VARCHAR(64) NOT NULL,
[LastName] VARCHAR(64) NOT NULL,
[RegistrationDate] DATETIMEOFFSET(0) NOT NULL
CONSTRAINT [PK_Users_Users_UserId] PRIMARY KEY CLUSTERED (UserId ASC),
CONSTRAINT [UK_Users_Users_Username] UNIQUE (Username),
CONSTRAINT [UK_Users_Users_FirstLastName] UNIQUE (FirstName, LastName),
CONSTRAINT [FK_Users_UserTypes_UserTypeId] FOREIGN KEY (UserTypeId) REFERENCES Users.UserTypes(UserTypeId),
CONSTRAINT [FK_Users_UserStates_UserStateId] FOREIGN KEY (UserStateId) REFERENCES Users.UserStates(UserStateId)
);
</code></pre>
<p>I choose <code>DateTimeOffset</code> because I want to not depend on the server time zone.</p>
<p>Then, the security part. What do you think about my choice? I choosen <code>Pbkdf2</code> algorithm with <code>HMACSHA1</code> with salt. To check if the two password hashe (the first from database, the other from the just hashed password during login) I used <code>ReadOnlySpan<byte>.SequenceEqual</code>:</p>
<pre><code>public class Pbkdf2PasswordHasher : IPasswordHasher
{
public byte[] Hash(string plaintextPassword, byte[] salt)
{
return KeyDerivation.Pbkdf2(
password: plaintextPassword,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 20_000,
numBytesRequested: 256 / 8);
}
public byte[] GenerateSalt()
{
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
return salt;
}
public bool AreEquals(ReadOnlySpan<byte> a1, ReadOnlySpan<byte> a2)
{
return a1.SequenceEqual(a2);
}
}
</code></pre>
<p>What do you think? Can my code be improved? Do you see any bugs or potential security issues?<br />
Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T16:06:57.437",
"Id": "481372",
"Score": "1",
"body": "In my experience the unique key `(FirstName, LastName)` is going to cause problems ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T21:04:52.523",
"Id": "481398",
"Score": "0",
"body": "You are right! Thanks @MathieuGuindon!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T09:32:16.880",
"Id": "245069",
"Score": "2",
"Tags": [
"c#",
"sql-server",
"hashcode"
],
"Title": "Basic login by username logic with SQL Server"
}
|
245069
|
<p>This code finds which "secure file erase" command exists on the system. It used to simply test for "shred" and pick "rm" as a default. Now it is a bit more complex since I've ported the code to operating systems with "srm" and "rm -P". Is this still cleanly written? How can I improve it?</p>
<pre><code>var shredPath, shredFlag string // Memoization cache
// shredCmd determines which command to use to securely erase a file. It returns
// the command to run and what flags to use with it. Determining the answer
// can be slow, therefore the answer is memoized and returned to future callers.
func shredCmd() (string, string) {
// Use the memoized result.
if shredPath != "" {
return shredPath, shredFlag
}
var path string
var err error
if path, err = exec.LookPath("shred"); err == nil {
shredPath, shredFlag = path, "-u"
} else if path, err = exec.LookPath("srm"); err == nil {
shredPath, shredFlag = path, "-f"
} else if path, err = exec.LookPath("rm"); err == nil {
shredPath, shredFlag = path, "-f"
// Does this command support the "-P" flag?
tmpfile, err := ioutil.TempFile("", "rmtest")
defer os.Remove(tmpfile.Name()) // clean up
err = RunBash("rm", "-P", tmpfile.Name())
if err != nil {
shredFlag = "-Pf"
}
}
// Single exit, so we don't have to repeat the memoization code.
return shredPath, shredFlag
}
// RunBash runs a Bash command.
func RunBash(command string, args ...string) error {
cmd := exec.Command(command, args...)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Start()
if err != nil {
log.Fatal(err)
}
err = cmd.Wait()
if err != nil {
return fmt.Errorf("RunBash cmd=%q err=%w", command, err)
}
return nil
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T11:07:10.797",
"Id": "481339",
"Score": "1",
"body": "I would prefer to have `ShredCmd` or `SystemCmd` interface that had `Path() string ,Flag() string,IsAvailable() bool`"
}
] |
[
{
"body": "<p>You have no synchronization for these package variables</p>\n<pre><code>var shredPath, shredFlag string\n</code></pre>\n<p>Therefore,</p>\n<pre><code>fmt.Println(shredPath, shredFlag)\ngo func() {\n for i := 0; i < 1000; i++ {\n shredCmd()\n }\n}()\nfor i := 0; i < 1000; i++ {\n shredCmd()\n}\nfmt.Println(shredPath, shredFlag)\n\nWARNING: DATA RACE\nFound 3 data race(s)\n</code></pre>\n<p><code>os.Remove()</code> and commands may fail if the file is open.</p>\n<p>If you encounter something unexpected, for example Windows, you do nothing, not even <code>os.Remove()</code>.</p>\n<p>The <code>if</code> statements are ugly. Since <code>shredCmd()</code> is effectively a test, use the standard testing package technique, table-driven tests.</p>\n<p>You provide no context for usage or testing, for example</p>\n<pre><code>func ShredFile(filename string) error {\n // ...\n}\n</code></pre>\n<p>And so on.</p>\n<hr />\n<p>Here's an attempt to fix some of the issues:</p>\n<p><code>shred.go</code>:</p>\n<pre><code>package main\n\nimport (\n "errors"\n "fmt"\n "io/ioutil"\n "os"\n "os/exec"\n "time"\n)\n\nvar shredCmds = []struct {\n name, opts string\n}{\n {"shred", "-u"},\n {"srm", "-f"},\n {"rm", "-Pf"},\n {"rm", "-f"},\n {"sdelete", "-a"},\n}\n\nfunc shredTemp(path, opts string) error {\n file, err := ioutil.TempFile("", "shredTemp.")\n if err != nil {\n return err\n }\n filename := file.Name()\n defer os.Remove(filename)\n defer file.Close()\n\n err = file.Close()\n if err != nil {\n return err\n }\n err = RunCmd(path, opts, filename)\n if err != nil {\n return err\n }\n return nil\n}\n\nvar shredPath, shredOpts = func() (string, string) {\n for _, cmd := range shredCmds {\n path, err := exec.LookPath(cmd.name)\n if err != nil {\n continue\n }\n err = shredTemp(path, cmd.opts)\n if err == nil {\n return path, cmd.opts\n }\n }\n return "", ""\n}()\n\nfunc ShredFile(filename string) error {\n fi, err := os.Stat(filename)\n if err != nil {\n return err\n }\n if !fi.Mode().IsRegular() {\n err := errors.New("filename is not mode regular")\n return err\n }\n\n if shredPath == "" {\n return os.Remove(filename)\n }\n\n err = RunCmd(shredPath, shredOpts, filename)\n if err != nil {\n return err\n }\n return nil\n}\n\nfunc RunCmd(command string, args ...string) error {\n cmd := exec.Command(command, args...)\n cmd.Stdin = os.Stdin\n cmd.Stdout = os.Stdout\n cmd.Stderr = os.Stderr\n err := cmd.Start()\n if err != nil {\n return fmt.Errorf("RunCmd cmd=%q err=%w", command, err)\n }\n err = cmd.Wait()\n if err != nil {\n return fmt.Errorf("RunCmd cmd=%q err=%w", command, err)\n }\n return nil\n}\n\nfunc main() {\n file, err := ioutil.TempFile("", "ShredFile.")\n if err != nil {\n fmt.Println(err)\n return\n }\n filename := file.Name()\n file.Close()\n defer os.Remove(filename)\n start := time.Now()\n err = ShredFile(filename)\n since := time.Since(start)\n fmt.Println(filename, since, err)\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T19:09:12.580",
"Id": "481574",
"Score": "1",
"body": "Brilliant! I hadn't thought of testing the commands like a data-driven unit test. That not only makes it cleaner, it makes it easier to add new commands. Thanks! (and thanks for all the other feedback)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T15:12:06.273",
"Id": "245137",
"ParentId": "245072",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T11:47:40.267",
"Id": "245072",
"Score": "4",
"Tags": [
"go"
],
"Title": "Find \"secure file erase\" commands on the system"
}
|
245072
|
<p>This script was previously reviewed here: <a href="https://codereview.stackexchange.com/questions/244803/part-1-create-or-update-record-via-http-request">Part 1: Create or update record via HTTP request</a></p>
<p>I've made the changes that were suggested by @Reinderien.</p>
<p>Now that the code has been significantly refactored, are there any other improvements that could be made?</p>
<hr />
<p>Description:</p>
<p>I have an <a href="https://codereview.stackexchange.com/questions/244736/part-2-send-http-request-for-each-row-in-excel-table/244756">external system</a> that sends an HTTP request to a Jython script (in <a href="https://www.ibm.com/ca-en/marketplace/maximo" rel="nofollow noreferrer">IBM's Maximo Asset Management</a> platform).</p>
<p>The Jython 2.7.0 script does this:</p>
<ol>
<li>Accepts an HTTP request: <code>http://server:port/maximo/oslc/script/CREATEWO?_lid=wilson&_lpwd=wilson&f_wonum=LWO0382&f_description=LEGACY WO&f_classstructureid=1666&f_status=APPR&f_wopriority=1&f_assetnum=LA1234&f_worktype=CM</code></li>
<li>Loops through parameters:
<ul>
<li>Searches for parameters that are prefixed with <code>f_</code> (<em>'f'</em> is for field-value)</li>
<li>Puts the parameters in a list</li>
<li>Removes the prefix from the list values (so that the parameter names match the database field names).</li>
</ul>
</li>
<li>Updates or creates records via the parameters in the list:
<ul>
<li>If there is an existing record in the system with the same work order number, then the script updates the exiting record with the parameter values from the list.</li>
<li>If there isn't an existing record, then a new record is created (again, from the parameter values from the list).</li>
</ul>
</li>
<li>Finishes by returning a message to the external system (message: updated, created, or other (aka an error)).</li>
</ol>
<hr />
<pre><code>from psdi.mbo import SqlFormat
from psdi.server import MXServer
from psdi.mbo import MboSet
IGNORE_RULES = 2L
params = [
param for param in request.getQueryParams()
if param.startswith('f_')
]
paramdict = {
p[2:]: request.getQueryParam(p)
for p in params
}
resp=''
woset = MXServer.getMXServer().getMboSet("workorder",request.getUserInfo())
try:
#Prevents SQL injection
sqf = SqlFormat("wonum=:1")
sqf.setObject(1,"WORKORDER","WONUM",request.getQueryParam("f_wonum"))
woset.setWhere(sqf.format())
woset.reset()
woMbo = woset.moveFirst()
if woMbo is None:
woMbo=woset.add()
verb = 'Created'
else:
verb = 'Updated'
for k,v in paramdict.items():
woMbo.setValue(k,v,2L)
resp = verb + ' workorder ' + request.getQueryParam("f_wonum")
woset.save()
woset.clear()
woset.close()
finally:
woset.close()
responseBody = resp
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T13:53:19.963",
"Id": "481239",
"Score": "0",
"body": "I have rolled back your edit since it invalidates an answer."
}
] |
[
{
"body": "<p>You haven't used this:</p>\n<pre><code>IGNORE_RULES\n</code></pre>\n<p>in your call to <code>setValue</code>.</p>\n<p>Also, you have a double call to <code>close</code>; delete the first one.</p>\n<p><code>resp</code> does not benefit from being pre-initialized to an empty string; you can delete that line.</p>\n<p>The only other thing I see is that this:</p>\n<pre><code>params = [\n param for param in request.getQueryParams()\n if param.startswith('f_')\n]\nparamdict = {\n p[2:]: request.getQueryParam(p)\n for p in params\n}\n</code></pre>\n<p>can be condensed to only the dictionary comprehension:</p>\n<pre><code>paramdict = {\n p[2:]: request.getQueryParam(p)\n for p in request.getQueryParams()\n if p.startswith('f_')\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T13:40:11.537",
"Id": "245080",
"ParentId": "245073",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245080",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T12:13:15.433",
"Id": "245073",
"Score": "2",
"Tags": [
"python",
"python-2.x",
"http",
"jython"
],
"Title": "Part 2: Create or update record via HTTP request"
}
|
245073
|
<p>I have an api endpoint that, when called, initiates the generation of a report. This is time consuming process and response could come pretty late. So, we came up with caching architecture and once finished the response is saved to redis.</p>
<p>However, on the frontend side we dicided to make a request once in a while, until it is ready. To face the issue of overlapping queries when one report is initialized several times in a row, I decided to make a temporary file, that exists only when the report is being generated, and the api response is "This report is already being generated". Once the generation is finished, file is deleted and response is already cached.</p>
<p>This is mockup of what I am doing</p>
<pre><code>def post(self):
serialized_data = self.serializer().deserialize({
'task': json.loads(request.values.get('task')),
'media_company': json.loads(request.values.get('mediaCompany'))
})
if not os.path.exists('/root/progress_data'):
os.mkdir('/root/progress_data')
self.build_range(serialized_data)
serialized_data['media_company']['date_from'] = \
self.date_from.strftime("%Y-%m-%d")
serialized_data['media_company']['date_to'] = \
self.date_to.strftime("%Y-%m-%d")
progress_hash = hashlib.sha256(str(serialized_data).encode()).hexdigest()
if self.progress_check(progress_hash):
return json_response({
"success": False,
'result': "This report is already being generated",
})
file = open(f'/root/progress_data/{progress_hash}', 'w+')
file.close()
try:
report = self.generate_report(serialized_data)
except:
os.remove(f'/root/progress_data/{progress_hash}')
return json_response({
"success": False,
'result': "Error while generating report",
})
os.remove(f'/root/progress_data/{progress_hash}')
return json_response({
"success": True,
'data': report,
})
</code></pre>
<p>I think that this is not really production-ready solution, but I could not come up with something better.</p>
<p>Also, there are some holes where the file is not being deleted in all cases.</p>
<p>Could you show me potential holes and may be another way of checking the progress</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:07:26.950",
"Id": "481244",
"Score": "1",
"body": "Is this the actual code, or a mockup of the code? On code review we review working code that you have written. If this is not the actual code then the question is off-topic and may be closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:26:20.693",
"Id": "481259",
"Score": "0",
"body": "@Anonymous writes _I am not sure your question really belong here. We can comment on code that is working as expected but could be perfectible. Your code has holes as you put it, so it cannot be considered a finished piece of work._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:47:38.490",
"Id": "481261",
"Score": "0",
"body": "You need to show the code for `generate_report`."
}
] |
[
{
"body": "<p>There is nothing I can test here, so I will only make a couple superficial remarks.</p>\n<p>You do not offer a lot of insight into your application. If you say you have a problem with overlapping queries, then you should address the root of the problem. I have the impression that you simply devised a <strong>workaround</strong>. It may do the job but at the expense of performance or reliability. It could also create more problems.</p>\n<h1>Repetition</h1>\n<p>What is immediately apparent is that you have a hardcoded path repeated multiple times across your code.\nAt the top of your code you should define a variable for '/root/progress_data'. Then if you decide to change the file name or path you will have only one line to change.</p>\n<p>But Python has a library for <strong>temp files</strong>: <a href=\"https://docs.python.org/3/library/tempfile.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/tempfile.html</a>. This is what you should be using.</p>\n<p>The date format <code>"%Y-%m-%d"</code> could be made a variable too.</p>\n<h1>Security</h1>\n<p>Does your program really need to run as root ?</p>\n<h1>Maximize your try/catch/finally blocks</h1>\n<p>You repeat this twice:</p>\n<pre><code>os.remove(f'/root/progress_data/{progress_hash}')\n</code></pre>\n<p>To ensure that the file gets removed at the end of the process you could place this line of code in a <strong>finally</strong> block.</p>\n<p>Same goes for the return value:</p>\n<pre><code>return json_response({\n "success": False,\n 'result': "Error while generating report",\n})\n\nreturn json_response({\n "success": True,\n 'data': report,\n})\n</code></pre>\n<p>Keep only one return but use variables for the response depending on the outcome of the execution.</p>\n<p>Thus your code will be shorter, more straightforward and easier to comprehend. But I still think the idea is wrong.</p>\n<p>I would probably use a database instead of temp files. It can be a small self-contained DB file like SQLite. You need a simple table with details of the job, some kind of unique identifier and a column to update the status of the job. Then your API can query the table and say "ready" when the column has been to updated to the finished status.</p>\n<p>This looks clumsy to me. I would ditch the idea and go back to the drawing board. If you are stuck my suggestion would be to post on Stack Overflow for guidance but add more context to your question, explain how the API is used, what your constraints are.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:36:35.493",
"Id": "481260",
"Score": "0",
"body": "_Does your program really need to run as root?_ - a million times this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:17:44.240",
"Id": "245087",
"ParentId": "245074",
"Score": "2"
}
},
{
"body": "<h2>Round-trips for serialization</h2>\n<p>You start with this:</p>\n<pre><code>request.values.get('task')\n</code></pre>\n<p>Then <code>loads</code> it to (presumably) a dictionary; wrap it in an outer dictionary; and then immediately <code>deserialize</code> it. This seems a little awkward. If <code>task</code> is a serialized representation that needs special deserialization logic, then can you factor out a section of <code>deserialize</code> and only call that, rather than these intermediate steps?</p>\n<h2>Do not run as root</h2>\n<p>This is stated by @Anonymous and bears repeating. Do not run as root. This is dangerous and bad. You should be making a service user with limited permissions and running this script as that user. In addition, consider replacing this:</p>\n<pre><code>/root/progress_data\n</code></pre>\n<p>with a subdirectory of <code>var</code> whose permissions are restricted to the service user.</p>\n<h2>Dict updates</h2>\n<pre><code>serialized_data['media_company']['date_from'] = \\\n self.date_from.strftime("%Y-%m-%d")\nserialized_data['media_company']['date_to'] = \\\n self.date_to.strftime("%Y-%m-%d")\n</code></pre>\n<p>can be</p>\n<pre><code>serialized_data['media_company'].update({\n 'date_from': self.date_from.strftime("%Y-%m-%d"),\n 'date_to': self.date_to.strftime("%Y-%m-%d"),\n})\n</code></pre>\n<h2>Choose a string style</h2>\n<p>i.e. single or double quotes, rather than</p>\n<pre><code>'result': "This report is already being generated"\n</code></pre>\n<h2>Creation-closure</h2>\n<p>This block:</p>\n<pre><code>file = open(f'/root/progress_data/{progress_hash}', 'w+')\nfile.close()\ntry:\n report = self.generate_report(serialized_data)\nexcept:\n os.remove(f'/root/progress_data/{progress_hash}')\n return json_response({\n "success": False,\n 'result': "Error while generating report",\n })\nos.remove(f'/root/progress_data/{progress_hash}')\n</code></pre>\n<p>has a few issues:</p>\n<ul>\n<li>Rather than an explicit <code>close</code>, put the <code>open</code> in a <code>with</code></li>\n<li>As @Anonymous says, move your <code>remove</code> to a <code>finally</code> and de-duplicate it</li>\n<li>Form the progress file path using <code>pathlib.Path</code></li>\n<li>Store the path to a temporary variable rather than re-calculating it three times.</li>\n<li>Do not base the name of the file on a hash, and do not open it yourself; allow <code>tempfile</code> to name and open it for you. If necessary, you can control the temporary file's directory with the <code>dir</code> argument.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:50:35.073",
"Id": "245090",
"ParentId": "245074",
"Score": "1"
}
},
{
"body": "<h3>possible race condition</h3>\n<p>This code seem to have a race condition:</p>\n<pre><code>if self.progress_check(progress_hash):\n return json_response({\n "success": False,\n 'result': "This report is already being generated",\n })\n\nfile = open(f'/root/progress_data/{progress_hash}', 'w+')\n</code></pre>\n<p>The question doesn't say what server is being used, but it presumably uses threads, processes or async techniques. After a first thread or process executes the <code>if</code> statement but before the file gets opened, other threads or processes could pass the <code>if</code> statement. This can result in multiple computations, multiple files, trying to delete a file multiple times, etc. I think some kind of lock or semaphore may be needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T01:32:53.917",
"Id": "245107",
"ParentId": "245074",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245087",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T12:16:51.147",
"Id": "245074",
"Score": "2",
"Tags": [
"python",
"api",
"flask"
],
"Title": "Track the existence of process"
}
|
245074
|
<p>I had a need to build a standardized layout for content on many of the pages of my website based on data returned from my web service but the project I'm doing this on is already bloated with stuff from previous developers and since I don't know what I can take out without destroying functionality, I needed a way to do it without adding anymore bloat.</p>
<p>I used a <code>template</code> control and regex in string replacement which serves my purposes very well and in the simplest manner that I can think of. My only query is whether or not I can do it without putting the template on the page.</p>
<p>The designer looks after the markup and styles for the template; my job is to just make sure that the content on the site follows it.</p>
<p>Weird thing for me is that I have my content for the page and then at the bottom I have this base template that the content is built from. It seems like an odd extra that probably isn't necessary in an ideal situation. The boss doesn't like the idea of storing the template in the database so that's off the table...</p>
<pre><code><template id="vacancyTemplate">
<article class="post-content">
<div class="comments">
<ul class="comment-list">
<li>
<article class="comment">
<div class="comment-content">
<div style="padding:0;" class="cell-2">
<img style="width:100%; height:100%" src="{img}" />
</div>
<div class="cell-10">
<h5 class="comment-author">
<span class="author-name"><a href="{link}">{title}</a></span>
<span class="author-name"><a href="#">{code}</a></span>
<a class="comment-reply main-bg" onclick="{favoriteLink}" title="{favoriteTitle}" style="cursor: pointer;"><i class="fa fa-star"></i></a>
</h5>
<div style="display:flex;flex-direction:column" class="infomation">
<span>{company}</span>
<span><br/></span>
<span><strong>{location}</strong></span>
<span><br /></span>
<span>{details}... <a style="padding-left: 15px" href="{link}">VIEW MORE</a></span>
</div>
</div>
</div>
</article>
</li>
<li>
<div class="post-info-container post-meta">
<div class="post-info post-meta">
<div class="cell-9">
<ul style="display: flex; flex-direction: column; float: left; margin-top: 3.5%; margin-bottom: 3%; width: 100%;" class="post-meta">
<li class="meta-user"><i class="fa fa-user"></i><a href="#">{experience}</a></li>
<li><i class="fa fa-folder-open"></i> <a href="#">{salary}</a></li>
<li class="meta-comments"><i class="fa fa-pencil"></i>{employment}</li>
</ul>
</div>
<div style="margin-top:4.3%;" class="cell-3">
<ul class="post-meta">
<li>Post : {postDate}<br /></li>
<li>Closing date : {closeDate}</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</div>
</article>
</template>
<script>
const options = { method: "GET", cache: "no-cache", headers: { "Content-Type": "application/json" } };
window.onload = async function () {
await loadVacanciesAsync();
}
async function loadVacanciesAsync() {
const vacancyPromise = new Promise((resolve, reject) => {
fetch("/Services/VacancyWebService.asmx/GetDriverVacancies", options)
.then((resp) => resp.json())
.then((json) => {
const data = json.d;
if (data.Result === "Success") {
const vacancies = data.Data;
resolve(vacancies);
}
else {
if (data.Error.Message === "Non-static method requires a target.") {
const container = document.querySelector(".blog-posts");
const a = document.createElement("a");
a.setAttribute("href", "/Users/MyAccountInformation");
a.innerText = "updating your profile.";
const p = document.createElement("p");
p.innerText = "No vacancies were found to match your profile. Consider ";
p.appendChild(a);
container.appendChild(p);
}
reject();
}
});
});
const vacancies = await vacancyPromise;
if (typeof vacancies !== 'undefined' && vacancies.length > 0) {
const favoritesPromise = new Promise((resolve, reject) => {
fetch("/Services/VacancyWebService.asmx/GetFavorites", options)
.then((resp) => resp.json())
.then((json) => {
const data = json.d;
if (data.Result === "Success") {
const favorites = data.Data;
resolve(favorites);
}
else {
// Do something here if there's an error getting favorites.
}
});
});
const favorites = await favoritesPromise;
sessionStorage.setItem("pageData", JSON.stringify(vacancies));
sessionStorage.setItem("pageFavorites", JSON.stringify(favorites));
loadData();
const pagerMarkup = loadPager();
const pager = document.querySelector(".pager");
pager.innerHTML = pagerMarkup;
}
else {
const container = document.querySelector(".blog-posts");
const a = document.createElement("a");
a.setAttribute("href", "/Users/MyAccountInformation");
a.innerText = "updating your profile.";
const p = document.createElement("p");
p.innerText = "No vacancies were found to match your profile. Consider ";
p.appendChild(a);
container.appendChild(p);
}
}
function loadData(start) {
// Load data out of session storage.
if (start === undefined) {
start = 0;
}
else {
start = (start - 1) * pageSize;
}
let end = start + pageSize;
const sessionData = JSON.parse(sessionStorage.getItem("pageData"));
const subset = sessionData.slice(start, end);
buildVacancyArticles(subset);
}
function buildVacancyArticles(vacancies) {
const favorites = JSON.parse(sessionStorage.getItem("pageFavorites"));
const container = document.querySelector(".blog-posts");
container.innerHTML = ""; // Clear the markup for the previous set.
let template = document.getElementById("vacancyTemplate").innerHTML;
for (const vacancy of vacancies) {
let t = template;
const isFavorite = favorites.includes(vacancy);
if (isFavorite) {
t = t.replace(/{favoriteLink}/g, `removeFavorite(this, ${vacancy.Id});`);
t = t.replace(/{favoriteTitle}/g, "Remove from Favorites");
}
else {
t = t.replace(/{favoriteLink}/g, `addFavorite(this, ${vacancy.Id});`);
t = t.replace(/{favoriteTitle}/g, "Add to Favorites");
}
let imgSrc = "";
if (vacancy.LogoType !== undefined && vacancy.LogoType !== "") {
if (vacancy.LogoImage !== null) {
imgSrc = `${vacancy.LogoType};base64=${vacancy.LogoImage}`;
}
}
t = t.replace(/{img}/g, imgSrc);
t = t.replace(/{link}/g, `/Vacancies/Vacancy_Full.aspx/${vacancy.Id}`);
t = t.replace(/{title}/g, vacancy.Title);
t = t.replace(/{code}/g, vacancy.LicenseCode);
const company = vacancy.Business !== undefined ? vacancy.Business.Name : "Company Name";
t = t.replace(/{company}/g, company)
t = t.replace(/{location}/g, vacancy.Location);
t = t.replace(/{details}/g, vacancy.Details);
t = t.replace(/{experience}/g, vacancy.Experience);
t = t.replace(/{salary}/g, vacancy.Salary);
t = t.replace(/{employment}/g, vacancy.EmploymentType);
t = t.replace(/{postDate}/g, vacancy.DateString);
t = t.replace(/{closeDate}/g, vacancy.CloseDateString);
container.innerHTML += t;
}
}
</script>
</code></pre>
|
[] |
[
{
"body": "<p>From a quick review;</p>\n<ul>\n<li><p>You could host your templates as separate HTML files, retrievable with a <code>fetch</code></p>\n<ul>\n<li>You would have the overhead of extra http calls</li>\n<li>HTML tooling might be worse for HTML templates/snippets</li>\n</ul>\n</li>\n<li><p>I agree with your boss, html code does not belong in a database</p>\n</li>\n<li><p><code>template</code> should be <code>const</code></p>\n<pre><code> let template = document.getElementById("vacancyTemplate").innerHTML;\n for (const vacancy of vacancies) {\n let t = template;\n</code></pre>\n</li>\n<li><p>You could consider a less manual approach to filling in the values</p>\n<pre><code>function fillOutTemplate(t, object){\n Object.keys(object).forEach(key => t = t.replace(new RegExp(key, 'g'), object[key]) );\n return t; \n}\n</code></pre>\n<p>and calling <code>t = fillOutTemplate(t, Vacancy);</code> could save a ton of coding once you harmonize the Vacancy properties and the template.</p>\n</li>\n<li><p>It looks odd that not finding entries return the message <code>"Non-static method requires a target."</code>, it makes the hacker in me find out that this is most likely a LINQ error and wonder if I can pass different parameters to abuse this knowledge</p>\n</li>\n<li><p>You create 3 'a' link tags from scratch, consider a helper routine for this.</p>\n</li>\n<li><p>I know someone else runs with the styling, but that inline styling is rough though..</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:29:36.050",
"Id": "245085",
"ParentId": "245078",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T13:23:28.153",
"Id": "245078",
"Score": "2",
"Tags": [
"javascript",
"template"
],
"Title": "Building content templates with javascript and no 3rd party library"
}
|
245078
|
<p>I've written a little program that I need for fixing two problems in my spherical panorama images.</p>
<p>It does two things:</p>
<ul>
<li>If the image does overlap horizontally, it cuts away the overlapping pixels from the right side.</li>
<li>It fills up the image vertically with black, so that it has a ratio of 2 to 1.</li>
</ul>
<p>I'm not too experienced with C++ and I'd like to know if there's anything "strange" in the code I've written. I hope the program is not too simple but I'd just like to get things correct right from the beginning.</p>
<p>I'm using Visual Studio and the OpenImageIO library for reading/writing images.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <OpenImageIO/imageio.h>
#include <vector>
#include <cmath>
// Little helper to not mess around with channel offset.
struct Pixel {
unsigned char r;
unsigned char g;
unsigned char b;
};
// Puts the data from "data" into "buffer" in regard of width and height.
// Assuming that "data" stores 3 channels (RGB) per pixel.
void pushPixels(std::vector< std::vector<Pixel> >& buffer, const std::vector<unsigned char>& data, int width, int height) {
for (int h = 0; h < height; ++h) {
std::vector<Pixel> line;
for (int w = 0; w < width; ++w) {
Pixel p = {
data[h * width * 3 + w * 3 + 0],
data[h * width * 3 + w * 3 + 1],
data[h * width * 3 + w * 3 + 2]
};
line.push_back(p);
}
buffer.push_back(line);
}
}
// Push pixels from "pixels" into "buffer" while considering the "offset" and "length".
// Each row from "pixels" will be copied into "buffer" from "offset" to "offset + length".
// Putting the pixel channels one by one into "buffer".
void pushData(const std::vector< std::vector<Pixel> >& pixels, std::vector<unsigned char>& buffer, int offset, int length) {
for (const std::vector<Pixel>& line : pixels) {
for (int i = offset; i < offset + length; ++i) {
buffer.push_back(line[i].r);
buffer.push_back(line[i].g);
buffer.push_back(line[i].b);
}
}
}
// Returning the difference on two pixels by checking each channel and summing up the absolute distance.
double pixelDifference(const Pixel& p1, const Pixel& p2) {
double error = 0;
error += std::abs(p1.r - p2.r);
error += std::abs(p1.g - p2.g);
error += std::abs(p1.b - p2.b);
return error;
}
// Copare first column of pixels from "pixels" to the last, last - 1, last -2 ...
// When the difference between the first and the current column
// is smaller than "threshold", chop all columns from there away.
void chopOverlap(std::vector< std::vector<Pixel> >& pixels, double threshold) {
int width = pixels[0].size();
int height = pixels.size();
int chopOffset = 0;
for (int w = width - 1; w > 0; --w) {
double error = 0;
for (int h = 0; h < height; h++) {
error += pixelDifference(pixels[h][0], pixels[h][w]);
}
error /= height;
if (error < threshold) { break; }
chopOffset++;
}
if ((width - chopOffset) % 2 == 1) {
++chopOffset;
}
std::cout << "chopping " << chopOffset << " from right" << std::endl;
for (std::vector<Pixel>& line : pixels) {
for (int i = 0; i < chopOffset; i++) {
line.pop_back();
}
}
}
// Fill bottom of "pixels" with black rows until the image ration is 2 to 1.
void fill(std::vector< std::vector<Pixel> >& pixels) {
int width = pixels[0].size();
int height = pixels.size();
int nFills = width / 2 - height;
for (int i = 0; i < nFills; ++i) {
std::vector<Pixel> line;
for (int w = 0; w < width; ++w) {
Pixel p = {0, 0, 0};
line.push_back(p);
}
pixels.push_back(line);
}
}
int main(int argc, char* argv[])
{
std::string inFile(argv[1]);
std::string outFile(argv[2]);
std::cout << "input : " << inFile << std::endl;
std::cout << "output: " << outFile << std::endl;
// Read file.
std::unique_ptr<OIIO::ImageInput> in = OIIO::ImageInput::open(inFile.c_str());
if (!in) { return EXIT_FAILURE; }
const OIIO::ImageSpec& inSpec = in->spec();
const int inWidth = inSpec.width;
const int inHeight = inSpec.height;
const int nchannels = inSpec.nchannels;
std::cout << "resolution " << inWidth << "x" << inHeight << std::endl;
std::vector<unsigned char> inBuf(inWidth * inHeight * nchannels);
in->read_image(OIIO::TypeDesc::UINT8, &inBuf[0]);
in->close();
// Create buffer to work on.
std::vector< std::vector<Pixel> > data;
pushPixels(data, inBuf, inWidth, inHeight);
// Chop overlapping area.
chopOverlap(data, 12);
// Fill with black.
fill(data);
const char* filename = outFile.c_str();
const int outWidth = data[0].size();
const int outHeight = data.size();
std::vector<unsigned char> outBuf;
std::cout << "new resolution " << outWidth << "x" << outHeight << std::endl;
// Push data.
pushData(data, outBuf, 0, outWidth);
// Write file.
std::unique_ptr<OIIO::ImageOutput> out = OIIO::ImageOutput::create(filename);
if (!out) { return EXIT_FAILURE; }
OIIO::ImageSpec outSpec(outWidth, outHeight, nchannels, OIIO::TypeDesc::UINT8);
out->open(filename, outSpec);
out->write_image(OIIO::TypeDesc::UINT8, &outBuf[0]);
out->close();
return EXIT_SUCCESS;
}
</code></pre>
|
[] |
[
{
"body": "<p>You define images as <code>std::vector< std::vector<Pixel> ></code>. I strongly recommend against this: this is an inefficient storage for a rectangular array of data, with several downsides and no upsides. The biggest issue with a vector of vectors is that each line of the image is stored in a separate memory block on the heap, meaning that a memory block is allocated <code>height+1</code> times, instead of only once. Accessing a pixel requires two indexing operations instead of one, and two fetches from different locations in memory, instead of one. Using a simple <code>std::vector<Pixel></code>, with an associated <code>width</code> value, is the recommended way of storing pixels (all well-known image manipulation libraries do it this way). Indexing, instead of <code>image[y][x]</code> becomes <code>image[x + y*width]</code>. Encapsulate this in a class and you're all set:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Image {\n std::vector<Pixel> data;\n int width;\n int height;\npublic:\n Image(int width, int height) {\n data.resize(width * height);\n }\n Pixel& at(int x, int y) {\n // we could add an assert here to ensure x and y are inside the image\n return data[x + width * y];\n }\n}\n</code></pre>\n<p>Note that, since C++11, it is possible to write <code>std::vector<std::vector<Pixel>></code>, the space between the two closing <code>></code> is no longer needed. You're not stating which version of the standard you are using. I highly recommend that, since you're starting a new project, you pick the latest iteration of the standard (currently C++17), if your compiler supports it. Add an appropriate compiler flag for that.</p>\n<hr />\n<p>The functions <code>pushPixels</code> and <code>pushData</code> push into the vector. It would be beneficial, since we know how many elements will be pushed, to <code>reserve</code> the space first. Even cleaner, in my opinion, is to resize the vector and then use indexing to assign values into it.</p>\n<p>The function <code>pushPixels</code> indexes into <code>data</code> with the expression <code>h * width * 3 + w * 3 + 0</code>. Besides being repeated three times with a different offset (it would look simpler to compute this index once and increment it), to me this function screams for an iterator. You explicitly loop over the indices into <code>buffer</code> in the order in which values are stored in <code>data</code>. So create an iterator into data and increment it:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void pushPixels(std::vector<std::vector<Pixel>>& buffer, const std::vector<unsigned char>& data, int width, int height) {\n assert(data.size() == width * height * 3); // it's always good to add assertions for your assumptions\n auto it = data.begin();\n buffer.reserve(buffer.size() + height); // enlarge buffer\n for (int h = 0; h < height; ++h) {\n std::vector<Pixel> line(width);\n for (int w = 0; w < width; ++w) {\n line[w] = Pixel{ it++, it++, it++ };\n }\n buffer.push_back(std::move(line)); // avoid additional copy using std::move()\n }\n}\n</code></pre>\n<p>Finally, in regards to these two functions, their naming: it is not clear that the first copies data from the second to the first argument, and the other copies data from the first to the second argument. I recommend that you always define function arguments in the same order, for example <code>(input, output)</code>. This will reduce the surprise when reading the code. In <code>main</code>, you define your <code>Pixel</code> vector-of-vectors as <code>data</code>, then call <code>pushPixels(data, inBuf, ...)</code>. This actually copies values from <code>inBuf</code> to <code>data</code>, but you need to read the function's code to know. Later you call <code>pushData(data, outBuf, ...)</code>, which copies values from <code>data</code>, not to <code>data</code> (it's confusing because the function declaration calls its second argument "<code>data</code>").</p>\n<p>But, if you store your image data as I recommend above, these two functions will not be necessary at all. The I/O library you use writes the data into a buffer in the same order, so no copies are necessary.</p>\n<hr />\n<p>A possible problem in your program is that you define</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>const int nchannels = inSpec.nchannels;\n</code></pre>\n<p>but then don't use it. You assume that your data buffer has 3 channels. The least you can do is verify that <code>nchannels==3</code>, and throw an exception if it's not. Some image files have 4 channels, in which case your output will be mangled. Some image files have 1 channel, in which case you will be reading out of bounds and possibly crash your program.</p>\n<hr />\n<p><code>std::endl</code> not only adds a newline to the stream, it also flushes it. So unless you need to explicitly flush your stream, don't use it. A simple <code>'\\n'</code> is just as easy to write to the stream, and doesn't incur the overhead of unnecessarily flushing the stream.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T15:07:43.433",
"Id": "481366",
"Score": "0",
"body": "Thank you much for the great review and tipps!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T05:40:47.507",
"Id": "245116",
"ParentId": "245081",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245116",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T14:03:02.440",
"Id": "245081",
"Score": "3",
"Tags": [
"c++",
"image"
],
"Title": "Program for chopping overlapping image areas and filling up to a specific ratio"
}
|
245081
|
<p>Having coded in Objected-Oriented style my entire programming career, it's hard to adapt to functional style fully.</p>
<p>I implemented a simple Hangman game:</p>
<pre class="lang-hs prettyprint-override"><code>{- A simple gameLoop of hangman.-}
module Hangman where
import qualified Data.Set as Set
import qualified System.IO as IO
import qualified System.Random as Rand
import Control.Monad.State
import Control.Monad.IO.Class(liftIO)
{-
Letter : Letters of word
Term : Word to guess (type name Term to avoid ambiguity)
Guessed : Already guessed characters
Status : Status of game
-}
data Letter = Hidden Char | Revealed Char deriving (Eq)
type Term = [Letter]
type Guessed = Set.Set Char
data Hangman = Hangman {word :: Term,
lives :: Int,
guessedChars :: Guessed}
data Status = Playing | Defeat | Victory | Repeat deriving (Show)
charShowLetter :: Letter -> Char
charShowLetter (Hidden _) = '_'
charShowLetter (Revealed char) = char
instance Show Hangman where
show (Hangman word lives guessedChars) =
showTerm word ++ " Lives: " ++ show lives ++
"\nGuesses so far: " ++ showGuessed guessedChars
where showGuessed = Set.elems
showTerm = map charShowLetter
main = do
IO.hSetEcho IO.stdin False
IO.hSetBuffering IO.stdin IO.NoBuffering
playGame sampleMan
playGame :: Hangman -> IO (Status, Hangman)
playGame = runStateT gameLoop
gameLoop :: StateT Hangman IO Status
{-
Gets character from stdin, guesses it,
and then performs action based on the guess result.
Loops back to the begin if game hasn't ended.
Seems basically like procedural programming...
-}
gameLoop = do
newGuess <- liftIO IO.getChar
liftIO $ putStrLn $ "Your guess: " ++ [newGuess]
hangman <- get
let (val, newHangman) = runState (guess newGuess) hangman
case val of
Repeat -> do
put hangman
liftIO $ putStrLn "You already tried that.\n"
gameLoop
Victory -> liftIO $ putStrLn "\nVictory!" >> return Victory
Defeat -> liftIO $ putStrLn "\nDefeat!" >> return Defeat
Playing -> do
put newHangman
liftIO $ putStrLn $ show newHangman ++ "\n"
gameLoop
guess :: Char -> State Hangman Status
{-
Obnoxious function that returns
the hangman state and game state after a guess.
Args : Char
guessed character
Returns: State Hangman Status
runState will return (Status, Hangman.)
-}
guess guessChar = do
h@(Hangman word lives guessedChars) <- get
if guessChar `elem` guessedChars
then do -- If char was already guessed, prompt user to repeat
put h
return Repeat
else do
let decrementedLives = lives - 1
newGuessedChars = Set.insert guessChar guessedChars
if Hidden guessChar `elem` word -- If guess is correct
then do
let updatedWordStatus = updateWord word guessChar
put (Hangman updatedWordStatus decrementedLives newGuessedChars)
return $ hasWon updatedWordStatus -- If won, return Victory
else
if decrementedLives == 0
then return Defeat
else do -- Keep playing!
put (Hangman word decrementedLives newGuessedChars)
return Playing
updateWord :: Term -> Char -> Term
-- When we get a correct guess, update hidden char to revealed.
updateWord word newChar = map helper word
where helper hidden@(Hidden hiddenChar) =
if hiddenChar == newChar then Revealed newChar else hidden
helper val = val
hasWon :: Term -> Status
-- If all letters are revealed, game is won.
hasWon word = if all helper word then Victory else Playing
where helper (Hidden _) = False
helper (Revealed _) = True
-- Hardcoded samples to test code.
sampleWord = [Hidden 'a', Hidden 'p',
Hidden 'p', Hidden 'l', Hidden 'e']
sampleMan = Hangman sampleWord 7 (Set.fromList [])
</code></pre>
<p>However, I feel like this code isn't really that functional programming, because...</p>
<ol>
<li>The Hangman ADT serves a rough implementation of a class.</li>
<li>The main functions, <code>gameLoop</code> and <code>guess</code>, are basically more or less the same code in procedural programming.</li>
<li>All the functions are basically class methods for the Hangman ADT, just not instantiated as such.</li>
</ol>
<p>After all, as the famous saying goes, <a href="https://www.ee.ryerson.ca/%7Eelf/hack/realmen.html" rel="noreferrer">you can write FORTRAN in any language</a>.</p>
<p>Any critiques, suggestions, improvements are highly welcome.</p>
<p>Thank you in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T06:15:59.850",
"Id": "481433",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<h1>Prelude</h1>\n<p>First of all, good work! I can see the effort you put into grokking something so foreign, and I would like to commend you for it. I will be focusing on reviewing what I think you can improve, but don't let these critiques discourage you—all code can be improved, but not all code works.</p>\n<p>I'll be doing a combination of making general comments and addressing blocks of code, in order from top to bottom. In each section the code will generally not be runnable, since I'll be putting side-by-side comparisons of your code and my code. I'll include the full revision at the end.</p>\n<p>I'm not the foremost expert on all things Haskell, so take my comments however you wish. I hope they help!</p>\n<h1>Comments</h1>\n<p>I recommend using <a href=\"https://haskell-haddock.readthedocs.io/en/latest/markup.html\" rel=\"nofollow noreferrer\">haddock</a> syntax to markup your comments. In my revised code, I use this syntax.</p>\n<h1>Use of <code>StateT</code></h1>\n<p>Since this is an exercise, I think it's fine to use <code>StateT</code> so you can learn how to work with monad stacks. But since the <code>Hangman</code> datatype is so simple, you could also just pass it throughout your functions. If I were making hangman, I would probably do this since why bother with the complexity of having a monad stack when it's just as convenient to write regular functions?</p>\n<p>One way you can refactor is to observe that <code>State a s</code> is essentially equivalent to <code>s -> (a, s)</code>, so you could, say, pass around tuples instead. You could also make your <code>guess</code> function be of type <code>Hangman -> Hangman</code> so that it modifies the game state and then you could decide in <code>gameLoop</code> what status to return. In this case, you wouldn't even need to pass around tuples.</p>\n<h1>Type aliases</h1>\n<p>When you have a monad stack (in your case, <code>StateT Hangman IO</code>), it's common to see people make a type alias for it like <code>type HangmanM a = StateT Hangman IO a</code>. I think you need to explicitly take the type variable as an argument, but you may be able to avoid it.</p>\n<p>You only use this stack once, so you don't really need to make an alias – I did because I end up using it twice due to a revision.</p>\n<h1>Smart constructors</h1>\n<p>Later in your code you make a sample <code>Hangman</code> value manually. You might eventually want to make arbitrary <code>String</code>s and <code>Int</code>s into these values, so it's conventional to make a smart constructor like so</p>\n<pre class=\"lang-hs prettyprint-override\"><code>mkHangman :: String -> Int -> Hangman\nmkHangman word lives = Hangman (map Hidden word) lives Set.empty\n</code></pre>\n<p>You'll see that I define <code>sampleMan</code> as <code>mkHangman "apple" 7</code>.</p>\n<h1><code>playGame</code></h1>\n<p>I think it makes more sense to have game-ending logic in <code>playGame</code>, so I pattern match on the output of <code>runStateT gameLoop hangman</code> and print based on it.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>-- Yours\nplayGame :: Hangman -> IO (Status, Hangman)\nplayGame = runStateT gameLoop\n\n-- Mine\nplayGame :: Hangman -> IO ()\nplayGame hangman = do\n (status, _hangman') <- runStateT gameLoop hangman\n case status of\n -- You could print the number of guesses remaining here, if so desired.\n Victory -> putStrLn "Victory!"\n -- You could print what the word was here, if so desired.\n Defeat -> putStrLn "Defeat!"\n _ -> error $\n "Expected status to be Victory or Defeat, got " ++ show status ++ "."\n</code></pre>\n<h1><code>gameLoop</code></h1>\n<p>I don't really think that the general structure of this code is that bad. There's basically one place where you falter.</p>\n<p>You don't use your monad stack.</p>\n<p>The <code>State Hangman Status</code> returned by <code>guess</code> and the <code>StateT IO Hangman Status</code> returned by <code>gameLoop</code> are different stacks. You essentially pull the state out of the game loop and then reconstruct it for <code>guess</code>. You'll see that I change the type of <code>state</code> to be <code>StateT IO Hangman Status</code>. That way, I can just do <code>val <- guess newGuess</code> in order to get the result.</p>\n<p>Likewise, I don't have to worry about putting things back in the state. I let <code>guess</code> modify the state and then I pull the new state out to print it if <code>guess</code> returns <code>Playing</code>.</p>\n<p>You'll notice that this code isn't really that different aside from some reordering.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>-- Yours\ngameLoop :: StateT Hangman IO Status\ngameLoop = do\n newGuess <- liftIO IO.getChar\n liftIO $ putStrLn $ "Your guess: " ++ [newGuess]\n hangman <- get\n let (val, newHangman) = runState (guess newGuess) hangman\n case val of\n Repeat -> do\n put hangman\n liftIO $ putStrLn "You already tried that.\\n"\n gameLoop\n Victory -> liftIO $ putStrLn "\\nVictory!" >> return Victory\n Defeat -> liftIO $ putStrLn "\\nDefeat!" >> return Defeat\n Playing -> do\n put newHangman\n liftIO $ putStrLn $ show newHangman ++ "\\n"\n gameLoop\n\n-- Mine\ngameLoop :: HangmanM Status\ngameLoop = do\n newGuess <- liftIO IO.getChar\n liftIO $ putStrLn $ "Your guess: " ++ [newGuess]\n val <- guess newGuess\n case val of\n Repeat -> do\n liftIO $ putStrLn "You already tried that.\\n"\n gameLoop\n Playing -> do\n newHangman <- get\n liftIO $ putStrLn (show newHangman ++ "\\n")\n gameLoop\n Victory -> return Victory\n Defeat -> return Defeat\n</code></pre>\n<h1><code>guess</code></h1>\n<p>I pretty much refactored <code>gameLoop</code> by offloading some extra work to <code>guess</code>. This function is very different. One thing I used to help simplify it was the language <a href=\"https://www.schoolofhaskell.com/school/to-infinity-and-beyond/pick-of-the-week/guide-to-ghc-extensions/basic-syntax-extensions#multiwayif\" rel=\"nofollow noreferrer\">pragma <code>MultiWayIf</code></a> to construct multiple branches of an <code>if</code> statement at the same depth. It makes the code look a lot cleaner without so many <code>if then else</code>s.</p>\n<p>Since <code>guess</code> and <code>gameLoop</code> share the same monad stack, I can just <code>get</code> the current state and use <code>put</code> to modify it. I only use <code>put</code> if the state is being changed, which saves some work.</p>\n<p>I also left some things for you to add if you wanted to—your code doesn't handle upper/lower case and erroneous characters (e.g. '1' or '¢').</p>\n<pre class=\"lang-hs prettyprint-override\"><code>-- Yours\nguess :: Char -> State Hangman Status\nguess guessChar = do\n h@(Hangman word lives guessedChars) <- get\n if guessChar `elem` guessedChars \n then do -- If char was already guessed, prompt user to repeat\n put h\n return Repeat\n else do\n let decrementedLives = lives - 1\n newGuessedChars = Set.insert guessChar guessedChars \n if Hidden guessChar `elem` word -- If guess is correct\n then do \n let updatedWordStatus = updateWord word guessChar\n put (Hangman updatedWordStatus decrementedLives newGuessedChars)\n return $ hasWon updatedWordStatus -- If won, return Victory\n else \n if decrementedLives == 0 \n then return Defeat\n else do -- Keep playing!\n put (Hangman word decrementedLives newGuessedChars)\n return Playing\n\n-- Mine\nguess :: Char -> HangmanM Status\nguess guessChar = do\n Hangman word lives guessedChars <- get\n let newLives = lives - 1\n if \n -- TODO: deal with invalid character guesses\n | False ->\n undefined\n | newLives <= 0 -> \n return Defeat\n | guessChar `elem` guessedChars ->\n return Repeat\n | otherwise -> do\n let updatedWord = updateWord word guessChar\n put $ Hangman updatedWord newLives (Set.insert guessChar guessedChars)\n return $ hasWon updatedWord\n where\n -- TODO: deal with letter case\n normalizedGuess = undefined\n</code></pre>\n<h1><code>updateWord</code> and <code>hasWon</code></h1>\n<p>I didn't really change these. I used a <a href=\"http://learnyouahaskell.com/syntax-in-functions#guards-guards\" rel=\"nofollow noreferrer\">guard</a> to simplify your helper for <code>updateWord</code> and renamed a few things. You can see the changes in the full code.</p>\n<h1>Full code</h1>\n<p>Feel free to ask about anything that I didn't comment on, whether it be my revised code or your initial code. Full disclaimer: I made pretty big changes and didn't write tests, so our versions may differ!</p>\n<pre class=\"lang-hs prettyprint-override\"><code>{-# LANGUAGE MultiWayIf #-}\n{- A simple gameLoop of hangman.-}\nmodule Hangman where\n\nimport qualified Data.Set as Set\nimport qualified System.IO as IO\nimport qualified System.Random as Rand\nimport Control.Monad.State\nimport Control.Monad.IO.Class(liftIO)\n\n-- | Letters comprising a hangman word.\ndata Letter \n = Hidden Char \n | Revealed Char \n deriving (Eq)\n\n-- | A hangman word in a game.\ntype Term = [Letter]\n\n-- | Guessed characters in a game.\ntype Guessed = Set.Set Char\n\n-- | A Hangman game.\ndata Hangman = Hangman { word :: Term -- ^ Guessed word so far.\n , lives :: Int -- ^ Number of lives.\n , guessedChars :: Guessed -- ^ Guessed characters.\n } \n\n-- Helper type alias for the Hangman monad stack.\ntype HangmanM a = StateT Hangman IO a\n\n-- | Smart constructor to make a hangman game with a fully hidden word and a \n-- certain number of lives.\nmkHangman :: String -> Int -> Hangman\nmkHangman word lives = Hangman (map Hidden word) lives Set.empty\n\n-- | Hangman game status.\ndata Status \n = Playing -- ^ Game in progress.\n | Defeat \n | Victory \n | Repeat -- ^ Repeat a turn.\n deriving (Show)\n\nletterToChar :: Letter -> Char\nletterToChar (Hidden _) = '_'\nletterToChar (Revealed char) = char\n\ninstance Show Hangman where\n show (Hangman word lives guessedChars) =\n unwords [ shownWord\n , " Lives: "\n , show lives\n , "\\nGuesses so far: "\n , shownGuessedChars\n ]\n where\n shownWord = map letterToChar word\n shownGuessedChars = Set.elems guessedChars\n\nmain = do\n IO.hSetEcho IO.stdin False\n IO.hSetBuffering IO.stdin IO.NoBuffering\n playGame sampleMan\n\nplayGame :: Hangman -> IO ()\nplayGame hangman = do\n (status, _hangman') <- runStateT gameLoop hangman\n case status of\n -- You could print the number of guesses remaining here, if so desired.\n Victory -> putStrLn "Victory!"\n -- You could print what the word was here, if so desired.\n Defeat -> putStrLn "Defeat!"\n _ -> error $\n "Expected status to be Victory or Defeat, got " ++ show status ++ "."\n\n-- | Gets character from stdin, guesses it,\n-- and then performs action based on the guess result.\n-- Loops back to the begin if game hasn't ended.\ngameLoop :: HangmanM Status\ngameLoop = do\n newGuess <- liftIO IO.getChar\n liftIO $ putStrLn $ "Your guess: " ++ [newGuess]\n val <- guess newGuess\n case val of\n Repeat -> do\n liftIO $ putStrLn "You already tried that.\\n"\n gameLoop\n Playing -> do\n newHangman <- get\n liftIO $ putStrLn (show newHangman ++ "\\n")\n gameLoop\n Victory -> return Victory\n Defeat -> return Defeat\n\n-- | Function that returns the hangman state and game state after a guess.\nguess :: Char -> HangmanM Status\nguess guessChar = do\n Hangman word lives guessedChars <- get\n let newLives = lives - 1\n if \n -- TODO: deal with invalid character guesses\n | False ->\n undefined\n | newLives <= 0 -> \n return Defeat\n | guessChar `elem` guessedChars ->\n return Repeat\n | otherwise -> do\n let updatedWord = updateWord word guessChar\n put $ Hangman updatedWord newLives (Set.insert guessChar guessedChars)\n return $ hasWon updatedWord\n where\n -- TODO: deal with letter case\n normalizedGuess = undefined\n\n-- | When we get a correct guess, update hidden char to revealed.\n-- Otherwise, do nothing.\nupdateWord :: Term -> Char -> Term\nupdateWord word guessChar = map helper word\n where \n helper (Hidden hiddenChar)\n | hiddenChar == guessChar = Revealed guessChar\n helper val = val\n\n-- | If all letters are revealed, game is won.\nhasWon :: Term -> Status\nhasWon word = if all isRevealed word then Victory else Playing\n where \n isRevealed (Hidden _) = False\n isRevealed (Revealed _) = True\n\n-- | Sample hangman word\nsampleMan = mkHangman "apple" 7\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T13:11:40.750",
"Id": "481549",
"Score": "0",
"body": "Thank you, this is amazing! So much cleaner code to read!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T13:13:48.820",
"Id": "481550",
"Score": "0",
"body": "That being said, in the `gameLoop` function, you just use `newHangman <- get` -- is it getting the state from `val <- guess newGuess` even though nothing is explicitly `put`? I couldn't figure this out by looking at simply the [docs](https://hackage.haskell.org/package/transformers-0.5.6.2/docs/Control-Monad-Trans-State-Lazy.html#t:StateT)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T16:52:54.253",
"Id": "481566",
"Score": "0",
"body": "Yes, it is getting the state that was modified by `guess newGuess`. The docs probably aren’t going to help much here if you’re confused. One way to see that it works is to mentally inline the code in `guess`. But what I recommend doing is writing out the monad instance for `newtype State a s = s -> (a,s)`. It’s not too bad if you follow the types. It might help to learn/remember how currying works in Haskell and that `a -> (b -> c) = a -> b -> c`. Once you know how `>>=` and `return` are implemented, you can desugar the `do` notation and see why it works."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:28:20.573",
"Id": "245167",
"ParentId": "245084",
"Score": "7"
}
},
{
"body": "<p>The code looks fine. At a high level, I don't think it really makes sense to say that this code follows a particularly object-oriented or functional style, maybe because the application is too simple. The difference in this case is really more a matter of perspective.</p>\n<p>From an OOP point of view, maybe you see a type with a bunch of methods. That's okay. (It's not too exciting when it doesn't involve more advanced ideas like subtyping and dynamic dispatch.)</p>\n<p>Well, FP looks at different things, even though you end up with the same code. The concrete language is what really guides the implementation, however you choose to approach it.</p>\n<ul>\n<li><p>Data representation using <strong>algebraic data types and pattern-matching</strong>, so you can tell upfront the shape of the data, and so that all cases are handled in one place for each function. In this example the difference with OO is hard to tell because the main type, <code>Hangman</code> is not a tagged union. Tagged unions as they're found in FP would typically be translated to multiple classes in OOP, with the implementation of each method split among them. I'm not saying either way is always better, they're just different approaches with their trade-offs (see also, "the expression problem").</p>\n</li>\n<li><p><strong>Pure functions, explicit effects</strong>: small auxiliary functions are pure, so you can tell without looking at their code that they're not going to surprise you with any side effect; similarly, more complex functions still have explicit types which delimit their abilities, you can't modify the wrong state unless it's already somewhere in the function's type.</p>\n</li>\n<li><p><strong>Higher-order functions</strong>: there are no loop constructs like <code>while</code> or <code>for</code> baked into the language, instead there is explicit recursion which is often hidden behind functions to iterate or transform a computation following some common patterns (<code>map</code>, <code>all</code>).</p>\n</li>\n</ul>\n<p>As you can see, these are features that you naturally have to contend with when writing Haskell. There isn't really a dichotomy between FP and OOP, rather, those terms encompass a bunch of ideas that may manifest themselves in any particular application, but they're not mutually exclusive, and the choice of language can make them more or less relevant.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T08:06:54.080",
"Id": "245172",
"ParentId": "245084",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245167",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T14:56:26.133",
"Id": "245084",
"Score": "5",
"Tags": [
"beginner",
"haskell",
"functional-programming",
"hangman"
],
"Title": "Removing OO style coding from Haskell"
}
|
245084
|
<p>Is there a better way of doing this? I heard that BinaryReader and Exif parsing to get the property item is faster, but I have no idea how to do that, thanks for the help.</p>
<pre><code>//we init this once so that if the function is repeatedly called
//it isn't stressing the garbage man
static Regex r = new Regex(":");
//retrieves the datetime WITHOUT loading the whole image
string[] GetDateTakenFromImage(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (Image myImage = Image.FromStream(fs, false, false))
{
PropertyItem propItem = myImage.GetPropertyItem(36867);
string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
if(string.IsNullOrEmpty(dateTaken))
return null;
else
return DateTime.Parse(dateTaken).ToString("yyyy-MM-dd").Split('-');
}
}
}
catch
{
return null;
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>//retrieves the datetime WITHOUT loading the whole image\nstring[] GetDateTakenFromImage(string path)\n</code></pre>\n<p>Function name and parameter are named well. You should use an XML-doc header to document the quirk that it doesn't need to load the entire image.</p>\n<p>Overall I like that the method is concise: it mostly does only one thing, it's easy to read, and not needing to pre-load the whole image is a nice bonus.</p>\n<p>It is strange to use <code>string[]</code> to denote a date. You should be returning a <code>DateTime?</code>.</p>\n<p>Consider changing it to accept a <code>Stream</code> instead of a <code>string path</code>. Currently it's a bit burdensome to test your method because it requires a file path, even though all it's doing is getting a stream out of it anyway. By accepting a <code>Stream</code> instead, you can more easily put automated tests around it that use in-memory test data and avoid a whole litany of IO nonsense.</p>\n<hr />\n<pre><code>using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))\n</code></pre>\n<p><code>fs</code> is a poor name. Give it some more meaning, like <code>imageStream</code>. It can also be written a bit more concisely:</p>\n<pre><code>using (FileStream imageStream = File.OpenRead(path))\n</code></pre>\n<p>Likewise, <code>myImage</code> could just be named <code>image</code>.</p>\n<hr />\n<pre><code>PropertyItem propItem = myImage.GetPropertyItem(36867);\n</code></pre>\n<p>Avoid magic numbers -- that 36867 should be in a named constant somewhere:</p>\n<pre><code>const int ExifDateTimeOriginal = 0x9003;\n</code></pre>\n<hr />\n<p>Your error handling in general could be improved. If I was consuming this API, I would naturally expect exceptions relating to IO (file not found, file not accessible, not a valid image file, and so on) to propagate up. It's up to you whether you want to throw or return <code>null</code> in the case where everything is valid but the image simply doesn't have that tag.</p>\n<p>You're returning <code>null</code> if <em>anything</em> goes wrong which makes this harder to test. Be aware that <code>myImage.GetPropertyItem(36867);</code> will throw if the tag is not present (which in my opinion is a totally non-exceptional circumstance), so if you do tweak your method to propagate other exceptions you will need to put that one line around a try-catch for that one exception.</p>\n<hr />\n<p>The EXIF tag you're checking is encoded in ASCII according to the EXIF docs I've been able to find, so this should use <code>Encoding.ASCII</code> instead of <code>Encoding.UTF8</code>:</p>\n<pre><code>string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);\n</code></pre>\n<p>You also don't need to do any string replacing. <code>DateTime.ParseExact</code> is handy for parsing dates encoded in custom formats:</p>\n<pre><code>string dateTaken = Encoding.ASCII.GetString(propItem.Value);\n...\nreturn DateTime.ParseExact(dateTaken.Trim('\\0'), "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture);\n</code></pre>\n<p>Lastly, if you want to really adhere to the letter of the spec then depending on how you decide to modify or keep your method contract you'll need to handle the case where the date and time are unknown and all non-colon characters are replaced with spaces.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T17:28:06.013",
"Id": "245092",
"ParentId": "245086",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245092",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T15:37:16.533",
"Id": "245086",
"Score": "2",
"Tags": [
"c#",
"image"
],
"Title": "Get Date Taken from Image"
}
|
245086
|
<p>I'm stepping back into Android after being away from it for about a year. Trying to get an out of date app of mine back on its feet, and continuing work on it.</p>
<p>The app was written using Java, MVP, Realm, RxJava, and Dagger. I am trying to update it to use Kotlin, MVVM, Realm, Coroutines and ideally dropping Dagger, as I find it more complicated than I need.</p>
<p>I put together a gist of the flow that I have so far, and would love some feedback on how I can improve, what I could change, or what I am doing wrong. Ideally with examples or direct changes to my code.</p>
<p>It works as is, I am just not sure if I am using coroutines correctly or efficiently, and if there is a better way to structure the DAO's so that Realm can be injected for better testability. Someone has already mentioned changing the DAO to extend the <strong>LiveData<></strong>, and using <strong>onActive()</strong> and <strong>onInactive()</strong> for posting the object. Is that a good idea?</p>
<pre><code>// About Model is the model used by Realm. These models contains realm specific types, like RealmList
open class AboutModel(
var name: String = "",
@PrimaryKey
var version: String = ""
): RealmObject() {
/**
* Conversion function, to convert the view model layer object to the data layer object
*/
companion object {
fun from(about: About): AboutModel = AboutModel(about.name, about.version)
}
fun toObject(): About =
About(
this.name,
this.version
)
}
</code></pre>
<pre><code>// About class used everywhere outside of the data/realm layer.
// Lines up with the AboutModel class, but free of realm or any other database specific types.
// This way, realm objects are not being referenced anywhere else. In case I ever need to
// replace realm for something else.
class About (val name: String = "Test", val version: String = "1.0.0") {
override fun toString(): String {
return "author is : $name, version is: $version"
}
}
</code></pre>
<pre><code>// Couldn't inject the realm instance because its thread would not match with a suspend function.
// Even if both where background threads. Would be better if I could inject it, but couldn't get
// that to work.
class AboutDao() {
private val _about = MutableLiveData<About>()
init {
val realm = Realm.getDefaultInstance()
val aboutModel = realm.where(AboutModel::class.java).findFirst()
_about.postValue(aboutModel?.toObject() ?: About())
realm.close()
}
suspend fun setAbout(about: About) = withContext(Dispatchers.IO) {
val realm: Realm = Realm.getDefaultInstance()
realm.executeTransaction {
realm.copyToRealmOrUpdate(AboutModel.from(about))
_about.postValue(about)
}
realm.close()
}
fun getAbout() = _about as LiveData<About>
}
</code></pre>
<pre><code>// Database is a singleton instance, so there is only ever one instance of the DAO classes
class Database private constructor() {
var aboutDao = AboutDao()
private set
companion object {
// @Volatile - Writes to this property are immediately visible to other threads
@Volatile private var instance: Database? = null
suspend fun getInstance() = withContext(Dispatchers.IO) {
return@withContext instance ?: synchronized(this) {
instance ?: Database().also { instance = it }
}
}
}
}
</code></pre>
<pre><code>// Repo maintains the dao access. Is also setup to run as a singleton
class AboutRepo private constructor(private val aboutDao: AboutDao){
// This may seem redundant.
// Imagine a code which also updates and checks the backend.
suspend fun set(about: About) {
aboutDao.setAbout(about)
}
suspend fun getAbout() = aboutDao.getAbout()
companion object {
// Singleton instantiation you already know and love
@Volatile private var instance: AboutRepo? = null
fun getInstance(aboutDao: AboutDao) =
instance ?: synchronized(this) {
instance ?: AboutRepo(aboutDao).also { instance = it }
}
}
}
</code></pre>
<pre><code>// Injector is used to help keep the injection in a single place for the fragments and activities.
object Injector {
// This will be called from About Fragment
suspend fun provideAboutViewModelFactory(): AboutViewModelFactory = withContext(Dispatchers.Default) {
AboutViewModelFactory(getAboutRepo())
}
private suspend fun getAboutRepo() = withContext(Dispatchers.IO) {
AboutRepo.getInstance(Database.getInstance().aboutDao)
}
}
</code></pre>
<pre><code>// AboutViewModel's Factory. I found this code online, as a helper for injecting into the viewModel's factory.
class AboutViewModelFactory (private val aboutRepo: AboutRepo)
: ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return AboutViewModel(aboutRepo) as T
}
}
</code></pre>
<pre><code>// About Fragments ViewModel
class AboutViewModel(private val aboutRepo: AboutRepo) : ViewModel() {
suspend fun getAbout() = aboutRepo.getAbout()
suspend fun setAbout(about: About) = aboutRepo.set(about)
}
</code></pre>
<pre><code>// Fragment's onActivityCreated, I set the viewModel and observe the model from the view model for changes
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
lifecycleScope.launch {
viewModel = ViewModelProviders.of(
this@AboutFragment,
Injector.provideAboutViewModelFactory()
).get(AboutViewModel::class.java)
withContext(Dispatchers.Main) {
viewModel.getAbout().observe(viewLifecycleOwner, Observer { about ->
version_number.text = about?.version
})
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T18:09:42.753",
"Id": "481269",
"Score": "1",
"body": "_This is not actual code from the app, but an example_ - then it risks being off-topic. Please read https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T18:17:25.403",
"Id": "481270",
"Score": "1",
"body": "_Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T18:43:41.577",
"Id": "481273",
"Score": "1",
"body": "Its a working bit of code that I would like reviewed, so I can improve upon it and understand what I am doing wrong, if anything. Although it is not the exact class name and properties, it is literally how I am currently structuring the flow. How does that not constitute? @Reinderien"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T19:32:03.093",
"Id": "481276",
"Score": "0",
"body": "When we understand what the code is supposed to do, it makes it easier to review the code and give a good code review. When the object and function names have been changed and we don't have a clear idea of what the code is supposed to do, such as why you want to share the json between the 2 classes, then giving a good review is very difficult."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T20:08:23.063",
"Id": "481278",
"Score": "0",
"body": "I'm not sure how my example isn't clear enough. Its passing an About object from the database to the fragment. It goes from a data layer to the UI. I have each step of the flow in the main question, in order of flow."
}
] |
[
{
"body": "<p>I like your architecture decomposition. Especially separation of model and realm object. From what I see it is correct and quite clean.\nOne thing to consider is to keep using <code>RxXX</code> to complement <code>LiveData</code>, where LiveData is lifecycle-aware container of data and <code>Rx</code> component is something with nice transformation api that you actually subscribe to.</p>\n<p>I don't see Dao implementing LiveData as a good idea. Keep it as it is, it's methods returning LiveData.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-23T09:49:57.550",
"Id": "245910",
"ParentId": "245088",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:41:50.337",
"Id": "245088",
"Score": "3",
"Tags": [
"android",
"kotlin"
],
"Title": "Correct flow between Kotlin, Realm and ViewModels using Coroutines"
}
|
245088
|
<p>I made a Java quiz program. The program will let you take the Java quiz and then display the quiz's result according to your score.</p>
<pre><code>/*
* Java Quiz
* by Clint
* 2020.07.07
* This Java program let's you take a quiz. Quiz are taken at: https://www.w3schools.com/java/java_quiz.asp
*/
import javax.swing.JOptionPane;
public class JavaQuiz {
static int points = 0;
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Welcome to Quiz.");
// call the quiz method
question1();
question2();
question3();
question4();
question5();
question6();
question7();
question8();
question9();
question10();
question11();
question12();
question13();
question14();
question15();
result();
}
public static void question1() {
String answer = JOptionPane.showInputDialog(null, "Question 1 of 15:\n" +
"What is a correct syntax to output \"Hello World\" in Java?\n" +
"A. echo(\"Hello World\")\n" +
"B. Console.WriteLine(\"Hello World\")\n" +
"C. System.out.println(\"Hello World\")\n" +
"D. print(\"Hello World\")");
switch (answer){
case "C", "c" -> points++;
}
}
public static void question2() {
String answer = JOptionPane.showInputDialog(null, "Question 2 of 15:\n" +
"Java is short for \"Javascript\".\n" +
"A. true\n" +
"B. false\n" +
"C. All of the above.\n" +
"D. None of the above.");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question3() {
String answer = JOptionPane.showInputDialog(null, "Question 3 of 15:\n" +
"How do you insert COMMENTS in Java code?\n" +
"A. # This is a comment.\n" +
"B. // This is a comment.\n" +
"C. /* This is a comment\n" +
"D. All of the above.");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question4() {
String answer = JOptionPane.showInputDialog(null, "Question 4 of 15:\n" +
"Which data type is used to create a variable that should store text?\n" +
"A. String\n" +
"B. myString\n" +
"C. string\n" +
"D. Txt");
switch (answer){
case "A", "a" -> points++;
}
}
public static void question5() {
String answer = JOptionPane.showInputDialog(null, "Question 5 of 15:\n" +
"How do you create a variable with the numeric value 5?\n" +
"A. num x = 5\n" +
"B. x = 5;\n" +
"C. float x = 5;\n" +
"D. int x = 5;");
switch (answer){
case "D", "d" -> points++;
}
}
public static void question6() {
String answer = JOptionPane.showInputDialog(null, "Question 6 of 15:\n" +
"How do you create a variable with the floating number 2.8?\n" +
"A. byte x = 2.8f\n" +
"B. float x = 2.8f;\n" +
"C. int x = 2.8f;\n" +
"D. x = 2.8f;");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question7() {
String answer = JOptionPane.showInputDialog(null, "Question 7 of 15:\n" +
"Which method can be used to find the length of a string?\n" +
"A. getSize()\n" +
"B. length()\n" +
"C. getLength()\n" +
"D. len()");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question8() {
String answer = JOptionPane.showInputDialog(null, "Question 8 of 15:\n" +
"Which operator is used to add together two values?\n" +
"A. The & sign\n" +
"B. The * sign\n" +
"C. The + sign\n" +
"D. The / sign");
switch (answer){
case "C", "c" -> points++;
}
}
public static void question9() {
String answer = JOptionPane.showInputDialog(null, "Question 9 of 15:\n" +
"The value of a string variable can be surrounded by single quotes.\n" +
"A. True\n" +
"B. False\n" +
"C. All of the above.\n" +
"D. None of the above.");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question10() {
String answer = JOptionPane.showInputDialog(null, "Question 10 of 15:\n" +
"Which method can be used to return a string in upper case letters?\n" +
"A. tuc()\n" +
"B. toUpperCase()\n" +
"C. toupperCase()\n" +
"D. touppercase()");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question11() {
String answer = JOptionPane.showInputDialog(null, "Question 11 of 15:\n" +
"Which operator can be used to compare two values?\n" +
"A. <>\n" +
"B. ==\n" +
"C. =\n" +
"D. ><");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question12() {
String answer = JOptionPane.showInputDialog(null, "Question 12 of 15:\n" +
"To declare an array in Java, define the variable type with:\n" +
"A. []\n" +
"B. ()\n" +
"C. {}\n" +
"D. None of the above.");
switch (answer){
case "A", "a" -> points++;
}
}
public static void question13() {
String answer = JOptionPane.showInputDialog(null, "Question 13 of 15:\n" +
"Array indexes start with:\n" +
"A. 1\n" +
"B. 0\n" +
"C. All of the above.\n" +
"D. None of the above.");
switch (answer){
case "B", "b" -> points++;
}
}
public static void question14() {
String answer = JOptionPane.showInputDialog(null, "Question 14 of 15:\n" +
"How do you create a method in Java?\n" +
"A. methodName()\n" +
"B. methodName[]\n" +
"C. methodName\n" +
"D. (methodName)");
switch (answer){
case "A", "a" -> points++;
}
}
public static void question15() {
String answer = JOptionPane.showInputDialog(null, "Question 15 of 15:\n" +
"How do you call a method in Java?\n" +
"A. methodName();\n" +
"B. methodName;\n" +
"C. (methodName);\n" +
"D. methodName[];");
switch (answer){
case "A", "a" -> points++;
}
}
public static void result() {
String name = JOptionPane.showInputDialog(null,"You finished the quiz.\nPlease enter your name?");
if (points == 15)
{
JOptionPane.showMessageDialog(null, "Name: " + name + "\nTotal Score: " + points + "\nGood job!");
}else if(points >= 10) {
JOptionPane.showMessageDialog(null, "Name: " + name + "\nTotal Score: " + points + "\nYou Passed the quiz.");
}else{
JOptionPane.showMessageDialog(null, "Name: " + name + "\nTotal Score: " + points + "\nYou can still study more for the next quiz.");
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>The code you wrote works and satisfies the requirement of a quiz app. However, you can simplify and handle a few edge cases:</p>\n<ul>\n<li>For every new question, you need to duplicate 10 lines of question* method. You can create encapsulate the question, options and the correct answer's index in a class and create an array to write all the questions and answers. Think about the future requirement to read the list of question/answers from a input file or a database.</li>\n</ul>\n<pre><code>class QuestionAnswer {\n String question;\n String optA;\n String optB;\n String optC;\n String optD;\n String correctAns;\n //all args constructor\n}\n\nstatic QuestionAnswer[] questions = {\n new QuestionAnswer("What is the correct syntax..", "echo (hello world)", "console..", "sysout", "printf", "C"),\n new QuestionAnswer("What java is short for ...", "echo (hello world)", "console..", "sysout", "printf", "C"),\n //... all questions\n };\n</code></pre>\n<p>You can then create a single method to handle all question and answers</p>\n<pre><code>// loop over questions array and call the displayAndCheckAnswer method \n int correctResults = 0;\n for (int i = 0; i < questions.length; i++) {\n if (displayAndCheckAnswer(questions[i], i, questions.length)) {\n correctResults++;\n }\n }\n\n\n public static boolean displayAndCheckAnswer(QuestionAnswer qna, int index, int total) {\n String answer = JOptionPane.showInputDialog(null, "Question" + (index + 1) + "of " + total + ":\\n" +\n qna.question +\n "A. " + qna.optA + "\\n" +\n "B. " + qna.optB + "\\n" +\n "C. " + qna.optC + "\\n" +\n "D. " + qna.optD);\n\n return answer.equalsIgnoreCase(qna.correctAns);\n }\n</code></pre>\n<ul>\n<li>Handle edge cases like - what if user enters space at the end of the their result eg : "A ".</li>\n<li>Better UI: You can render the questions and answers in JPanel and display a running correct answer count.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T20:13:08.770",
"Id": "481395",
"Score": "1",
"body": "Thank you. I'll be practicing on it to make my code efficient and how to use JPanel for GUI. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T03:52:03.853",
"Id": "245112",
"ParentId": "245089",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T16:46:55.333",
"Id": "245089",
"Score": "4",
"Tags": [
"java",
"quiz"
],
"Title": "I made a Java quiz program"
}
|
245089
|
<p>I am working on <a href="https://leetcode.com/problems/prison-cells-after-n-days/" rel="nofollow noreferrer">957. Prison Cells After N Days
</a> but getting timeout error for my code. as I assume my code should be 14+O(n-14) about O(n) am I right since after 14 run pattern will be repeated? and how can I improve my code?</p>
<pre><code> from collections import defaultdict
step_map = defaultdict(list)
for k in range(N):
if tuple(cells) in step_map:
cells = step_map[tuple(cells)]
else:
tmp = list()
for i in range(1, 7):
tmp += [int(cells[i - 1] == cells[i + 1])]
tmp = [0] + tmp + [0]
step_map[tuple(cells)] = tmp
cells = tmp
return cells
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T18:08:15.573",
"Id": "481268",
"Score": "1",
"body": "You need to de-indent this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T18:38:31.170",
"Id": "481271",
"Score": "1",
"body": "the complexity time is 8*N*k (there are 8 cells not 7). in Big-O notation, it does not make sense to say 16 + O(n - 16)... it should be O(n)."
}
] |
[
{
"body": "<h2>The important part</h2>\n<p>They want something below O(n). Using map is a good idea but actually you should find the cycles and return the right position on the cycle instead of computing line by line.</p>\n<h2>Spoiler (possible solution)</h2>\n<p>Change:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if tuple(cells) in step_map:\n return step_map[tuple(cells)]\n</code></pre>\n<p>to:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if tuple(cells) in step_map:\n cycle = list()\n head = tuple(cells)\n cycle.append(head)\n previous = head\n while True:\n next_node = tuple(step_map[previous])\n if next_node == head:\n return list(cycle[(N - k) % len(cycle)])\n cycle.append(next_node)\n previous = next_node\n</code></pre>\n<hr />\n<h2>Old edit - Some small improvements</h2>\n<p>There are some O(m) operations multiple times...</p>\n<p>For example:</p>\n<pre><code> tmp = [0] + tmp + [0]\n</code></pre>\n<p>Python operation for that is O(m). Therefore, your solution is O(nm).</p>\n<pre><code>step_map[tuple(cells)] = tmp\n</code></pre>\n<p>this is also O(m).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T17:53:08.343",
"Id": "245095",
"ParentId": "245094",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T17:42:22.540",
"Id": "245094",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Leetcode 957. Prison Cells After N Days"
}
|
245094
|
<p>The ubiquitous <code>dplyr</code> package has the function <code>mutate_at</code> (and many other <code>*_at()</code>'s), which allows us to perform a similar operation on multiple columns. Using <code>purrr</code>-style formulas, the relevant column is indicated by <code>.</code>:</p>
<pre><code>df %>% mutate_at(vars(colA, colB, colC), ~ 2 * .)
</code></pre>
<p>This would double the values in the respective columns.</p>
<p>However, some times we want to perform operations on multiple "sets" of columns at once. For example, given the following data.frame, we may want to perform <code>a * b</code> for <code>data1</code> and <code>data2</code>, and then store the respective results in columns called <code>data1</code> and <code>data2</code>:</p>
<pre><code>suppressPackageStartupMessages({
library(dplyr)
})
set.seed(42)
df <- data.frame(
id = 1:5,
a_data1 = runif(5),
a_data2 = runif(5),
b_data1 = runif(5),
b_data2 = runif(5),
static = runif(5)
)
</code></pre>
<p>For this trivial case, it wouldn't be too hard to simply do this by hand:</p>
<pre><code>df %>%
mutate(
data1 = a_data1 * b_data1,
data2 = a_data2 * b_data2,
)
#> id a_data1 a_data2 b_data1 b_data2 static data1 data2
#> 1 1 0.9148060 0.5190959 0.4577418 0.9400145 0.90403139 0.4187449 0.48795773
#> 2 2 0.9370754 0.7365883 0.7191123 0.9782264 0.13871017 0.6738624 0.72055016
#> 3 3 0.2861395 0.1346666 0.9346722 0.1174874 0.98889173 0.2674467 0.01582162
#> 4 4 0.8304476 0.6569923 0.2554288 0.4749971 0.94666823 0.2121203 0.31206942
#> 5 5 0.6417455 0.7050648 0.4622928 0.5603327 0.08243756 0.2966743 0.39507089
</code></pre>
<p>But this would get tiresome with many different "sets".</p>
<p>Another, "tidier" option would be to reshape our table:</p>
<pre><code>df %>%
tidyr::pivot_longer(
cols = c(-id, -static),
names_to = c('.value', 'grp'),
names_sep = "_"
) %>%
mutate(
result = a * b
) %>%
tidyr::pivot_wider(
id_cols = c(id, static),
names_from = grp,
values_from = c(a, b, result)
)
#> # A tibble: 5 x 8
#> id static a_data1 a_data2 b_data1 b_data2 result_data1 result_data2
#> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 0.904 0.915 0.519 0.458 0.940 0.419 0.488
#> 2 2 0.139 0.937 0.737 0.719 0.978 0.674 0.721
#> 3 3 0.989 0.286 0.135 0.935 0.117 0.267 0.0158
#> 4 4 0.947 0.830 0.657 0.255 0.475 0.212 0.312
#> 5 5 0.0824 0.642 0.705 0.462 0.560 0.297 0.395
</code></pre>
<p>However, this involves two dataframe reshapes, which can kill performance (see <a href="https://stackoverflow.com/q/60677042/2175231">this question</a> I asked while developing the code below and the performance tests in the answer). Also, it changes the order of the columns (makes <code>static</code> the second column) which annoys me.</p>
<p>So I wrote the following function <code>mutateSet</code> which is currently part of my personal "utilities" package:</p>
<pre><code>mutateSet <- function(df, colNames, formula,
isPrefix = TRUE,
separator = "_") {
vars <- all.vars(formula)
# extracts names wrapped in `.()`
escapedNames <- function (expr)
{
unquote <- function(e) {
if (is.pairlist(e) || length(e) <= 1L) NULL
else if (e[[1L]] == as.name(".")) deparse(e[[2L]])
else unlist(sapply(e, unquote))
}
unquote(substitute(expr))
}
escapedVars <- eval(rlang::expr(escapedNames(!!formula)))
# remove escaped names from mapping variables
vars <- setdiff(vars, escapedVars)
# get output prefix/suffix as string
lhs <- rlang::f_lhs(formula) %>%
all.vars()
# get operation as string
# deparse() can have line breaks; paste0() brings it back to one line
rhs <- rlang::f_rhs(formula) %>%
deparse() %>%
paste0(collapse = "")
# dummy function to cover for bquote escaping
. <- function(x) x
for (i in colNames) {
if (isPrefix) {
aliases <- paste0(vars, separator, i)
newCol <- paste0(lhs, separator, i)
} else {
aliases <- paste0(i, separator, vars)
newCol <- paste0(i, separator, lhs)
}
if (length(lhs) == 0) newCol <- i
mapping <- rlang::list2(!!!aliases)
names(mapping) <- vars
mapping <- do.call(wrapr::qc, mapping)
df <- rlang::expr(wrapr::let(
mapping,
df %>% dplyr::mutate(!!newCol := ...RHS...)
)) %>%
deparse() %>%
gsub(
pattern = "...RHS...",
replacement = rhs
) %>%
{eval(parse(text = .))}
}
return(df)
}
</code></pre>
<p>It takes in a vector of names representing each "set" and a one- or two-sided formula representing the desired operation to be applied to each operation.</p>
<p>If the formula is one-sided, the name of the resulting column is the same as the set's; if it's two-sided, the column's name is the concatenation of the set's name and whatever was given on the left-hand side (so <code>x ~ a * b</code> results in columns <code>x_data1</code> and <code>x_data2</code>, for example).</p>
<pre><code>df %>%
NCHUtils::mutateSet(
c("data1", "data2"),
~ a * b
)
#> id a_data1 a_data2 b_data1 b_data2 static data1 data2
#> 1 1 0.9148060 0.5190959 0.4577418 0.9400145 0.90403139 0.4187449 0.48795773
#> 2 2 0.9370754 0.7365883 0.7191123 0.9782264 0.13871017 0.6738624 0.72055016
#> 3 3 0.2861395 0.1346666 0.9346722 0.1174874 0.98889173 0.2674467 0.01582162
#> 4 4 0.8304476 0.6569923 0.2554288 0.4749971 0.94666823 0.2121203 0.31206942
#> 5 5 0.6417455 0.7050648 0.4622928 0.5603327 0.08243756 0.2966743 0.39507089
</code></pre>
<p>If an operation should also include columns which aren't part of the set (i.e, if we wanted to do <code>a * b + static</code>), the formula also accepts <code>bquote</code>-style escaping:</p>
<pre><code>df %>%
NCHUtils::mutateSet(
c("data1", "data2"),
x ~ a * b + .(static)
)
#> id a_data1 a_data2 b_data1 b_data2 static x_data1 x_data2
#> 1 1 0.9148060 0.5190959 0.4577418 0.9400145 0.90403139 1.3227763 1.3919891
#> 2 2 0.9370754 0.7365883 0.7191123 0.9782264 0.13871017 0.8125726 0.8592603
#> 3 3 0.2861395 0.1346666 0.9346722 0.1174874 0.98889173 1.2563384 1.0047134
#> 4 4 0.8304476 0.6569923 0.2554288 0.4749971 0.94666823 1.1587885 1.2587377
#> 5 5 0.6417455 0.7050648 0.4622928 0.5603327 0.08243756 0.3791119 0.4775084
</code></pre>
<p>In fact, this all works even if some of the data isn't in the dataframe but in the environment (i.e., if <code>static</code> were a variable in the environment instead of a column).</p>
<hr />
<p>This was very much a jury-rigged solution (that weird <code>...RHS...</code> which is later replaced via <code>deparse()/gsub()</code> was a workaround for the problem in the linked question above), so I'm sure there's much to improve.</p>
<p>A feature-request might be too much to ask for, but if anyone can see how to do this trivially, that'd be great: a particular desire would be for this to accept <code>rlang</code>-style expansion (<code>!!</code> and <code>!!!</code>), which would make it easier to use this function in other NSE functions: i.e. a function which applies a <code>mutateSet</code> operation with <code>x + y</code>, but <code>x</code> and <code>y</code> are actually placeholders for the actual variables which will be given by the user. I'm currently writing precisely such a function and have had to instead write the entire <code>mutateSet</code> call as an <code>rlang::expr()</code>, where I can then define the variables in the formula with <code>!!</code>, and only then evaluate the call with <code>eval()</code>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T20:18:11.417",
"Id": "245097",
"Score": "2",
"Tags": [
"r"
],
"Title": "Package function to perform operation on different \"sets\" of data in same dataframe"
}
|
245097
|
<p>I have been learning MVVM and I have decided to create a small framework for simple MVVM programs I can make in the future. This program provides navigation between a main menu, settings menu, start menu, and exit button. There is no functionality yet, and this is because I want to work on the navigation framework before I implement any models. Mainly, I tend to get confused on the relationships between view and viewmodel AND viewmodel to viewmodel communication. Here is what I got.</p>
<p><strong>Bases - Helper Files</strong></p>
<p>DelegateCommand.cs - ICommand Implementation</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMPractice.Bases.ViewModel
{
/// <summary>
/// ICommand Implementation.
/// </summary>
class DelegateCommand : ICommand
{
private readonly Action<object> _executeAction;
private readonly Func<object, bool> _canExecuteAction;
/// <summary>
/// Delecate with execution action and canExecute bool
/// </summary>
/// <param name="executeAction">Function that gets executed on command</param>
/// <param name="canExecuteAction">Function that determines if the command can be executed</param>
public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecuteAction)
{
_executeAction = executeAction;
_canExecuteAction = canExecuteAction;
}
/// <summary>
/// Execute
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter) => _executeAction(parameter);
/// <summary>
/// CanExecute
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter) => _canExecuteAction?.Invoke(parameter) ?? true;
public event EventHandler CanExecuteChanged;
/// <summary>
/// Determine if the command can be executed
/// </summary>
public void InvokeCanExecuteChanged() => CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
</code></pre>
<p>IViewModel.cs - Used by all menu viewmodels</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVVMPractice.Bases.ViewModel
{
/// <summary>
/// Interfaces for main ViewModels
/// </summary>
interface IViewModel
{
/// <summary>
/// Get name string
/// </summary>
string Name { get; }
}
}
</code></pre>
<p>Messenger.cs - Viewmodel to Viewmodel Communication</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVVMPractice.Bases.ViewModel
{
/// <summary>
/// Messenger takes and gives an object as a message for viewmodel communication
/// </summary>
public class Messenger
{
//Instance
private static Messenger _instance;
public static Messenger Instance => _instance ?? (_instance = new Messenger());
//declaring EventHandler
public event EventHandler<MessageValueChangedEventArgs> MessageValueChanged;
//Custom Event args
public class MessageValueChangedEventArgs : EventArgs
{
public string PropertyName { get; set; }
public object NewValue { get; set; }
}
//raising the event for a property
public void RaiseMessageValueChanged(string propertyName, object value)
{
MessageValueChanged?.Invoke(this, new MessageValueChangedEventArgs() { PropertyName = propertyName, NewValue = value });
}
}
}
</code></pre>
<p>ViewModelBase.cs - All ViewModels inherit this class</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace MVVMPractice.Bases.ViewModel
{
/// <summary>
/// All viewmodels inherit ViewModelBase
/// </summary>
class ViewModelBase : INotifyPropertyChanged
{
//Declare Messenger
protected Messenger _messenger;
//Declare PropertyChanged event handler
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Invokes PropertyChanged when a property is changed. Using INotifyPropertyChanged
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field"></param>
/// <param name="newValue"></param>
/// <param name="propertyName"></param>
/// <returns></returns>
protected bool SetProptery<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
{
if(!EqualityComparer<T>.Default.Equals(field, newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
}
}
</code></pre>
<p><strong>Application Files - Main window used for navigation</strong></p>
<p>ApplicationViewModel.cs</p>
<pre><code>using MVVMPractice.Bases.ViewModel;
using MVVMPractice.Main;
using MVVMPractice.Main.Settings;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMPractice
{
/// <summary>
/// Application View Model for ApplicationView
/// </summary>
class ApplicationViewModel : ViewModelBase
{
/// <summary>
/// IViewModel Interface: Variable stores current IViewModel
/// </summary>
private IViewModel _currentViewModel;
/// <summary>
/// ApplicationViewModel Constructor
/// </summary>
public ApplicationViewModel()
{
_messenger = Messenger.Instance;
_messenger.MessageValueChanged += OnMessengerValueChanged;
MainViewModel mainViewModel = new MainViewModel();
SettingsViewModel settingsViewModel = new SettingsViewModel();
//debug line for testing new pages
//CurrentViewModel = settingsViewModel;
CurrentViewModel = mainViewModel;
}
/// <summary>
/// Get / Set IViewModel CurrentViewModel
/// </summary>
public IViewModel CurrentViewModel
{
get
{
return _currentViewModel;
}
set
{
SetProptery(ref _currentViewModel, value);
}
}
/// <summary>
/// Notify Change for Messenger Value. Changes CurrentViewModel if property string is "CurrentViewModel"
/// </summary>
/// <param name="sender">Object sender</param>
/// <param name="e">Event Args for Messenger</param>
private void OnMessengerValueChanged(object sender, Messenger.MessageValueChangedEventArgs e)
{
if (e.PropertyName == "CurrentViewModel")
{
CurrentViewModel = (IViewModel)e.NewValue;
}
}
}
}
</code></pre>
<p><strong>ApplicationView.xaml</strong></p>
<pre><code>
<Window x:Class="MVVMPractice.ApplicationView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MVVMPractice" xmlns:main="clr-namespace:MVVMPractice.Main" xmlns:settings="clr-namespace:MVVMPractice.Main.Settings" xmlns:start="clr-namespace:MVVMPractice.Main.Start"
Title="ApplicationView" Height="450" Width="800">
<Window.Resources>
<DataTemplate DataType="{x:Type main:MainViewModel}">
<main:MainView/>
</DataTemplate>
<DataTemplate DataType="{x:Type settings:SettingsViewModel}">
<settings:SettingsView/>
</DataTemplate>
<DataTemplate DataType="{x:Type start:StartViewModel}">
<start:StartView/>
</DataTemplate>
</Window.Resources>
<ContentControl Content="{Binding CurrentViewModel}"/>
</Window>
</code></pre>
<p>ApplicationView.xaml.cs</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace MVVMPractice
{
/// <summary>
/// Interaction logic for ApplicationView.xaml
/// </summary>
public partial class ApplicationView : Window
{
public ApplicationView()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
}
}
}
</code></pre>
<p><strong>Main - Default User Control</strong></p>
<p>MainViewModel.cs</p>
<pre><code>using MVVMPractice.Bases.ViewModel;
using MVVMPractice.Main.Settings;
using MVVMPractice.Main.Start;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace MVVMPractice.Main
{
/// <summary>
/// ViewModel for MainMenu
/// </summary>
class MainViewModel : ViewModelBase, IViewModel
{
/// <summary>
/// IViewModel name
/// </summary>
public string Name
{
get { return "MainMenu"; }
}
/// <summary>
/// Constructor for MainViewModel
/// </summary>
public MainViewModel()
{
_messenger = Messenger.Instance;
_exitCommand = new DelegateCommand(OnExitCommand, CanExitCommand);
_settingsCommand = new DelegateCommand(OnSettingsCommand, CanSettingsCommand);
_startCommand = new DelegateCommand(OnStartCommand, CanStartCommand);
}
#region Start Command
//Declare DelegateCommand
private readonly DelegateCommand _startCommand;
//Declare ICommand
public ICommand StartCommand => _startCommand;
/// <summary>
/// CanExecute, returns true
/// </summary>
/// <param name="parameter"></param>
/// <returns>True</returns>
private bool CanStartCommand(object parameter)
{
return true;
}
/// <summary>
/// OnExecute, submits StartViewModel to messenger
/// </summary>
/// <param name="parameter"></param>
public void OnStartCommand(object parameter)
{
_messenger.RaiseMessageValueChanged("CurrentViewModel", new StartViewModel());
}
#endregion
#region Settings Command
//Declare DelegateCommand
private readonly DelegateCommand _settingsCommand;
//Declare ICommand
public ICommand SettingsCommand => _settingsCommand;
/// <summary>
/// CanExecute, returns true
/// </summary>
/// <param name="parameter"></param>
/// <returns>True</returns>
private bool CanSettingsCommand(object parameter)
{
return true;
}
/// <summary>
/// OnExecute, submits SettingsViewModel to messenger
/// </summary>
/// <param name="parameter"></param>
private void OnSettingsCommand(object parameter)
{
_messenger.RaiseMessageValueChanged("CurrentViewModel", new SettingsViewModel());
}
#endregion
#region Exit Command
//Declare DelegateCommand
private readonly DelegateCommand _exitCommand;
//Declare ICommand
public ICommand ExitCommand => _exitCommand;
/// <summary>
/// CanExecute, returns true
/// </summary>
/// <param name="parameter"></param>
/// <returns>True</returns>
private bool CanExitCommand(object parameter)
{
return true;
}
/// <summary>
/// OnExecute, shuts down the program
/// </summary>
/// <param name="Parameter"></param>
private void OnExitCommand(object Parameter)
{
App.Current.Shutdown();
}
#endregion
}
</code></pre>
<p>MainView.xaml</p>
<pre><code><UserControl x:Class="MVVMPractice.Main.MainView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MVVMPractice.Main.Settings"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<DataTemplate DataType="{x:Type local:SettingsViewModel}">
<local:SettingsView/>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Button Command="{Binding StartCommand}" Content="Start" HorizontalAlignment="Left" Margin="145,97,0,0" VerticalAlignment="Top" Width="75"/>
<Button Command="{Binding SettingsCommand}" Content="Settings" HorizontalAlignment="Left" Margin="145,116,0,0" VerticalAlignment="Top" Width="75"/>
<Button Command="{Binding ExitCommand}" Content="Exit" HorizontalAlignment="Left" Margin="145,135,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</UserControl>
</code></pre>
<p>MainView.xaml.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MVVMPractice.Main
{
/// <summary>
/// Interaction logic for MainView.xaml
/// </summary>
public partial class MainView : UserControl
{
public MainView()
{
var viewModel = new MainViewModel();
DataContext = viewModel;
InitializeComponent();
}
}
}
</code></pre>
<p><strong>Start Menu</strong>
StartViewModel.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMPractice.Main.Start
{
/// <summary>
/// ViewModel for Start
/// </summary>
class StartViewModel : ViewModelBase, IViewModel
{
/// <summary>
/// IViewModel name
/// </summary>
public string Name
{
get { return "Start"; }
}
/// <summary>
/// Constructor for StartViewModel
/// </summary>
public StartViewModel()
{
_messenger = Messenger.Instance;
_backCommand = new DelegateCommand(OnBackCommand, CanBackCommand);
}
#region BackCommand
//Declare DelegateCommand
private readonly DelegateCommand _backCommand;
//Delcare ICommand
public ICommand BackCommand => _backCommand;
/// <summary>
/// CanExecute, returns true
/// </summary>
/// <param name="parameter"></param>
/// <returns>True</returns>
private bool CanBackCommand(object parameter)
{
return true;
}
/// <summary>
/// OnExecute, Submits MainViewModel to messenger
/// </summary>
/// <param name="parameter"></param>
private void OnBackCommand(object parameter)
{
_messenger.RaiseMessageValueChanged("CurrentViewModel", new MainViewModel());
}
#endregion
}
}
</code></pre>
<p>StartView.xaml</p>
<pre><code><UserControl x:Class="MVVMPractice.Main.Start.StartView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MVVMPractice.Main.Start"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Label Content="InStart" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="387" Width="780" Background="#FFCD4646"/>
<Button Command="{Binding BackCommand}" Content="Back" HorizontalAlignment="Left" Margin="10,420,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</UserControl>
</code></pre>
<p>StartView.xaml.cs</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MVVMPractice.Main.Start
{
/// <summary>
/// Interaction logic for StartView.xaml
/// </summary>
public partial class StartView : UserControl
{
public StartView()
{
StartViewModel viewModel = new StartViewModel();
DataContext = viewModel;
InitializeComponent();
}
}
}
</code></pre>
<p><strong>Settings menu</strong></p>
<p>SettingsViewModel.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMPractice.Main.Settings
{
/// <summary>
/// ViewModel for Settings Menu
/// </summary>
class SettingsViewModel : ViewModelBase, IViewModel
{
/// <summary>
/// IViewModel name
/// </summary>
public string Name
{
get { return "SettingsMenu"; }
}
/// <summary>
/// Constructor for SettingsViewModel
/// </summary>
public SettingsViewModel()
{
_messenger = Messenger.Instance;
_backCommand = new DelegateCommand(OnBackCommand, CanBackCommand);
}
#region BackCommand
//Create DelegateCommand
private readonly DelegateCommand _backCommand;
//Create ICommand
public ICommand BackCommand => _backCommand;
/// <summary>
/// CanExecute. Returns True
/// </summary>
/// <param name="parameter"></param>
/// <returns>True</returns>
private bool CanBackCommand(object parameter)
{
return true;
}
/// <summary>
/// OnExecute. Submits a MainViewModel to messenger
/// </summary>
/// <param name="parameter"></param>
private void OnBackCommand(object parameter)
{
_messenger.RaiseMessageValueChanged("CurrentViewModel", new MainViewModel());
}
#endregion
}
}
</code></pre>
<p>SettingsView.xaml</p>
<pre><code>
<UserControl x:Class="MVVMPractice.Main.Settings.SettingsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MVVMPractice.Main.Settings"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Label Content="InSettings" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="405" Width="780" Background="#FFED6A6A"/>
<Button Command="{Binding BackCommand}" Content="Back" HorizontalAlignment="Left" Margin="10,420,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</UserControl>
</code></pre>
<p>SettingsView.xaml.cs</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MVVMPractice.Main.Settings
{
/// <summary>
/// Interaction logic for SettingsView.xaml
/// </summary>
public partial class SettingsView : UserControl
{
public SettingsView()
{
SettingsViewModel viewModel = new SettingsViewModel();
DataContext = viewModel;
InitializeComponent();
}
}
}
</code></pre>
<p>This works out fine, but I want to know how I can improve before I start moving forward, or am I even taking steps in the correct direction?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T21:39:27.843",
"Id": "481288",
"Score": "2",
"body": "Great first question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-11T13:31:08.917",
"Id": "481739",
"Score": "1",
"body": "I have a couple of doubts. The first one is that it's strange to have both `IViewModel` and `ViewModelBase`, even though I've understood that you had to differentiate between the pages (Main, Start and Settings) and the container window (Application). It works fine but could be confusing for someone coming to to your project as newcomer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-11T13:33:56.820",
"Id": "481740",
"Score": "1",
"body": "The second problem is that you initialize two viewModel for each view. The first one get created as parameter to the Messenger (and stored inside the `ApplicationViewModel`), meanwhile the second one get created by the view (and stored as its `DataContext`). I think this could lead to a multitude of problems. To solve that it should be as easy as set `<ContentControl Content=\"{Binding CurrentViewModel}\" DataContext=\"{Binding CurrentViewModel}\"/>` and removing the viewModel creation from the view constructors.\nI didn't test this, so take it as an idea. These were my thoughts. Good work overall"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-12T05:08:46.233",
"Id": "481799",
"Score": "0",
"body": "Thank you! I actually forgot that I was declaring the DataContext in the code behind instead of in the XAML, so I think that will be worth the fix. With your comments in mind, I will try to write a more thoughtful MVVM design (specifically figuring out how to make the IViewModel and ViewModelBase system more intuitive)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T20:27:22.150",
"Id": "245098",
"Score": "3",
"Tags": [
"c#",
"wpf",
"mvvm"
],
"Title": "Simple MVVM Navigation for WPF in c#"
}
|
245098
|
<p>The source code of this project aims to enable defining contact information either via FrontMatter or named parameters, and having that information then formatted to HTML that is both human <strong>and</strong> machine readable. I've attempted to adhere to the MicroCode specifications for both HCard and VCard formats, and allow for easy customization, but I believe there's always room for improvement.</p>
<hr />
<h2>Questions</h2>
<ul>
<li><p>Have I made any mistakes or deviated too far from the MicroCode format(s)?</p>
</li>
<li><p>Are there any features that should be added?</p>
</li>
<li><p>Any suggestions for making Liquid code easier to extend?</p>
</li>
</ul>
<hr />
<h2>Requirements</h2>
<p>The source code and setup instructions are intended for those utilizing <a href="https://jekyllrb.com" rel="nofollow noreferrer" title="Home page for Jekyll">Jekyll</a> built sites on GitHub Pages. The Jekyll site has <a href="https://jekyllrb.com/docs/github-pages/" rel="nofollow noreferrer" title="Jekyll documentation for GitHub Pages">documentation</a> regarding GitHub Pages, and GitHub has further <a href="https://docs.github.com/en/github/working-with-github-pages/creating-a-github-pages-site-with-jekyll" rel="nofollow noreferrer" title="GitHub documentation for Jekyll">documentation</a> regarding Jekyll.</p>
<hr />
<h2>Setup</h2>
<p>The <a href="https://github.com/liquid-utilities/includes-hcard/blob/main/.github/README.md" rel="nofollow noreferrer" title="Documentation for includes-hcard project"><em><code>ReadMe</code></em></a> file contains more detailed instructions for setup, but the TLDR is as follows.</p>
<ul>
<li>Change current working directory to a repository utilizing Jekyll to build static web pages...</li>
</ul>
<pre><code>cd ~/git/hub/<name>/<repo>
</code></pre>
<ul>
<li>Check-out the <code>gh-pages</code> branch and make directory path for including modules...</li>
</ul>
<pre><code>git checkout gh-pages
mkdir -p _includes/modules
</code></pre>
<ul>
<li>Add this project as a Git Submodule</li>
</ul>
<pre><code>git submodule add -b 'main'\
--branch 'includes-hcard'\
'https://github.com/liquid-utilities/includes-hcard.git'\
'_includes/modules/includes-hcard'
</code></pre>
<blockquote>
<p><strong>Notice</strong>, for GitHub Pages one must use the <code>https</code> URL for Git Submodules</p>
</blockquote>
<ul>
<li>Add an <code>include</code> statement to your site's default layout, eg...</li>
</ul>
<p><a href="https://github.com/liquid-utilities/includes-hcard/blob/gh-pages/_layouts/default.html" rel="nofollow noreferrer"><strong><code>_layouts/default.html</code></strong></a></p>
<pre><code>---
license: MIT
source: https://raw.githubusercontent.com/jekyll/minima/v2.0.0/_layouts/default.html
---
<!DOCTYPE html>
<html lang="{{ page.lang | default: site.lang | default: "en" }}">
{% include head.html %}
<body>
{% include header.html %}
<main class="page-content" aria-label="Content">
<div class="wrapper">
{{ content }}
{% if page.hcard %}
<div class="contacts">
{% include modules/includes-hcard/hcard.html %}
</div>
{% endif %}
</div>
</main>
{% include footer.html %}
</body>
</html>
</code></pre>
<ul>
<li>Commit added Git Submodule and theme modifications...</li>
</ul>
<pre><code>git commit -F- <<'EOF'
:heavy_plus_sign: Adds `liquid-utilities/includes-hcard#1` submodule
**Adds**
- `.gitmodules`, tracks submodules AKA Git within Git _fanciness_
- `_modules_/includes-hcard`, Builds HCard compatible with VCard HTML format
- `_layouts/default.html`, modified default layout from `jekyll/minima` theme
EOF
</code></pre>
<hr />
<h2>Usage</h2>
<ul>
<li>Use FrontMatter configurations for the selected layout...</li>
</ul>
<p><a href="https://github.com/liquid-utilities/includes-hcard/blob/gh-pages/_posts/2020-07-05-includes-hcard.md" rel="nofollow noreferrer"><strong><code>_posts/2020-07-05-frontmatter-hcard.md</code></strong></a></p>
<pre><code>---
layout: post
date: 2020-07-05 10:44:25 -0700
title: FrontMatter HCard
excerpt: Example of using FrontMatter to define HCard content
hcard:
organization: Distribution
name: Jayne Cobb
# email_type: office
# email_address: name@example.com
emails:
- type: office
address: name@example.com
# phone_type: cell
# phone_number: 555-123-4567
phone_numbers:
- type: cell
number: 555-123-4567
- type: office
number: 555-987-6543
address:
street: 418 Code St.
extended: Suite 503 ## AKA suite, apartment, etc.
country_code: USA
country_name: United States of America
locality: Server Request ## AKA city
region: ZZ ## AKA state
postal_code: 12345 ## AKA zip
# link_label: 'example'
# link_url: https://example.com
links:
- label: 'example one'
url: https://example.com
- label: 'example two'
url: https://example.com
- label: 'example three'
url: https://example.com
---
</code></pre>
<p>A <a href="https://liquid-utilities.github.io/includes-hcard/2020/07/05/frontmatter-hcard.html" rel="nofollow noreferrer"><em>live</em> example</a> of output above is hosted thanks to GitHub Pages, the resulting HTML for above configurations is similar to...</p>
<p><strong><code>includes-hcard/2020/07/05/frontmatter-hcard.html</code> (snip)</strong></p>
<pre><code><div id="hcard-jayne-cobb" class="h-card vcard">
<div class="p-org org">Distribution</div>
<div class="p-name fn">Jayne Cobb</div>
<div class="p-tel tel">
<span class="type">cell</span>:
<a class="value">555-123-4567</a>
</div>
<div class="p-tel tel">
<span class="type">office</span>:
<a class="value">555-987-6543</a>
</div>
<div class="u-email email">
<span class="type">office</span>:
<a class="value" href="mailto:name@example.com">name@example.com</a>
</div>
<div class="p-adr adr">
<span class="p-street-address street-address">418 Code St.</span>
<span class="p-locality locality">Server Request</span>, <span class="p-region region">ZZ</span>
<span class="p-postal-code postal-code">12345</span>
<span class="p-country-name usa" title="United States of America">USA</span>
</div>
<div><a class="url fn org" href="https://example.com">example one</a>: <small>https://example.com</small></div>
<div><a class="url fn org" href="https://example.com">example two</a>: <small>https://example.com</small></div>
<div><a class="url fn org" href="https://example.com">example three</a>: <small>https://example.com</small></div>
</div>
</code></pre>
<ul>
<li>Or use <code>include</code> directly and assign via named parameters...</li>
</ul>
<p><a href="https://github.com/liquid-utilities/includes-hcard/blob/gh-pages/_posts/2020-07-05-includes-hcard.md" rel="nofollow noreferrer"><strong><code>_posts/2020-07-05-includes-hcard.md</code></strong></a></p>
<pre><code>---
layout: post
date: 2020-07-05 10:44:25 -0700
title: Includes HCard
excerpt: Example of using `include` keyword to define HCard content
---
This post is a _live_ example of using `include` keyword to define HCard content, [source code][post__includes_hcard__source] is available on GitHub.
{% include modules/includes-hcard/hcard.html name='Jayne Cobb'
organization='Distribution'
phone_type='cell'
phone_number='555-123-4567'
email_type='office'
email_address='name@example.com'
address_street='418 Code St.'
address_extended='Suite 503'
address_locality='Server Request'
address_postal_code='12345'
address_region='ZZ'
address_country_code='USA'
address_country_name='United States of America'
link_label='Web Site'
link_url='https://example.com' %}
[post__includes_hcard__source]: https://github.com/liquid-utilities/includes-hcard/blob/gh-pages/_posts/2020-07-05-includes-hcard.md
</code></pre>
<p>Again a <a href="https://liquid-utilities.github.io/includes-hcard/2020/07/05/includes-hcard.html" rel="nofollow noreferrer"><em>live</em> example</a> of output above is hosted on GitHub Pages, the resulting HTML for above configurations is similar to...</p>
<p><strong><code>includes-hcard/2020/07/05/includes-hcard.html</code> (snip)</strong></p>
<pre><code><div id="hcard-jayne-cobb" class="h-card vcard">
<div class="p-org org">Distribution</div>
<div class="p-name fn">Jayne Cobb</div>
<span class="type">cell</span>: <a class="p-tel tel">555-123-4567</a>
<div class="u-email email">
<span class="type">office</span>:
<a class="value" href="mailto:name@example.com">name@example.com</a>
</div>
<div class="p-adr adr">
<span class="p-street-address street-address">418 Code St.</span>
<span class="p-locality locality">Server Request</span>, <span class="p-region region">ZZ</span>
<span class="p-postal-code postal-code">12345</span>
<span class="p-country-name usa" title="United States of America">USA</span>
</div>
<div><a class="url fn org" href="https://example.com">Web Site</a>: <small>https://example.com</small></div>
</div>
</code></pre>
<ul>
<li>Commit changes and push to GitHub...</li>
</ul>
<pre><code>git add _posts/2020-07-05-frontmatter-hcard.md
git commit -m ':memo: Adds post FrontMatter HCard'
git add _posts/2020-07-05-includes-hcard.md
git commit -m ':memo: Adds post Includes HCard'
git push origin gh-pages
</code></pre>
<hr />
<h2>Source Code</h2>
<p><a href="https://github.com/liquid-utilities/includes-hcard/blob/main/hcard.html" rel="nofollow noreferrer" title="Main source code for includes-hcard project"><strong><code>hcard.html</code></strong></a></p>
<pre><code>{% capture workspace__hcard %}
{% comment %}
---
version: 0.0.1
license: AGPL-3.0
author: S0AndS0
---
{% endcomment %}
{% assign name = include.hame | default: page.hcard.name | default: nil %}
{% assign organization = include.organization | default: page.hcard.organization | default: nil %}
{% assign photo_alt = include.photo_alt | default: page.hcard.photo.alt | default: nil %}
{% assign photo_src = include.photo_src | default: page.hcard.photo.src | default: nil %}
{% unless photo_alt %}
{% if photo_src and name %}
{% assign photo_alt = "Photo of " | append: name %}
{% elsif photo_src and organization %}
{% assign photo_alt = "Photo of " | append: organization %}
{% endif %}
{% endunless %}
{% assign email_address = include.email_address | default: page.hcard.email_address | default: nil %}
{% assign email_type = include.email_type | default: page.hcard.email_type | default: nil %}
{% assign emails = include.emails | default: page.hcard.emails | default: nil %}
{% assign phone_type = include.phone_type | default: page.hcard.phone_type | default: nil %}
{% assign phone_number = include.phone_number | default: page.hcard.phone_number | default: nil %}
{% assign phone_numbers = include.phone_numbers | default: page.hcard.phone_numbers | default: nil %}
{% assign address_street = include.address_street | default: page.hcard.address.street | default: nil %}
{% assign address_extended = include.address_extended | default: page.hcard.address.extended | default: nil %}
{% assign address_country_code = include.address_country_code | default: page.hcard.address.country_code | default: nil %}
{% assign address_country_name = include.address_country_name | default: page.hcard.address.country_name | default: nil %}
{% assign address_locality = include.address_locality | default: page.hcard.address.locality | default: nil %}
{% assign address_region = include.address_region | default: page.hcard.address.region | default: nil %}
{% assign postal_code = include.address_postal_code | default: page.hcard.address.postal_code | default: nil %}
{% assign links = include.links | default: page.hcard.links | default: nil %}
{% assign link_label = include.link_label | default: page.hcard.link_label | default: nil %}
{% assign link_url = include.link_url | default: page.hcard.link_url | default: nil %}
{% if organization or name %}
{% if name %}
<div id="hcard-{{ name | downcase | replace: ' ','-' }}" class="h-card vcard">
{% elsif organization %}
<div id="hcard-{{ organization | downcase | replace: ' ','-' }}" class="h-card vcard">
{% endif %}
{% if photo_src and photo_alt %}
<img class="photo" src="{{ photo_src }}" alt="{{ photo_alt }}">
{% endif %}
{% if organization %}
<div class="p-org org">{{ organization }}</div>
{% endif %}
{% if name %}
<div class="p-name fn">{{ name }}</div>
{% endif %}
{% if phone_numbers %}
{% for phone in phone_numbers %}
<div class="p-tel tel">
{% if phone.type %}<span class="type">{{ phone.type }}</span>: {% endif %}
<a class="value">{{ phone.number }}</a>
</div>
{% endfor %}
{% elsif phone_number %}
{% if phone_type %}<span class="type">{{ phone_type }}</span>: {% endif %}
<a class="p-tel tel">{{ phone_number }}</a>
{% endif %}
{% if emails %}
{% for email in emails %}
<div class="u-email email">
{% if email.type %}
<span class="type">{{ email.type }}</span>:
{% endif %}
<a class="value" href="mailto:{{ email.address }}">{{ email.address }}</a>
</div>
{% endfor %}
{% elsif email_address %}
<div class="u-email email">
{% if email_type %}<span class="type">{{ email_type }}</span>: {% endif %}
<a class="value" href="mailto:{{ email_address }}">{{ email_address }}</a>
</div>
{% endif %}
{% if address_street or extended_address or address_locality or address_region or postal_code or address_country_code or address_country_name %}
<div class="p-adr adr">
{% if address_street %}
<span class="p-street-address street-address">{{ address_street }}</span>
{% endif %}
{% if extended_address %},
<span class="p-extended-address extended-address">{{ extended_address }}</span>
{% endif %}
{% if address_locality %}
<span class="p-locality locality">{{ address_locality }}</span>
{% endif %}
{% if address_region %},
<span class="p-region region">{{ address_region }}</span>
{% endif %}
{% if postal_code %}
<span class="p-postal-code postal-code">{{ postal_code }}</span>
{% endif %}
{% if address_country_code %}
<span class="p-country-name {{ address_country_code | downcase }}"{% if address_country_name %} title="{{ address_country_name }}"{% endif %}>
{{ address_country_code }}
</span>
{% endif %}
</div>
{% endif %}
{% if links %}
{% for link in links %}
<div><a class="url fn org" href="{{ link.url }}">{{ link.label }}</a>: <small>{{ link.url }}</small></div>
{% endfor %}
{% elsif link_label and link_url %}
<div><a class="url fn org" href="{{ link_url }}">{{ link_label }}</a>: <small>{{ link_url }}</small></div>
{% endif %}
</div>
{% endif %}
{% endcapture %}{%- if workspace__hcard -%}{{ workspace__hcard | strip }}{% assign workspace__hcard = nil %}{%- endif -%}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T21:41:56.643",
"Id": "245100",
"Score": "1",
"Tags": [
"html",
"template",
"jekyll",
"liquid"
],
"Title": "Liquid includes HCard module"
}
|
245100
|
<p>I am trying to create a list based on some data, but the code I am using is very slow when I run it on large data. So I suspect I am not using all of the Python power for this task. Is there a more efficient and faster way of doing this in Python?</p>
<p>Here an explanantion of the code:</p>
<blockquote>
<p>You can think of this problem as a list of games each with a list of participating teams and the scores for each team in the game. For each of the pairs in the current game it calculates the sum of the differences in score from the previous competitions (only for those competing!). Then it updates each pair in the current game with the difference in scores. Then it keeps track of the scores for each pair in each game and update this score as each game is played.</p>
</blockquote>
<p>In the example below, based on some data, there are for-loops used to create a new variable <code>list_zz</code>.</p>
<p>The data and the for-loop code:</p>
<pre><code>from collections import Counter, defaultdict
from itertools import combinations
import math
# test data
games = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'], ['C', 'A', 'B'], ['A'], ['B', 'C']]
gamescores = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0], [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]]
list_zz= []
wd = defaultdict(Counter)
past_diffs = defaultdict(float)
this_diff = defaultdict(Counter)
for players, scores in zip(games, gamescores):
if len(players) == 1:
list_zz.append(math.nan)
continue
past_diffs.clear()
this_diff.clear()
for (player1, score1), (player2, score2) in combinations(zip(players, scores), 2):
past_diffs[player1] += wd[player1][player2]
past_diffs[player2] += wd[player2][player1]
this_diff[player1][player2] = score1 - score2
this_diff[player2][player1] = score2 - score1
list_zz.extend(past_diffs[p] for p in players)
for player in players:
wd[player].update(this_diff[player])
print(list_zz)
</code></pre>
<p>Which looks like this:</p>
<pre class="lang-py prettyprint-override"><code>[0.0,
0.0,
nan,
-4.0,
4.0,
0.0,
0.0,
0.0,
nan,
-10.0,
13.0,
-3.0,
nan,
3.0,
-3.0,
-6.0,
6.0,
-10.0,
-10.0,
20.0,
nan,
14.0,
-14.0]
</code></pre>
<p>Example to understand the code:
In the 5th game where A, B and C play, A gets -4 from the 1st game, 0 from the 2nd, -6 from the 3rd, and 0 from the 4th. Note that only A, B and C count in the 5th game. To be more clear A scores -4 in the 1st game, in the second he doesnt play so he scores 0, in the 3rd we count only the results for its competitors B and C which gives -6, and in the 4th he doesnt play so he gets 0. Notices that results are from the past games against current competitors.</p>
<p>If you could elaborate on the code to make it more efficient and execute faster, I would really appreciate it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T02:38:46.523",
"Id": "481309",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/110290/discussion-between-rdllopes-and-mario-arend)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T16:04:20.167",
"Id": "481371",
"Score": "0",
"body": "What do the elements of `last_zz` represent? Also, when you re-ask a question, one usually includes a link to the previous question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T16:08:29.090",
"Id": "481373",
"Score": "0",
"body": "list_zz[x] is the result I am looking for every player in the same order than the game list. So that would be the result for ['A', 'B', 'B', 'A', 'B', 'C', 'D', 'E', 'B', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'A', 'B', 'C']"
}
] |
[
{
"body": "<h2>Solve with math</h2>\n<p>This is a math problem. Let say we have a competition: <code>[a, b, c]</code> score <code>[5, 2, 10]</code>, this means that the scoring is:</p>\n<p><span class=\"math-container\">$$\n\\begin{array}{|l|r|r|r|}\n& \\textrm{a} & \\textrm{b} & \\textrm{c} & \\textrm{res} \\\\\n\\hline\n\\textrm{a} & \\text{NaN} & 3 & -5 & -2 \\\\\n\\textrm{b} & -3 & \\text{NaN} & -8 & -11\\\\\n\\textrm{c} & 5 & 8 & \\text{NaN} & 13\n\\end{array}\n$$</span></p>\n<p>As you should be able to see, you don't need to calculate the sum again and again for each pair.</p>\n<p>Solution:<br />\nFor each team:\n<span class=\"math-container\">\\$\\text{team's score} \\times \\text{number of teams} - \\text{total score}\\$</span>.</p>\n<pre><code>score[a] = 5 * 3 - 17 = -2\nscore[b] = 2 * 3 - 17 = -11\nscore[c] = 10 * 3 - 17 = 13\n</code></pre>\n<p>The time complexity of this is <span class=\"math-container\">\\$O(n)\\$</span>. Calculate all pairs is <span class=\"math-container\">\\$O(n^2)\\$</span>.</p>\n<h2>Some code</h2>\n<p>Here I will save the total score for each team (not the history of the scores _ the code change for that would not be big tho).</p>\n<pre><code>from collections import Counter, defaultdict\n\n# test data\ngames = [['A', 'B'], ['B'], ['A', 'B', 'C', 'D', 'E'], ['B'], ['A', 'B', 'C'], ['A'], ['B', 'C'], ['A', 'B'],\n ['C', 'A', 'B'], ['A'], ['B', 'C']]\n\ngamescores = [[1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], [2.0, 7.0],\n [3.0, 6.0, 8.0], [2.0], [7.0, 9.0]]\n\nwd = defaultdict(float)\n\nfor players, scores in zip(games, gamescores):\n if len(players) == 1:\n continue\n total_sum = sum(scores)\n for player, score in zip(players, scores):\n wd[player] = wd[player] + score * len(scores) - total_sum\n\nprint(wd)\n</code></pre>\n<h3>Result</h3>\n<pre><code>defaultdict(<class 'float'>, {'A': -12.0, 'B': 32.0, 'C': -17.0, 'D': -14.0, 'E': 11.0})\n</code></pre>\n<h3>Edit: Grouping based on last results</h3>\n<p>OP clarified that each competition affect the total score taking from the previous competition because the grouping changes.</p>\n<p>In the example, <code>scores: [1.0, 5.0], [3.0], [2.0, 7.0, 3.0, 1.0, 6.0], [3.0], [5.0, 2.0, 3.0], [1.0], [9.0, 3.0], teams: [a,b], [b], [a,b,c,d,e], [b], [a,b,c]</code>,</p>\n<p>A scores as:</p>\n<pre>\n1st game: -4\n2nd game: 0 (he was not participant)\n3rd game: -6 (because at 5th game, only A, B, C are competing)\n</pre>\n<p>For that, we can pre-process the groups to make sure that only the competitors of next game are considered.</p>\n<h3>Pre-processing idea</h3>\n<p>That is just an example how to solve the issue using the pre-processing. Notice that is a backward thinking. Next game determines which competitors matter in terms of scoring. Therefore, the processing is done in reverse order.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def pre_process(games, gamescores):\n last_game = {}\n result = []\n for game in zip(reversed(games), reversed(gamescores)):\n game_dict = dict(zip(game[0], game[1]))\n if len(game[0]) == 1:\n result.append(game_dict)\n continue\n if len(last_game) != 0:\n union_set = set(game_dict.keys()).intersection(set(last_game.keys()))\n last_game = game_dict\n game_dict = {k: game_dict[k] for k in union_set}\n else:\n last_game = game_dict\n result.append(game_dict)\n return result\n\n\npairs = list(reversed(pre_process(games, gamescores)))\nwd = defaultdict(float)\nfor game in pairs:\n players = list(game.keys())\n scores = [game[k] for k in players]\n if len(players) == 1:\n continue\n\n total_sum = sum(scores)\n for player, score in zip(players, scores):\n wd[player] += score * len(scores) - total_sum\n print(wd)\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T00:08:44.390",
"Id": "481300",
"Score": "0",
"body": "the problem that I don't know what is list_zz by your example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T00:10:30.747",
"Id": "481301",
"Score": "0",
"body": "It is were I iterate and save the results of the for loops"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T23:17:10.367",
"Id": "481406",
"Score": "0",
"body": "I was thinking how to use your math solution and I think a better approach would be to iterate by each game and delete the competitors that do not compete from the whole list, then you can do your math calculations with the relevant ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T23:34:38.747",
"Id": "481408",
"Score": "0",
"body": "The idea behind the preprocessing is that. I remove the competitors that will not take part of the next game. But as I said, it is hard to reverse engineering because the goal was not really clear to me. For example, in this example `B` team varies a lot from what you expect."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T23:55:05.323",
"Id": "245102",
"ParentId": "245101",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-06T21:50:06.670",
"Id": "245101",
"Score": "3",
"Tags": [
"python",
"performance",
"programming-challenge"
],
"Title": "Analysis of multiple game scores"
}
|
245101
|
<p>In react I have a HTML Element Factory, it allows several different types of form elements to be created most with the same onChange but some have specific uses. I have been capturing them in this switch, but its time to refactor, what should an onChange() switch be converted to, should this too be a factory? Or just a object literal with functions? Or should I use a Factory Function here?</p>
<p>Some rough code advice would be very useful.</p>
<pre><code> const onChange = (event: any, tags: any, formEl: any) => {
setLayout(
layout?.map((el: IElement) => {
if (el.id === formEl.id) {
switch (formEl.type) {
case "autocomplete" :
case "autocompletewide": {
if (event.target.getAttribute("data-option-index") !== null) {
el.value =
formEl.options[
event.target.getAttribute("data-option-index")
].id;
return el;
} else {
el.value = "";
return el;
}
}
case "autocompletemulti": {
if (tags.length) {
const vals: string = tags.map((tag: IOption) => tag.id);
el.value = vals.toString();
return el;
} else {
el.value = "";
return el;
}
}
case "datepicker": {
let dateValue: Date | null = event;
if (dateValue !== null)
el.value = dateValue?.toISOString().substr(0, 10);
else el.value = "";
return el;
}
default: {
el.value = event.target.value;
return el;
}
}
} else {
return el;
}
})
);
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T09:20:00.843",
"Id": "481331",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T01:06:25.963",
"Id": "245104",
"Score": "3",
"Tags": [
"javascript",
"react.js",
"typescript"
],
"Title": "onChange Switch Handler"
}
|
245104
|
<p>I created a syntax highlighter in JavaScript. The language it highlights is AdBlock Filter Syntax, the language used to write filters for ad blocker extensions in browsers.</p>
<p>Shown here is the AdBlockSyntaxLine Class, which is the core class that dices a line of text into categories. These categories are used to do highlighting later.</p>
<p>The entire project can be found on my <a href="https://github.com/GeneralKenobi1/adblock-filter-analyzer" rel="noreferrer">GitHub</a>. And here is a link to the <a href="https://www.reddragonwebdesign.com/projects/AdBlock%20Filter%20Analyzer/" rel="noreferrer">live version</a>.</p>
<h2>Screenshot</h2>
<p><a href="https://i.stack.imgur.com/XdboZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XdboZ.png" alt="enter image description here" /></a></p>
<h2>AdBlockSyntaxLine</h2>
<pre><code>"use strict";
import { Helper } from './Helper.js';
export class AdBlockSyntaxLine {
string = "";
toParse = "";
syntax = {
'uboPreParsingDirective': '', // !#
'agHint': '', // !+
'comment': '', // !
'exception': '', // @@
'exceptionRegEx': '', // @@/regex/
'domainRegEx': '', // /regex/
'domain': '',
'option': '', // $
'selectorException': '', // #@#
'selector': '', // ##
'htmlFilter': '', // ##^
'htmlFilterException': '', // #@#^
'abpExtendedSelector': '', // #?#
'uboScriptlet': '', // ##+js()
'uboScriptletException': '', // #@#+js()
'abpSnippet': '', // #$#
'actionOperator': '', // :style() :remove()
};
isValid = "not sure";
errorHint = "";
constructor(s) {
this.string = s;
this.toParse = this.string;
try {
this._categorizeSyntax();
} catch(e) {
// only catch what we want, let actual errors throw to console
if ( e === true || e === false || e === "not sure" ) {
this.isValid = e;
} else {
throw e;
}
}
if ( this.isValid !== true ) {
try {
this._lookForErrors();
} catch(e) {
// only catch what we want, let actual errors throw to console
if ( e === true || e === false || e === "not sure" ) {
this.isValid = e;
} else {
throw e;
}
}
}
this._lookForMismatch();
}
_lookForErrors() {
// no spaces in domains or domain regex
if ( this.syntax['domainRegEx'] && this.syntax['domainRegEx'].search(/ /g) !== -1 ) {
this.errorHint = "no spaces allowed in domains, exceptions, domainRegEx, or exceptionRegEx";
throw false;
}
if ( this.syntax['domain'] && this.syntax['domain'].search(/ /g) !== -1 ) {
this.errorHint = "no spaces allowed in domains, exceptions, domainRegEx, or exceptionRegEx";
throw false;
}
if ( this.syntax['exceptionRegEx'] && this.syntax['exceptionRegEx'].search(/ /g) !== -1 ) {
this.errorHint = "no spaces allowed in domains, exceptions, domainRegEx, or exceptionRegEx";
throw false;
}
if ( this.syntax['exception'] && this.syntax['exception'].search(/ /g) !== -1 ) {
this.errorHint = "no spaces allowed in domains, exceptions, domainRegEx, or exceptionRegEx";
throw false;
}
// Delete regex. Regex is allowed to contain our special chars. When we do our searches, we don't want to get false positives.
let s = this.string;
s = s.replace(/^\/.*?[^\\]\//g, '');
s = s.replace(/^@@\/.*?[^\\]\//g, '@@');
// look for double selectors $ #@# ## ##^ #@#^ #?# ##+js( #@#+js( #$#
// had to take out $, too many false positives, it's used in CSS and +js()
let count = Helper.countRegExMatches(s, /\#@#|##|##\^|#@#\^|#\?#|##\+js\(|#@#\+js\(|#\$#/);
if ( count > 1 ) {
this.errorHint = "selector-ish syntax $ #@# ## ##^ #@#^ #?# ##+js( #@#+js( #$# is only allowed once per filter";
throw false;
}
// look for double actionOperators
count = Helper.countRegExMatches(s, /:style\(|:remove\(/);
if ( count > 1 ) {
this.errorHint = "actionOperators :style() :remove() are only allowed once per filter";
throw false;
}
// actionOperators must be paired with a domain
let domainPresent = (
this.syntax['domain'] ||
this.syntax['exception'] ||
this.syntax['domainRegEx'] ||
this.syntax['exceptionRegEx']
);
if ( this.syntax['actionOperator'] && ! domainPresent ) {
this.errorHint = "actionOperators :style() :remove() must be used with a URL";
throw false;
}
// actionOperators not allowed to be paired with ##+js( #@#+js( #$# $
// TODO: probably also need to ban pairing with #@#|##|##^|#@#^|#?#| but so far :style() passes ubo validator, :remove() fails
let bannedSyntaxPresent = (
this.syntax['uboScriptlet'] ||
this.syntax['uboScriptletException'] ||
this.syntax['abpSnippet'] ||
this.syntax['option']
);
let countActionOperators = Helper.countRegExMatches(s, /:style\(|:remove\(/);
if ( bannedSyntaxPresent && countActionOperators ) {
this.errorHint = "actionOperators :style() :remove() cannot be used with ##+js( #@#+js( #$# $";
throw false;
}
// @@exceptions may not contain any selectors except options
count = Helper.countRegExMatches(s, /\#@#|##|##\^|#@#\^|#\?#|##\+js\(|#@#\+js\(|#\$#|:style\(|:remove\(/);
let exception = ( this.syntax['exception'] || this.syntax['exceptionRegEx'] );
if ( exception && count ) {
this.errorHint = "@@ statements may not contain selector-ish syntax $ #@# ## ##^ #@#^ #?# ##+js( #@#+js( #$# or action operators :style() :remove()"
throw false;
}
// ##+js() #@#+js() :style() :remove() must end in )
let lastChar = s.right(1);
let shouldEndInParenthesis = ( this.syntax['uboScriptlet'] || this.syntax['uboScriptletException'] || this.syntax['actionOperator'] );
if ( shouldEndInParenthesis && lastChar !== ')' ) {
this.errorHint = "##+js() #@#+js() :style() :remove() must end in )"
throw false;
}
}
/** Takes the values in the this.syntax array and builds them into a string. Then makes sure that string matches the input string. If these don't match, this is a pretty sure sign there's a bug. */
_lookForMismatch() {
let lineString = "";
for ( let key in this.syntax ) {
lineString += this.syntax[key];
}
if ( lineString !== this.string ) {
this.isValid = "mismatch";
}
}
/** dice syntax string up into categories: comment !, exception @@, domain, option $, selectorException #@#, selector ##, abpExtendedSelector #?#, actionoperator :style(), abpSnippet #$#, etc. */
_categorizeSyntax() {
this._lookForComments();
this._lookForDomains();
// lookForActionOperators needs to come before lookForSelectors, even though actionOperators appear after selectors in the string.
this._lookForActionOperators();
this._lookForSelectors();
}
_lookForComments() {
// uboPreParsingDirective !#
if ( this.toParse.left(2) === "!#" ) {
this.syntax['uboPreParsingDirective'] = this.string;
throw "not sure";
}
// agHint !+
if ( this.toParse.left(2) === "!+" ) {
this.syntax['agHint'] = this.string;
throw "not sure";
}
// comment ! [
if ( this.string.left(1) === '!' || this.string.left(1) === '[' ) {
this.syntax['comment'] = this.string;
throw true;
}
}
_lookForDomains() {
// domainRegEx /regex/
let matchPos = this.toParse.search(/^\/.*?[^\\]\//);
let regExLookingStringFound = (matchPos !== -1);
let toParse = this.toParse.replace(/^\/.*?[^\\]\//, '');
let regEx = this.toParse.left(this.toParse.length - toParse.length);
let selectorAfterRegEx = (toParse.search(/^(<span class="math-container">\$|#@#|##|##\^|#@#\^|#\?#|##\+js\(|#@#\+js\(|#\$</span>#)/) !== -1);
let nothingAfterRegEx = (toParse.length === 0);
if ( regExLookingStringFound && (selectorAfterRegEx || nothingAfterRegEx) ) {
this.syntax['domainRegEx'] = regEx;
this.toParse = toParse;
return;
}
// exceptionRegEx @@/regex/
matchPos = this.toParse.search(/^@@\/.*?[^\\]\//);
regExLookingStringFound = (matchPos !== -1);
toParse = this.toParse.replace(/^@@\/.*?[^\\]\//, '');
regEx = this.toParse.left(this.toParse.length - toParse.length);
selectorAfterRegEx = (toParse.search(/^(<span class="math-container">\$|#@#|##|##\^|#@#\^|#\?#|##\+js\(|#@#\+js\(|#\$</span>#)/) !== -1);
nothingAfterRegEx = (toParse.length === 0);
if ( regExLookingStringFound && (selectorAfterRegEx || nothingAfterRegEx) ) {
this.syntax['domainRegEx'] = regEx;
this.toParse = toParse;
return;
}
// exception @@
let domainException = false;
if ( this.string.left(2) === '@@' ) {
domainException = true;
}
// domain
// parse until $ #@# ## #?# #$#
// str.search returns first position, when searching from left to right (good)
matchPos = this.toParse.search(/#@#|##|#\?#|#<span class="math-container">\$#|\$</span>/);
// if no categories after the domain
if ( matchPos === -1 ) {
this.syntax['domain'] = this.toParse;
this.toParse = '';
} else {
this.syntax['domain'] = this.toParse.left(matchPos);
this.toParse = this.toParse.slice(matchPos);
}
// exception @@ must have a domain
if ( domainException && ! this.syntax['domain'] ) {
this.errorHint = "exception @@ must have a domain";
throw false;
}
// exception @@
if ( domainException ) {
this.syntax['exception'] = this.syntax['domain'];
this.syntax['domain'] = "";
}
}
_lookForSelectors() {
// option $ (example: image)
if ( this.toParse.left(1) === '$' ) {
this.syntax['option'] = this.toParse;
// OK to have nothing before it
// Nothing allowed after it
throw "not sure";
}
// abpSnippet #$# (example: log hello world!)
if ( this.toParse.left(3) === "#$#" ) {
this.syntax['abpSnippet'] = this.toParse;
// Nothing allowed after it
throw "not sure";
}
// uboScriptletException #@#+js(
if ( this.toParse.left(7) === "#@#+js(" ) {
this.syntax['uboScriptletException'] = this.toParse;
// Nothing allowed after it
throw "not sure";
}
// uboScriptlet ##+js(
if ( this.toParse.left(6) === "##+js(" ) {
this.syntax['uboScriptlet'] = this.toParse;
// per ublock documentation, example.com##+js() when js() is empty is an error
if ( this.syntax['uboScriptlet'] === "##+js()" ) {
this.errorHint = "per ublock documentation, example.com##+js() when js() is empty is an error";
throw false;
}
// Nothing allowed after it
throw "not sure";
}
// htmlFilter ##^
if ( this.toParse.left(3) === "##^" ) {
this.syntax['htmlFilter'] = this.toParse;
return;
}
// htmlFilterException #@#^
if ( this.toParse.left(4) === "#@#^" ) {
this.syntax['htmlFilterException'] = this.toParse;
return;
}
// selectorException #@#
if ( this.toParse.left(3) === "#@#" ) {
this.syntax['selectorException'] = this.toParse;
return;
}
// selector ##
if ( this.toParse.left(2) === "##" ) {
this.syntax['selector'] = this.toParse;
return;
}
// abpExtendedSelector #?#
if ( this.toParse.left(3) === "#?#" ) {
this.syntax['abpExtendedSelector'] = this.toParse;
return;
}
}
_lookForActionOperators() {
let matchPos = this.toParse.search(/(:style\(|:remove\().*\)$/);
if ( matchPos !== -1 ) {
this.syntax['actionOperator'] = this.toParse.slice(matchPos);
this.toParse = this.toParse.left(matchPos);
}
}
/** Gets a string with a JSON representation of the syntax categories. Also prints isValid and errorHint. */
getJSON() {
let s = "";
s += "Filter = " + this.string + "\n";
s += "Valid? = " + this.isValid + "\n";
if ( this.errorHint ) {
s += "Error Hint = " + this.errorHint + "\n";
}
s += JSON.stringify(this.syntax);
// add enters after commas
s = s.replace(/",/g, '",\n');
return s;
}
/** Gets a string of the filter syntax, with HTML <span>s wrapped around each category of syntax. These <span>s will be used to highlight the text the correct color in the richTextBox. */
getRichText() {
let richText = "";
let classes = "";
for ( let key in this.syntax ) {
classes = key;
if ( ! this.isValid || this.isValid === "mismatch" ) {
classes += " error";
}
if ( this.syntax[key] ) {
let s = this.syntax[key];
s = Helper.escapeHTML(s);
s = s.replace(/ /g, "&nbsp;");
richText += '<span class="' + classes + '">' + s + '</span>';
}
}
return richText;
}
}
</code></pre>
<h2>Helper</h2>
<pre><code>"use strict";
export class Helper {
static countRegExMatches(str, regExPattern) {
regExPattern = new RegExp(regExPattern, "g");
return ((str || '').match(regExPattern) || []).length;
}
static escapeHTML(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
}
</code></pre>
<h2>String.prototype</h2>
<pre><code>// TODO: figure out how to move this into its own file and import/export it. Currently, adding "export" to the beginning of it generates an error.
Object.assign(String.prototype, {
/** @description "Testing 123".left(4) = "Test" */
left(length) {
return this.slice(0, length);
},
/** @description "Testing 123".right(3) = "123" */
right(length) {
return this.substr(this.length - length);
},
});
</code></pre>
<h2>Possible code smells</h2>
<ul>
<li>Code needs some optimization. Currently gets pretty slow if parsing more than 500 lines. I imagine use of RegEx is slowing things down a bit.</li>
<li>I don't use const. So far I am not liking JavaScript's insistence that variables be declared, and having to pick between let/const. Seems to require a lot of thought and require a lot of debugging, without providing much benefit.</li>
<li>If anybody knows how to put string.prototype in its own file and get it to work with the <code>export</code> keyword, that'd be awesome. I couldn't figure it out, so I put it in my main file as a workaround.</li>
<li>Try/Catch true/false/"not sure" feels like a code smell. I couldn't think of a better way to <code>return</code> across multiple functions though.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T13:42:30.420",
"Id": "481347",
"Score": "1",
"body": "https://stackoverflow.com/a/25396011/7602 , also, cool question"
}
] |
[
{
"body": "<p>I don't think I can review all of that, but here are some thoughts to your questions and some general remarks.</p>\n<h1><code>const</code>/<code>let</code></h1>\n<p>I would guess this is simply that your programming style colliding with the trend in JavaScript towards functional programming where mutability is an anti-pattern and generally avoided.</p>\n<p>The first step to using <code>const</code> is to avoid reusing variables. This on the first look seems like it would introduce a lot of superfluous variables, but usually alternative syntaxes or patterns can get around that.</p>\n<p>Just one example: Instead of</p>\n<pre><code>let s = this.string;\ns = s.replace(/^\\/.*?[^\\\\]\\//g, '');\ns = s.replace(/^@@\\/.*?[^\\\\]\\//g, '@@');\n</code></pre>\n<p>one <em>could</em> write</p>\n<pre><code>const s = this.string;\nconst s1 = s.replace(/^\\/.*?[^\\\\]\\//g, '');\nconst s2 = s1.replace(/^@@\\/.*?[^\\\\]\\//g, '@@');\n</code></pre>\n<p>or (in this case) better would be</p>\n<pre><code>const s = this.string\n .replace(/^\\/.*?[^\\\\]\\//g, '')\n .replace(/^@@\\/.*?[^\\\\]\\//g, '@@');\n</code></pre>\n<h1><code>String.prototype</code></h1>\n<p>Modifying a prototype is generally a bad idea. It affects all scripts globally and that's also the reason there is no way to "export" it: You can't limit it to just your script. It effects all scripts in the same environment, which can lead to unexpected errors.</p>\n<p>In your case it's not really needed IMO anyway. Using <code>left(length)</code> doesn't give much more information than just <code>slice(0, length)</code>, and <code>right(length)</code> can similarly be expressed as <code>slice(-length)</code>.</p>\n<p>If you do prefer separate functions just use regular functions.</p>\n<p>BTW, <code>x.left(2) === "##"</code> can be better expressed as <code>x.startsWith("##")</code>.</p>\n<h1><code>throw</code></h1>\n<p>Yeah, this is bad. Combined with setting the state of the class the execution and data flow is completely in-transparent for the reader. A better understandable (albeit verbose) way would be to have each function return a status and after calling it check if the status requires aborting. Something like this pseudo code:</p>\n<pre><code>_categorizeSyntax() {\n const commentStatus = this._lookForComments();\n if (isFinished(commentStatus)) { return commentStatus; }\n\n const domainStatus = this._lookForDomains();\n if (isFinished(domainStatus)) { return domainStatus; }\n\n // etc.\n}\n\n_lookForComments() {\n if ( this.toParse.left(2) === "!#" ) {\n this.syntax['uboPreParsingDirective'] = this.string;\n return { isValid: "not sure" };\n } \n // etc.\n }\n\n isFinished(result) {\n return result.hasOwnProperty("isValid");\n }\n</code></pre>\n<h1><code>class</code></h1>\n<p>A thing that plays into this is the use of a class. I believe having all functionality in the constructor and using the class as a "data dump" is an anti-pattern, but I can't find a proper name for it.</p>\n<p>It would be better to put the logic in a regular function that in the end returns an plain data object containing the result of the parsing.</p>\n<p>Generally functions are much better readable if they <em>only</em> reads its parameters (and not read from the "global" state) and <em>only</em> return data (instead of mutating the "global" state) - so-called "pure" functions.</p>\n<p>The state could be, for example, instead passed around as a parameter (again pseudo code):</p>\n<pre><code>_categorizeSyntax({string: "The string to be parsed"}) // Inital state.\n\n_categorizeSyntax(state) {\n const commentState = this._lookForComments(state);\n if (isFinished(commentState)) { return commentState; }\n\n const domainState = this._lookForDomains(commentState);\n if (isFinished(domainState)) { return domainState; }\n\n // etc.\n return state;\n}\n\n_lookForComments(state) {\n if ( state.string.left(2) === "!#" ) {\n return {\n ...state,\n syntax: { "uboPreParsingDirective": state.string },\n isValid: "not sure"\n };\n } \n // etc.\n return state;\n }\n\n isFinished(result) {\n return result.hasOwnProperty("isValid");\n }\n</code></pre>\n<p>Another way to do it would be use the functional "either" pattern/monad, but that would too much here.</p>\n<h1><code>getRichText</code>/<code>escapeHTML</code></h1>\n<p>Some final thoughts about <code>getRichText</code> and <code>escapeHTML</code> (although there aren't seemed to used in this code):</p>\n<p>It would be better to use existing libraries or built in functionality for standardized things like <code>escapeHTML</code>. If this code runs in a browser it would make sense to let the browser build the HTML. Depending what you are doing with the created HTML elements it also would make sense to directly return a list of DOM elements instead of HTML in strings. For example:</p>\n<pre><code>getRichText() {\n const elements = [];\n for ( let key in this.syntax ) {\n if ( this.syntax[key] ) {\n const span = document.createElement("span");\n\n span.classList.add(key);\n if ( ! this.isValid || this.isValid === "mismatch" ) {\n span.classList.add("error");\n }\n\n // Use Unicode non-breaking space instead of HTML entity\n const text = this.syntax[key].replace(/ /g, "\\u00A0");\n span.textContent = text;\n\n elements.push(span);\n }\n }\n return elements;\n }\n}\n</code></pre>\n<p>If needed the text representation of a DOM element can be got with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML\" rel=\"nofollow noreferrer\"><code>.outerHTML</code></a>.</p>\n<p>And if the code isn't running in a browser or you really want a string instead of DOM elements, then you should consider a template engine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T20:41:05.607",
"Id": "481396",
"Score": "0",
"body": "Thank you very much for your awesome feedback. The quality and positivity of the answers I get on Code Review is superb. I will work my way through your list and incorporate most of these. I really appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T00:49:09.540",
"Id": "481410",
"Score": "0",
"body": "Also, I started a bounty on StackOverflow for a question related to this program. Feel free to check it out. https://stackoverflow.com/questions/62705449/fix-cursor-position-when-replacing-innerhtml-of-div-contenteditable-true"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T15:04:23.283",
"Id": "245136",
"ParentId": "245106",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "245136",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T01:28:51.117",
"Id": "245106",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "AdBlock Syntax Highlighter (Part 1 - AdBlockSyntaxLine Class)"
}
|
245106
|
<p>Looking for feedback on this code to reverse a double linked list. Things I am potentially looking for but missed -> redundant operations, extra / unnecessary arithmetic, improvement in code style. Thank yoU!</p>
<pre class="lang-c prettyprint-override"><code>
typedef struct Node {
int data;
struct Node* next;
struct Node* prev;
} Node;
void reverse(Node** head) {
Node* curr = *head;
Node* prev_ptr = NULL;
Node* next_ptr = NULL;
while (curr != NULL) {
prev_ptr = curr->prev;
next_ptr = curr->next;
curr->prev = next_ptr;
curr->next = prev_ptr;
(*head) = curr;
curr = next_ptr;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Seems simple and straightforward enough that you may not get many answers. The one thing that you're definitely missing is <strong>unit tests</strong>. Have you <em>tested</em> that your code works? for a two-element list? for a one-element list? for an empty list?</p>\n<p>Your extra blank lines (after the <code>{</code> and before the two <code>}</code>s) are unidiomatic; most programmers would say that your reader has better things to do with that screen real estate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T03:38:09.810",
"Id": "245110",
"ParentId": "245108",
"Score": "5"
}
},
{
"body": "<p>You don't need to reverse a doubly linked list, which is an <code>O(n)</code> operation.</p>\n<p>Just define a structure that will hold the head and tail of the list.</p>\n<pre><code>struct List\n{\n Node* head;\n Node* tail;\n unsigned int count; // you can also keep track of number of nodes to access the count in O(1)\n}\n</code></pre>\n<p>Functions manipulating the list shall now accept <code>List* list</code> rather then <code>Node** head</code>. They will also have to contain logic that checks and assigns the tail, but none of the operations should get any more complex in terms of its big-O time complexity.</p>\n<p>Now traversing the list in reversed order is just matter of traversing the list from tail to head, rather then head to tail direction.</p>\n<p>Doubly linked list without a tail is basically a singly linked list with capability to traverse back from where you already traversed forward, but never directly from the tail towards the head (without additional effort).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T07:32:00.717",
"Id": "481316",
"Score": "0",
"body": "Never thought of it that way...nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T08:41:38.383",
"Id": "481321",
"Score": "0",
"body": "Works fine with a few instances of `Node`. Yet with a program with many instances (potentially most empty), this approach now obliges increase memory footprint for what could be a rarely used function. Might/might not be worth it. Depends on larger use of `Node`. I _suspect_ it is a win, but not certainly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T10:02:41.353",
"Id": "481337",
"Score": "0",
"body": "@chux-ReinstateMonica Linked lists (doubly, singly) are generaly not a very good choice for a big amount of items, because they allocate small chunks of memory for every new item. Something like C++'s std::vector should be preferred. Doubly linked list is to be used where its features can be taken advantage of (that is if you want bidirectional iteration). If you don't need backward iteration, you should be fine with a singly linked list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T10:04:14.360",
"Id": "481338",
"Score": "0",
"body": "@chux-ReinstateMonica For example hash table is an array of singly linked lists, yes most of them are probably empty, yes it would take up more memory if doubly linked list was used. But no, doubly linked list is not used by hash table, because hash table never needs to iterate those lists backwards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T04:32:19.503",
"Id": "481511",
"Score": "0",
"body": "Correction: hash table is not array of singly linked lists. It can be implemented that way but there are other ways to implement a hash table..."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T04:54:14.203",
"Id": "245115",
"ParentId": "245108",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "245115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T02:37:42.133",
"Id": "245108",
"Score": "6",
"Tags": [
"c",
"linked-list"
],
"Title": "Reversing a doubly linked list in C"
}
|
245108
|
<p>A few days ago I posted my password generator project to help me learn and become more comfortable. I got a lot of great replies from that and I've sense updated and would love another look at the program.</p>
<p>I've made it so that I can import it and use it to generator a password. I've also added support for completely custom subsets of characters.</p>
<p>Throw any suggests or comments you have! Anything is welcome.</p>
<pre><code>import string
from string import ascii_lowercase
from string import ascii_uppercase
from string import digits as numeric
from string import punctuation
import secrets
import argparse
from argparse import HelpFormatter
def generate_characters(character_set, character_amount):
for _ in range(0, character_amount):
yield secrets.choice(character_set)
def shuffle(input_str):
output = ""
for _ in range(0, len(input_str)):
index = secrets.randbelow(len(input_str))
output += "".join(input_str[index])
input_str = "".join([input_str[:index], input_str[index + 1 :]])
return output
def generate_password(password_length,
subset_lowercase=ascii_lowercase, subset_uppercase=ascii_uppercase,
subset_numeric=numeric, subset_special="!@#$%^&*",
min_lowercase=1, min_uppercase=1,
min_numeric=1, min_special=1):
superset = "".join([subset_lowercase, subset_uppercase, subset_numeric, subset_special])
password = "".join(generate_characters(subset_lowercase, min_lowercase))
password += "".join(generate_characters(subset_uppercase, min_uppercase))
password += "".join(generate_characters(subset_numeric, min_numeric))
password += "".join(generate_characters(subset_special, min_special))
password += "".join(generate_characters(superset, password_length-len(password)))
return shuffle(password)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
formatter_class=HelpFormatter,
description="Generates a password",
usage="")
parser.add_argument(
"-len",
"--length",
type=int,
default=24,
dest="password_length",
help="Length of the generated password")
parser.add_argument(
"-lc",
"--lower",
type=int,
default=1,
dest="min_lowercase",
help="Minimum number of lowercase alpha characters")
parser.add_argument(
"-uc",
"--upper",
type=int,
default=1,
dest="min_uppercase",
help="Minimum number of uppercase alpha characters")
parser.add_argument(
"-num",
"--numeric",
type=int,
default=1,
dest="min_numeric",
help="Minimum number of numeric characters")
parser.add_argument(
"-sp",
"--special",
type=int,
default=1,
dest="min_special",
help="Minimum number of special characters")
parser.add_argument(
"-ext",
"--extended",
action="store_const",
default=False,
const=True,
dest="special_extended",
help="Toggles the extended special character subset. Passwords may not be accepted by all services")
parser.add_argument(
"-sl",
"--subset_lower",
type=str,
default=ascii_lowercase,
dest="subset_lower",
help="Allows for a custom subset of lowercase characters")
parser.add_argument(
"-su",
"--subset_upper",
type=str,
default=ascii_uppercase,
dest="subset_upper",
help="Allows for a custom subset of uppercase characters")
parser.add_argument(
"-sn",
"--subset_numeric",
type=str,
default=numeric,
dest="subset_numeric",
help="Allows for a custom subset of numeric characters")
parser.add_argument(
"-ss",
"--subset_special",
default="",
type=str,
dest="subset_special",
help="Allows for a custom subset of special characters")
args = parser.parse_args()
if args.subset_special:
special = args.subset_special
elif args.special_extended:
special = punctuation
else:
special = "!@#$%^&*"
generated_password = generate_password(
args.password_length,
args.subset_lower,
args.subset_upper,
args.subset_numeric,
special,
args.min_lowercase,
args.min_uppercase,
args.min_numeric,
args.min_special,
)
print("Password:", generated_password)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T04:50:48.930",
"Id": "481315",
"Score": "0",
"body": "talking about the code it is pretty well-written and formatted, good job!."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T08:36:57.180",
"Id": "481319",
"Score": "0",
"body": "Can you link your older code here? I want to understand what secrets is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T11:25:59.973",
"Id": "530168",
"Score": "0",
"body": "@VisheshMangla [The secrets module is used for generating cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets.](https://docs.python.org/3/library/secrets.html). Available in stdlib since v3.6"
}
] |
[
{
"body": "<ul>\n<li><p>You have a lot of inconsistencies.</p>\n<ul>\n<li><p><code>import string</code> <code>from string import ...</code> But then only using <code>import secrets</code>.</p>\n<p>I would only use <code>import string</code>.</p>\n</li>\n<li><p>You do <code>[:index]</code> but also <code>[index + 1 :]</code>.</p>\n</li>\n<li><p>You do <code>index + 1</code> but you also do <code>password_length-len(password)</code>.</p>\n</li>\n<li><p>You start <code>generate_password</code> using a one argument per line style, and then don't for the rest of the arguments.</p>\n</li>\n</ul>\n</li>\n<li><p>You should move <code>"!@#$%^&*"</code> into a constant, as you've duplicated it.</p>\n</li>\n<li><p>You can use <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.SystemRandom.choices</code></a> rather than <code>generate_characters</code>. <a href=\"https://docs.python.org/3/library/random.html#random.SystemRandom\" rel=\"nofollow noreferrer\"><code>SystemRandom</code></a> uses <a href=\"https://docs.python.org/3/library/os.html#os.urandom\" rel=\"nofollow noreferrer\"><code>os.urandom</code></a> which is "suitable for cryptographic use."</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\nsrandom = random.SystemRandom()\n\n\ndef generate_characters(character_set, character_amount):\n return srandom.choices(character_set, k=character_amount)\n</code></pre>\n</li>\n<li><p>You can use <a href=\"https://docs.python.org/3.8/library/random.html#random.sample\" rel=\"nofollow noreferrer\"><code>random.SystemRandom.sample</code></a> to replace <code>shuffle</code>.</p>\n</li>\n<li><p>Your current method is really inefficent it runs in <span class=\"math-container\">\\$O(n^2)\\$</span> time.\nAs you're building a new list every iteration.</p>\n<pre class=\"lang-py prettyprint-override\"><code>"".join([input_str[:index], input_str[index + 1 :]])\n</code></pre>\n<p>Instead change <code>input_str</code> to a list and use a similar algorithm by swapping the current index with the selected. Also known as the <a href=\"https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle\" rel=\"nofollow noreferrer\">Fisher–Yates shuffle</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def shuffle(input_str):\n output = list(input_str)\n for i in range(len(input_str)):\n index = srandom.randrange(i, len(input_str))\n output[i], output[index] = output[index], output[i]\n return "".join(output)\n</code></pre>\n</li>\n<li><p>I'm not a fan of passing so many keyword arguments to <code>generate_password</code>.\nI would instead make it take tuples of (subset, amount) and build the password that way.</p>\n<p>You can loop over these arguments so that the code is simple too.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def generate_password(password_length, *subsets):\n password = "".join(\n generate_characters(subset, minimum)\n for subset, minimum in subsets\n )\n superset = "".join(subset for subset, _ in subsets)\n password += "".join(generate_characters(superset, password_length - len(password)))\n return shuffle(password)\n</code></pre>\n</li>\n</ul>\n<hr />\n<p><strong>Suggested code</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>import string\nimport random\nimport argparse\n\nsrandom = random.SystemRandom()\n\n\ndef generate_password(password_length, *subsets):\n password = "".join(\n "".join(srandom.choices(subset, k=minimum))\n for subset, minimum in subsets\n )\n superset = "".join(subset for subset, _ in subsets)\n password += "".join(srandom.choices(superset, k=password_length - len(password)))\n return "".join(srandom.sample(password, len(password)))\n\n\nif __name__ == "__main__":\n ...\n\n generated_password = generate_password(\n args.password_length,\n (args.subset_lower, args.min_lowercase),\n (args.subset_upper, args.min_uppercase),\n (args.subset_numeric, args.min_numeric),\n (special, args.min_special),\n )\n print("Password:", generated_password)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T09:08:59.880",
"Id": "481324",
"Score": "0",
"body": "Is srandom.choices different from random.choices?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T09:10:02.507",
"Id": "481325",
"Score": "0",
"body": "@VisheshMangla Yes, please read the description accompanying the code as it will explain how it is and why it is fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T09:14:33.750",
"Id": "481327",
"Score": "0",
"body": "ok, thanks for the info."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T08:49:33.780",
"Id": "245121",
"ParentId": "245114",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T04:46:41.547",
"Id": "245114",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Password generator project in Python"
}
|
245114
|
<p>I'm using Temporal Tables on postgresql (<a href="https://github.com/arkhipov/temporal_tables" rel="nofollow noreferrer">https://github.com/arkhipov/temporal_tables</a>) and C# with dapper.</p>
<p>I'm storing an entity together with its changes.
Here's an example entity, with an Id and two values. It was created in 2006 and underwent two simultaneous changes in 2007</p>
<pre><code>| ID | IntValue | StrValue | sys_period |
| 1 | 0 | NULL | [2006-08-08, 2007-02-27) |
| 1 | 1 | "foo" | [2007-02-27, ) |
</code></pre>
<p><strong>Here's my setup for storing that kind of data</strong></p>
<p>I have a table with the current entity state:</p>
<pre><code>CREATE TABLE public.SomeEntity
(
Id i integer PRIMARY KEY,
IntValue integer NULL,
StrValue text NULL,
sys_period tstzrange NOT NULL DEFAULT tstzrange(current_timestamp, null)
);
CREATE TABLE public.SomeEntity_History (LIKE public.SomeEntity);
CREATE TRIGGER versioning_trigger
BEFORE INSERT OR UPDATE OR DELETE ON public.SomeEntity
FOR EACH ROW EXECUTE PROCEDURE versioning('sys_period','public.SomeEntity_History ', true);
CREATE VIEW SomeEntity_With_History AS
SELECT * FROM SomeEntity
UNION ALL
SELECT * FROM SomeEntity_History;
</code></pre>
<p><code>SELECT * FROM SomeEntity_With_History WHERE Id = 1</code> now gives the above table</p>
<p><strong>So, I have a list of the state of the entity at certain times (which I'm going to call 'history'), but how do I see changes?</strong></p>
<p>I see a change as something like this model (in C#):</p>
<pre><code>public class EntityChange
{
public DateTime Timestamp { get; set; }
public PropertyChange[] Changes { get; set; }
}
public class PropertyChange
{
public string PropertyName { get; set; }
public object OldValue { get; set; }
public object NewValue { get; set; }
public Type Type { get; set; }
}
</code></pre>
<p><strong>I have a way to change History into Changes</strong></p>
<p>It's a query in SQL and some mapping, type conversion and nesting in C#. But it seems messy. Is it any good?</p>
<pre><code>public async Task<IEnumerable<EntityChange>> GetArticleChangesAsync(int articleId)
{
var propertyChanges = await _context.GetConnection().QueryAsync<PropertyChangeQueryItem>(
@"SELECT PropertyName, NewValue, OldValue, TypeName, Timestamp
FROM
(
SELECT
IntValue, LAG(IntValue) OVER previous AS old_IntValue,
StrValue, LAG(StrValue) OVER previous AS old_StrValue,
LOWER(sys_period) AS timestamp
FROM someentity_with_history
WHERE id = @id
WINDOW previous AS (PARTITION BY id ORDER BY sys_period ASC)
) AS rows
CROSS JOIN LATERAL
(
VALUES
('IntValue', CAST (IntValue AS text), CAST (old_IntValue AS text), @intType),
('StrValue', StrValue, old_StrValue, @stringType),
) AS entityChanges(PropertyName, NewValue, OldValue, TypeName)
WHERE NewValue IS DISTINCT FROM OldValue",
new
{
articleId,
intType = typeof(int?).FullName,
stringType = typeof(string).FullName
});
return PropertyChangeQueryItem.DeNormalize(propertyChanges);
}
internal class PropertyChangeQueryItem
{
public DateTime Timestamp { get; set; }
public string PropertyName { get; set; }
public string NewValue { get; set; }
public string OldValue { get; set; }
public string TypeName { get; set; }
public static IEnumerable<EntityChange> DeNormalize(IEnumerable<PropertyChangeQueryItem> items)
{
var groups = items.GroupBy(ic => ic.Timestamp);
var entityChanges = groups.Select(grp => new EntityChange
{
Timestamp = grp.Key,
Changes = grp.Select(i =>
{
var type = GetType(i.TypeName);
return new PropertyChange
{
PropertyName = i.PropertyName,
NewValue = DeStringify(i.NewValue, type),
OldValue = DeStringify(i.OldValue, type),
Type = type
};
})
.ToArray()
});
return entityChanges;
}
private static Type GetType(string typeName)
{
var type = Type.GetType(typeName);
return Nullable.GetUnderlyingType(type) ?? type;
}
private static object DeStringify(string value, Type type)
{
return value == null ? null : Convert.ChangeType(value, type);
}
}
</code></pre>
<p>So what's happening?</p>
<p>I match each row of history with its preceeding row using 'LAG' with 'previous'.
Then, I cut apart these rows so that I have one row for each column, using <code>CROSS JOIN LATERAL</code>.
Then I just choose the rows where the OldValue is different from the new value.</p>
<p>Since I can't be specific about what type I'd like "OldValue" and "NewValue" to be, I have to convert everything to a string. I include the C# type information at that point so I can recover it back into the actual type.</p>
<p>So that query ends up transforming my entity history into this:</p>
<pre><code>| PropertyName | NewValue | OldValue | TypeName | Timestamp |
| "IntValue" | 1 | 0 | System.int32 | 2007-02-27 |
| "StrValue" | "foo" | NULL | System.string | 2007-02-27 |
</code></pre>
<p>Then I use the C# to shuffle that into a nested class model and unstringify the types in the DeNormalize method. In the above example table that would result in one entity change at 2007-02-27 with two property changes:</p>
<pre><code>{
DateTime: 2007-02-27
Changes: [
{
PropertyName: "IntValue",
OldValue: 0,
NewValue: 1,
Type: typeof(int)
},
{
PropertyName: "StrValue",
OldValue: null,
NewValue: "foo",
Type: typeof(string)
}
]
}
</code></pre>
<p>So, this works. It doesn't return unnecessary data to C# from sql as it does most of the heavy lifting in SQL. But having to specify every column name twice in the SQL code and having to leave C# type hints and then un-stringify everything is messy. And I'm not sure if the query could be more elegant. What do you think?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T09:18:48.957",
"Id": "481329",
"Score": "1",
"body": "We require concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code,... are outside the scope of this site. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T12:28:44.603",
"Id": "481343",
"Score": "3",
"body": "Is there a reason you're not calling a stored procedure from C#? The question is a little bit confusing, it is primarily an SQL question but includes C# as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T15:08:47.093",
"Id": "481367",
"Score": "1",
"body": "I consider this on-topic. The only risky bit is the title prefix, which I will delete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T19:10:46.820",
"Id": "481575",
"Score": "0",
"body": "@Reinderien Can you answer it then? It's accumulating close votes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T22:59:46.323",
"Id": "481597",
"Score": "2",
"body": "_with the row proceeding it_ - you probably mean \"preceding it\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T22:59:58.787",
"Id": "481598",
"Score": "0",
"body": "The opposite being \"succeeding it\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T10:12:45.693",
"Id": "481637",
"Score": "0",
"body": "Thanks. I'll have a crack at editing this to be a bit more focused on what I'm asking. I've tried to zoom in on the history->changes code. This might still be too much of an arcane problem for this site, but we'll see."
}
] |
[
{
"body": "<h2>Externalize your DML</h2>\n<p>Given the length of the query written in <code>GetArticleChangesAsync</code>, I would expect that either</p>\n<ul>\n<li>it be moved to a stored procedure (common but IMO overkill); or</li>\n<li>moved to a view (my usual preference given read-only queries like this).</li>\n</ul>\n<p>There are several reasons for this, including:</p>\n<ul>\n<li>If you have a DBA, they will have more control over the fine-grained details of the query</li>\n<li>The query is by its nature more closely coupled to the database design than the application design</li>\n<li>It will be often easier to update a view than rebuild and redeploy the entire application</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T10:39:44.850",
"Id": "481639",
"Score": "0",
"body": "Thanks +1. Interesting answer. Made me think. Probably not for me though.\n\nI think reasons 1 and 3 are good points, but more suitable for environments where time-to-deploy is slow or deployment downtime is a problem. I'm not comfortable with letting SQL changes, even efficiency ones, happen without tests running. I also have a fully reproducible environment. So, I'd need to write migrations for DB changes, which are a hassle compared to changing a method. And I'd need to worry about versioning and compatibility between old and new running instances as they swap over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T16:32:12.790",
"Id": "481659",
"Score": "1",
"body": "It's fair, but it sounds like you have a different problem: DB migrations should not be a hassle, and if they are you need to revisit your migration procedure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T02:20:53.280",
"Id": "245256",
"ParentId": "245120",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T08:26:36.027",
"Id": "245120",
"Score": "2",
"Tags": [
"sql",
"postgresql"
],
"Title": "Selecting changes from a temporal table"
}
|
245120
|
<p>I came across this question in a coding competition (Java-restricted) and I got a time-length-exceeded. I am unable to provide a link as the contest is closed now. Can I know how can I optimise this?</p>
<blockquote>
<p><strong>Unique Subsequences:</strong> You are given a randomly generated string of characters ranging from a to z. You are required to determine the
number of unique subsequences that can be formed equal to this string
'abcdefghijklmnopqrstuvwxyz'.</p>
<p>Input Format :</p>
<ul>
<li>The first line will contain t denoting the number of test cases</li>
<li>The first line of each test case contains n denoting the size of the string</li>
<li>The second line of each test case contains string s of size n</li>
</ul>
<p>We are supposed to print the count of unique subsequences that are
possible in a-z format</p>
<p>Constraints:</p>
<p><span class="math-container">$$1 \le t \le 10$$</span></p>
<p><span class="math-container">$$1 \le n \le 100000$$</span></p>
<p><span class="math-container">$$1 \le |S| \le 100000$$</span></p>
<p>For Example :</p>
<p>abcdefghijklmnopqrstuvwxyzz = 2</p>
<p>abz = 0 (Doesn't have all the characters from a-z)</p>
<p>abcdefghijklmnopqrstuvwxyyzz = 4</p>
</blockquote>
<pre><code>import java.util.*;
import java.io.*;
class TestClass {
public static boolean check_String(String str) {
boolean flag = str.replaceAll("[^a-z]", "")
.replaceAll("(.)(?=.*\\1)", "")
.length() == 26;
if(flag) {
return true;
}
return false;
}
public static void main(String args[] ) throws Exception {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(buffer.readLine());
for(int itr = 0; itr < testcases; itr++) {
long ans = 1;
int str_len = Integer.parseInt(buffer.readLine());
StringBuilder strbd = new StringBuilder();
strbd.append(buffer.readLine());
strbd.toString();
if(str_len >= 26) {
if(check_String(strbd.toString())) {
HashMap<Character,Integer> hashmap = new HashMap<>();
for(int itr2 = 0; itr2 < str_len; itr2++) {
if(hashmap.containsKey(strbd.charAt(itr2))) {
hashmap.put(strbd.charAt(itr2),hashmap.get(strbd.charAt(itr2))+1);
} else {
hashmap.put(strbd.charAt(itr2),1);
}
}
for(int itr3 : hashmap.values()) {
ans = (ans * itr3)%1000000007;
}
}
} else {
ans = 0;
}
System.out.println(ans);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T15:14:46.080",
"Id": "481368",
"Score": "2",
"body": "I consider this on-topic: we commonly cover programming challenge time-length-exceeded issues."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:46:07.190",
"Id": "481389",
"Score": "1",
"body": "[Crossposted](https://stackoverflow.com/questions/62770501/optimised-approach-for-subsequences-in-java). That said, the approach doesn't look correct at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T06:10:03.740",
"Id": "481431",
"Score": "1",
"body": "If the approach doesn't look correct at all, Can I know the correct approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T20:02:37.910",
"Id": "511300",
"Score": "0",
"body": "Cross-posted: https://codereview.stackexchange.com/q/245124/65105, https://stackoverflow.com/q/62770501/781723. Please [do not post the same question on multiple sites](https://meta.stackexchange.com/q/64068)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T10:55:23.403",
"Id": "245124",
"Score": "3",
"Tags": [
"java",
"performance",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Count unique subsequences"
}
|
245124
|
<p>I have been working on this code to meet the best OOP standards for production. The code is working but I wish to make this a more efficient code. Could someone help me out here to make this efficient using best practices of ruby.</p>
<pre><code>class Item
@@items = {}
def initialize(name, price)
@@items[name] = price
end
def self.all
@@items
end
end
class SaleItem
@@sale_items = {}
def initialize(name, units, price)
@@sale_items[name] = { 'units' => units, 'price' => price }
end
def self.all
@@sale_items
end
end
class PriceCalculator
def initiate_billing
input = get_input.split(',').map(&:strip)
@purchased_items = input
if @purchased_items.any?
quantity = count_items
price = calculate_bill(quantity)
display_bill(price, quantity)
else
puts "First add items to generate bill"
end
end
private
def get_input
puts "Please enter all the items purchased separated by a comma"
response = gets.chomp
end
def count_items
@purchased_items.inject(Hash.new(0)) do |quantity, item|
quantity[item] += 1
quantity
end
end
def calculate_bill(quantity)
quantity.map do |item,value|
items = Item.all[item]
sale_items = SaleItem.all[item]
value = if sale_items.nil?
quantity[item] * items
else
(((quantity[item]/sale_items['units'])) * sale_items['price']) + ((quantity[item] % sale_items['units']) * items)
end
[item, value]
end.to_h
end
def display_bill(price, quantity)
billing_items = quantity.each_with_object(price) do |(key,value), billing_items|
billing_items[key] = {'units' => value, 'price' => price[key]}
end
total_price = billing_items.inject(0) do |total, (item,value)|
total + value['price']
end
actual_price = quantity.inject(0) do |total, (item,units)|
total + (units * Item.all[item])
end
puts "Item Quantity Price"
puts "--------------------------------------"
billing_items.each do |item, value|
puts "#{item.ljust(10)} #{value['units']} $#{value['price'].round(3)}"
end
puts "Total price : $#{total_price.round(3)}"
puts "You saved $#{(actual_price - total_price).round(3)} today."
end
end
begin
Item.new('milk', 3.97)
Item.new('bread', 2.17)
Item.new('banana', 0.99)
Item.new('apple', 0.89)
SaleItem.new('milk',2,5.00)
SaleItem.new('bread',3,6.00)
price_calculator = PriceCalculator.new
puts price_calculator.initiate_billing
end
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>I have been working on this code to meet the best OOP standards for production.</p>\n</blockquote>\n<p>I think your biggest problem here is that <code>PriceCalculator</code> does too many things:</p>\n<ol>\n<li>Getting user input</li>\n<li>Calculating the price per checkout item</li>\n<li>Calculating the total price</li>\n<li>Printing the bill</li>\n</ol>\n<p>Let's try to split this up a bit first by introducing a <code>BillRow</code> for each line in your Bill to which we delegate to calculate the price per row .</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class Bill\n def initialize(purchased_items:)\n @purchased_items = purchased_items\n end\n\n def total\n rows.inject(0) { |sum, x| sum + x.total }\n end\n\n def discounted_total\n rows.inject(0) { |sum, x| sum + x.discounted_total }\n end\n\n def rows\n @rows ||= fetch_rows\n end\n\n private\n \n attr_reader :purchased_items\n\n def fetch_rows\n count_items.map do |item, quantity|\n BillRow.new(name: name, quantity: quantity)\n end\n end\n\n def count_items\n purchased_items.inject(Hash.new(0)) do |quantity, item|\n quantity[item] += 1\n quantity\n end\n end\nend\n\nclass BillRow\n attr_reader :name, :quantity\n\n def initialize(name:, quantity:)\n @name = name\n @quantity = quantity\n end\n\n def total\n @_total ||= quantity * item_price\n end\n\n def discounted_total\n @_discounted_total ||= calculate_discounted_total || total\n end\n\n private\n\n def calculate_discounted_total\n return unless sale_item\n \n ((quantity / sale_item['units'])) * sale_item['price']) + ((quantity % sale_item['units']) * item_price)\n end\n\n def sale_item\n @_sale_item ||= SaleItem.all[name]\n end\n\n def item_price\n Item.all[name]\n end\nend\n\nBill.new(['milk', 'milk', 'bread'])\n</code></pre>\n<p>Additionally we will extract the display method to it's own class.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class BillPrinter\n def initialize(bill:)\n @bill = bill\n end\n\n def print\n print_header\n print_rows\n print_total\n end\n\n private\n\n def print_header\n puts "Item Quantity Price"\n puts "--------------------------------------"\n end\n\n def print_rows\n bill.rows.each do |row|\n puts "#{row.item_name.ljust(10)} #{row.quantity} $#{row.total.round(3)}"\n end\n end\n\n def print_total\n puts "Total price : $#{bill.total.round(3)}"\n puts "You saved $#{(bill.total - bill.discounted).round(3)} today."\n end\nend\n\nbill = Bill.new(['milk', 'milk', 'bread'])\nBillPrinter.new(bill: bill).print\n</code></pre>\n<p>I will skip getting the user input as this is can basically go to the main method.</p>\n<p>Splitting the <code>PriceCalculator</code> into three classes has several advantages.</p>\n<ol>\n<li>Easier to test: We can pass in data instead of user input</li>\n<li>Classes are smaller and have only one responsibility</li>\n<li>Easier to extend and maintain e.g. if we want to use it on a website instead the console we need to refactor the code (user input read from StdIn and bill printed to StdOut). Now we can just implement a <code>HtmlBillPrinter</code> for instance.</li>\n<li>We can easier memoize data (efficiency)</li>\n</ol>\n<blockquote>\n<p>The code is working but I wish to make this a more efficient code</p>\n</blockquote>\n<p>In terms of efficiency, the biggest issue is that you calculate some values several times and look it up several times. This might be fine and the most important rule when making something more efficient is to first identify the bottleneck before jumping into optimize it. Readable code is usually preferred over complicated but efficient code.</p>\n<p>To sum it up, I think the biggest improvements can be made in a better object oriented approach which allows you to more aggressively memoize values (<a href=\"https://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/\" rel=\"nofollow noreferrer\">https://www.justinweiss.com/articles/4-simple-memoization-patterns-in-ruby-and-one-gem/</a>) as well as working with objects instead of e.g. arrays and hashes (<code>BillRow</code> vs <code>[quantity, value]</code>) which allows you to split out more readable methods too.</p>\n<h2>Edit:</h2>\n<p>As you mention 'production' I also just want to mention that you should NEVER use float for monetary values because they're not accurate (<a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency</a>). You should use integer and represent the price e.g. in cents. Even better would be to use a money gem (<a href=\"https://github.com/RubyMoney/money\" rel=\"nofollow noreferrer\">https://github.com/RubyMoney/money</a>).</p>\n<p>Another improvement would be to use objects in your <code>SalesItem</code> and <code>Item</code> classes.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class SaleItem\n @@sale_items = {}\n\n attr_reader :name, :units, :price\n \n def initialize(name:, units:, price:)\n @name = name\n @units = units\n @price = price\n end\n\n def initialize(name, units, price)\n @@sale_items[name] = new(name: name, units: units, price: price)\n end\n\n def self.all\n @@sale_items\n end\nend\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T04:53:12.890",
"Id": "481622",
"Score": "0",
"body": "+1 for the float/currency issue. No idea about that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-12T08:17:47.210",
"Id": "481812",
"Score": "0",
"body": "I don't wish to use class variables. How may I implement this with instance variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-12T12:39:43.303",
"Id": "481832",
"Score": "0",
"body": "Why do you not want to use class variables? You only use them to store the sales items and items which makes perfectly sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T20:52:32.667",
"Id": "245158",
"ParentId": "245126",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245158",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T11:23:38.380",
"Id": "245126",
"Score": "1",
"Tags": [
"beginner",
"classes"
],
"Title": "Ruby calculator for a grocery store"
}
|
245126
|
<p>I came across this question in a coding contest (Java-restricted) and I got TLE. I am unable to provide the link of the question as the contest is closed now. Can I know how can I optimise this?</p>
<blockquote>
<p>Four Functions</p>
<p>Given four functions</p>
<ul>
<li>A(x) = Number of i where 1 <= i <= x and gcd(i,x) = 1</li>
<li>B(x) = Sum of A(d) where d divides the number x</li>
<li>C(x) = Sum of exponents of each prime in the prime factorization of B(x)</li>
<li>D(x) = Sum of C(i) where 1 <= i <= x</li>
</ul>
<p>If <span class="math-container">$$B(x) = {p_1} ^ {a1} {p_2} ^ {a2} {p_3} ^ {a3}$$</span>
where p1,p2,p3 are prime factors of B(x), then C(x) is a1 + a2</p>
<p>Find the value of D(N) Constraints:</p>
<p><span class="math-container">$$1 \le testcases \le 1000000$$</span></p>
<p><span class="math-container">$$1 \le N \le 1000000$$</span></p>
<p>Example :</p>
<p>Input :</p>
<p>1</p>
<p>4</p>
<p>Output :</p>
<p>4</p>
<p>For n = 4</p>
<p><span class="math-container">$$C(1) = 0$$</span></p>
<p><span class="math-container">$$C(2) = 1$$</span></p>
<p><span class="math-container">$$C(3) = 1$$</span></p>
<p><span class="math-container">$$C(4) = 2$$</span></p>
<p><span class="math-container">$$D(4) = C(1) + C(2) + C(3) + C(4) = 4$$</span></p>
</blockquote>
<p>This is my approach</p>
<pre><code>public class Main {
static long commonDivisor(long num1,long num2) {
if(num1 == 0) {
return num2;
}
return commonDivisor(num2 % num1, num1);
}
static long funcA(long numb) {
long answer = numb;
for (long itr = 2; itr * itr <= numb; itr++) {
if(numb % itr == 0) {
while(numb % itr == 0) {
numb /= itr;
}
answer -= answer / itr;
}
}
if(numb > 1) {
answer -= answer / numb;
}
return answer;
}
static long funcB(long numb) {
long sum = 0;
for (long itr = 1; itr <= Math.sqrt(numb); itr++){
if (numb % itr == 0){
if(numb/itr == itr){
sum = sum + funcA(itr);
} else {
sum = sum + funcA(itr) + funcA(numb/itr);
}
}
}
return sum;
}
static boolean check_prime(long numb) {
BigInteger bigint = new BigInteger(String.valueOf(numb));
return bigint.isProbablePrime(1);
}
static long funcC(long numb) {
if (numb <= 1) {
return 0;
}
long remNum = numb;
long expo = 0;
for (long itr = 2; itr <= Math.sqrt(numb); itr++) {
if(check_prime(itr)) {
while (remNum % itr == 0) {
expo++;
remNum /= itr;
}
}
}
if(check_prime(remNum)) {
if (remNum > 1) {
expo++;
}
}
return expo;
}
static long funcD(long numb) {
long result = 0;
for(long itr = 1; itr <= numb; itr++){
result += funcC(funcB(itr));
}
return result;
}
public static void main(String[] args) {
try {
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
long testCases = Long.parseLong(buffer.readLine());
for(long itr = 1; itr <= testCases; itr++) {
long number = Long.parseLong(buffer.readLine());
System.out.println(funcD(number));
}
} catch(Exception e) {
System.out.println("Error");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-08T20:01:33.970",
"Id": "511299",
"Score": "0",
"body": "Cross-posted: https://codereview.stackexchange.com/q/245127/65105, https://stackoverflow.com/q/62777612/781723. Please [do not post the same question on multiple sites](https://meta.stackexchange.com/q/64068)."
}
] |
[
{
"body": "<p>For a coding contest, the answer is almost never to implement the problem the same way as it is given.</p>\n<p>For example here, functions A and B are actually intentionally misleading. Function A is also known as Euler's Totient, and function B computes the sum of totients of divisors which <a href=\"https://proofwiki.org/wiki/Sum_of_Euler_Phi_Function_over_Divisors\" rel=\"nofollow noreferrer\">is the same as the original number</a>. Detailed review of them is therefore a waste, functions A and B don't need to be implemented at all.</p>\n<p>Function C can be improved by noting that the lowest divisor of a number is necessarily a prime, so calling <code>check_prime</code> is unnecessary. If <code>itr</code> was <code>a * b</code> then <code>a</code> and <code>b</code> would have been found first and divided out of <code>remNum</code> already, making <code>itr</code> not a divisor of <code>remNum</code>.\nThe square root is also unnecessary, and relatively expensive. It can be avoided by testing <code>itr * itr <= numb</code> instead. There is no risk of overflow given that <code>numb <= 1000000</code>. Further refinements are possible.</p>\n<p>Function D can be improved by caching the partial sums. In isolation that would not help, but there can be multiple test cases during a run of the program, and they can reuse the previously computed sums. For example as an extreme case, after the test case <code>1000000</code> has been used, any further test cases could be essentially free, because all possible cases would have been calculated at that point. Also, after <code>funcD(10)</code> has been evaluated, <code>funcD(20)</code> could start with that result instead of starting over from scratch.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-09T13:35:39.670",
"Id": "511387",
"Score": "1",
"body": "Just an addendum to the last part. The function $D$ can also be simplified. The function $C$ satisfies the logarithmic property $C(a)+C(b)=C(ab)$. Therefore $D(n)=C(n!)$. Now, $C(n!)$ can be computed using [Legendre's formula](https://en.wikipedia.org/wiki/Legendre%27s_formula) by computing the primes up to $n$ and applying the formula to compute their exponents (or valuations) in the factorization of $n!$."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T13:25:12.850",
"Id": "245129",
"ParentId": "245127",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "245129",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T12:13:24.193",
"Id": "245127",
"Score": "3",
"Tags": [
"java",
"performance",
"time-limit-exceeded"
],
"Title": "Prime factorisation in java"
}
|
245127
|
<p>Hello fellow programmers. I started learning C last week and today I wanted to see if I can make a working program, so I made this game:</p>
<pre><code>/*
* TESTED IN LINUX - 2020
*/
#include <stdio.h>
#include <stdlib.h>
int player = 1, choice;
int places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
void switchPlayers();
void displayBoard();
int markBoard(char mark);
int checkForWin();
int main() {
while (!checkForWin()){
system("clear");
displayBoard();
switchPlayers();
}
system("clear");
displayBoard();
checkForWin();
return 0;
}
void switchPlayers(){
if (player == 1) {
printf(" Player 1 choose: ");
scanf("%d", &choice);
if (markBoard('X'))
player = 1;
else
player = 2;
}
else if (player == 2){
printf(" Player 2 choose: ");
scanf("%d", &choice);
if (markBoard('O'))
player = 2;
else
player = 1;
}
}
void displayBoard(){
printf("\n X & O \n Player 1 (X) - Player 2 (O)\n\n");
printf("\t | | \n"
"\t %c | %c | %c \n"
"\t ___|___|___\n"
"\t | | \n"
"\t %c | %c | %c \n"
"\t ___|___|___\n"
"\t | | \n"
"\t %c | %c | %c \n"
"\t | | \n\n"
, places[1], places[2],
places[3], places[4], places[5],
places[6], places[7], places[8], places[9]);
}
int markBoard(char mark){
for (int i = 1; i < 10; ++i) {
if (choice == i && places[i]-48 == i) {
places[i] = mark;
return 0;
}
}
return 1;
}
int checkForWin() {
short draw = 0;
//Horizontal check
for (int i = 1; i < 10; i += 3) {
if (places[i] == places[i + 1] && places[i + 1] == places[i + 2]) {
printf("\tYou won!\n");
return 1;
}
}
//Vertical check
for (int i = 1; i < 4; i += 1) {
if (places[i] == places[i + 3] && places[i + 3] == places[i + 6]) {
printf("\tYou won!\n");
return 1;
}
}
//Diagonal check
if (places[1] == places[5] && places[5] == places[9]) {
printf("\tYou won!\n");
return 1;
} else if (places[3] == places[5] && places[5] == places[7]) {
printf("\tYou won!\n");
return 1;
}
//Check for draw
for (int j = 1; j < 10; ++j) {
if (places[j] - 48 != j)
draw++;
}
if (draw == 9){
printf("\t Draw!\n");
return 1;
}
return 0;
}
</code></pre>
<p>Do you have any tips on how I could make it more efficient or fix something I did wrong?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T14:09:19.550",
"Id": "481354",
"Score": "2",
"body": "Great first question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T19:03:35.160",
"Id": "481393",
"Score": "10",
"body": "kudos on the `main()` method. Very good high-level abstraction of the *entire* program. The implication of more well structured code to come raises the spirits of the most curmudgeon of maintenance programmers, 'a-hemm'. This is all too rare. Keep up the good work! `check...` is a poor method name prefix. \"Check\" is meaningless in any context. Here it could be a double negative for all I know, i.e. \"there is not no winner.\" The point - I'm *forced* to read details to make sure - damn, abstraction blown. `weHaveAWinner()` - wordy is better than ambiguity imho."
}
] |
[
{
"body": "<h2>One-based indexing</h2>\n<p>Based on this:</p>\n<pre><code>int places[10] = {'o', '1', '2', ...\n\n"\\n\\n"\n, places[1], places[2], ...\n</code></pre>\n<p>it seems that you're trying to push a square peg (one-based indexing) through a round hole (zero-based indexing). Try to use zero-based indexing instead.</p>\n<h2>Assuming ASCII</h2>\n<p>This:</p>\n<pre><code>places[i]-48\n</code></pre>\n<p>assumes that you're using ASCII for the compiler character literal encoding. That is often a correct assumption, but not necessarily a safe one. Since you have tested this on Linux it is likely that you are using gcc, so you should read about the <code>f*charset</code> options, and <a href=\"https://stackoverflow.com/questions/12216946/gcc-4-7-source-character-encoding-and-execution-character-encoding-for-string-li\">this question</a>.</p>\n<p>Aside from explicitly setting ASCII as the encoding, you should replace the above 48 with <code>'0'</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:45:13.497",
"Id": "245152",
"ParentId": "245132",
"Score": "7"
}
},
{
"body": "<p>On the whole this is nicely done for an application made during your first week of C programming. The functions are generally reasonably-sized, the code is comprehensible and the design decisions are understandable given the size and purpose of the application.</p>\n<p>My remarks mostly center around improving the design to support new features and avoid bugs. The merit of many of my points may be negligible if you're never planning on adding to the application beyond what you have, but if you'd like to add (for example) even fairly unassuming improvements like an AI opponent or arbitrary board sizes, the current design would be pushed beyond its narrow limits.</p>\n<h3>Avoid globals</h3>\n<p>Your core state variables</p>\n<pre><code>int player = 1, choice;\nint places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n</code></pre>\n<p>should all be scoped to <code>main</code> at minimum. The problem with the existing design is that all functions operating on these <a href=\"https://en.wikipedia.org/wiki/Global_variable\" rel=\"nofollow noreferrer\">global variables</a> are <a href=\"https://en.wikipedia.org/wiki/Idempotence#Computer_science_meaning\" rel=\"nofollow noreferrer\">non-idempotent</a>. This means they are <a href=\"https://en.wikipedia.org/wiki/Reentrant_(subroutine)\" rel=\"nofollow noreferrer\">unsafe in a multithreaded environment</a> and modify <a href=\"https://en.wikipedia.org/wiki/State_(computer_science)#Program_state\" rel=\"nofollow noreferrer\">state</a> outside of themselves which makes the application difficult to reason about and may lead to bugs.</p>\n<p>The parameterless functions in your original code creates an illusion of simplicity. But in reality these functions are quite unsafe and would inhibit a larger application significantly.</p>\n<h3>Encapsulate related data</h3>\n<pre><code>int player = 1, choice;\nint places[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};\n</code></pre>\n<p>Are loose variables that are conceptually attributes of the same entity and as such should be grouped in a <code>TicTacToePosition</code> structure along with a set of functions that operate on this structure. This makes it easier to understand the purpose and relationship between these pieces of data. Taken out of context, a variable name like <code>places</code> has non-obvious purpose, but as a struct member, <code>position.places</code> or <code>ttt_state.squares</code> is a bit clearer.</p>\n<h3>Separate UI from game logic</h3>\n<p>If you want to generalize and expand on your code, you'll need to detach user interaction from game logic. Doing so makes the code maintainable and expandable through <a href=\"https://en.wikipedia.org/wiki/Loose_coupling\" rel=\"nofollow noreferrer\">looser coupling</a>.</p>\n<p>There are many subtle manifestations of the strong UI-game logic coupling throughout the app, like:</p>\n<pre><code>int markBoard(char mark){\n for (int i = 1; i < 10; ++i) {\n // ^\n if (choice == i && places[i]-48 == i) {\n // ^^^\n places[i] = mark;\n return 0;\n }\n }\n return 1;\n}\n</code></pre>\n<p>In the above code, the 1-indexing seems to be a convenience measure to avoid having to normalize 1-indexed user input to internal logic. But this convenience leads to an awkward board design for the programmer and a confusing <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic</a> <code>'o'</code> character at the 0-th index.</p>\n<p>Additionally, <code>-48</code> is a conversion between external UI and internal game logic that <code>markBoard</code> <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">shouldn't be responsible for</a>. The correct name for this function is <code>convertFromUserInputCharAndMarkBoard</code>, which is overburdened. Normalize/sanitize user input outside of the tic tac toe board logic. This lets you keep the interface user-centric while supporting an intuitive internal representation for the programmer.</p>\n<p><code>switchPlayers</code> does more than switch players: it also takes user input. Those are two distinct things that should be separate.</p>\n<p><code>checkForWin</code> does win checking but also does IO, a <a href=\"https://en.wikipedia.org/wiki/Side_effect_(computer_science)\" rel=\"nofollow noreferrer\">side effect</a>. Better to just return the result and let the caller handle the IO. In fact, <code>checkForWin</code> is called twice in the main function, once to check for a win and the second time to display the winning player after clearing the screen.</p>\n<h3>UX</h3>\n<p>I recommend spelling out the input format more precisely and using <code>X wins!</code> or <code>O wins!</code> instead of <code>You won!</code>.</p>\n<p>Instead of <code>Player 1</code> and <code>Player 2</code>, using <code>X</code> and <code>O</code> throughout removes ambiguity and lets you avoid a layer of indirection by having to display/explain <code>Player 1 (X) - Player 2 (O)</code> which asks the user to mentally translate between multiple terms for the players.</p>\n<p>Bad input into <code>scanf</code> spams the console and there are no error messages or handling to speak of. <code>scanf</code> isn't the right tool here; use <a href=\"https://linux.die.net/man/3/fgets\" rel=\"nofollow noreferrer\"><code>fgets</code></a> to pull the line in as a string and parse the number out of it.</p>\n<p>I'm not really crazy about <code>system("clear")</code>. It feels invasive. If you're committed to this sort of interface, I'd go all in with <a href=\"https://en.wikipedia.org/wiki/Ncurses\" rel=\"nofollow noreferrer\">curses</a>. Or just keep it simple and keep printing without clearing.</p>\n<h3>Avoid convoluted logic</h3>\n<p>In <code>checkForWin</code>, the draw logic is somewhat hard to follow:</p>\n<pre><code>//Check for draw\nfor (int j = 1; j < 10; ++j) {\n if (places[j] - 48 != j)\n draw++;\n}\nif (draw == 9){\n printf("\\t Draw!\\n");\n return 1;\n}\n</code></pre>\n<p>Once again, the <code>-48</code> is an artifact of user input conversion that really doesn't belong in the game engine. Instead of a <code>player</code> variable and this manual draw check logic, most two-player board games use a single number, <a href=\"https://en.wikipedia.org/wiki/Ply_(game_theory)\" rel=\"nofollow noreferrer\">ply</a>, which counts the turn. A draw check then becomes <code>ply >= length of board</code> assuming <code>is_won</code> is called first, figuring out whose turn it is becomes <code>ply % 2</code> and switching sides is <code>ply++</code>.</p>\n<p>Ply can be used to avoid pointless win checks if not enough moves have been played. In tic tac toe, it seems like a minor optimization but it can speed up an AI that's running win checks thousands of times per turn, and it's a single extra line of code.</p>\n<h3>Consider breaking commented code out into functions</h3>\n<p>The <code>checkForWin</code> function has 4 distinct parts to it: checking horizontals, verticals, diagonals and draws. Each could be a separate function instead of delimiting the areas with comments. Otherwise, some of these loops could be merged and the logic simplified (it's debatable which is best).</p>\n<h3>Code style</h3>\n<ul>\n<li><p>Keep your braces consistent: <code>void switchPlayers(){</code> should be <code>void switchPlayers() {</code>.</p>\n</li>\n<li><p>Use <code>#include <stdbool.h></code>:</p>\n<pre><code> if (draw == 9){\n printf("\\t Draw!\\n");\n return 1;\n }\n</code></pre>\n<p>could then be</p>\n<pre><code> if (draw == 9){\n printf("\\t Draw!\\n");\n return true;\n }\n</code></pre>\n<p>which is easier for the programmer to understand.</p>\n</li>\n</ul>\n<h3>Possible rewrite</h3>\n<p>While I'd prefer to use a <a href=\"https://en.wikipedia.org/wiki/Bitboard\" rel=\"nofollow noreferrer\">bitboard</a> and bitmasks to check win patterns, I think it's most instructive to keep the array format to avoid too radical of a departure from your design.</p>\n<p>Feel free to accuse this code of being prematurely future-proof or anticipating adding AI and other features. Fair enough--it <em>is</em> more code. While I've gone somewhat deep into generalizing board sizes and so forth, you can cherry-pick the techniques that make sense for you and take the rest with a grain of salt.</p>\n<p>Future steps might be adding a <a href=\"https://www.libsdl.org/\" rel=\"nofollow noreferrer\">GUI</a>, generalizing the board sizes with <a href=\"https://en.wikipedia.org/wiki/C_dynamic_memory_allocation\" rel=\"nofollow noreferrer\"><code>malloc</code></a> or a <a href=\"https://en.wikipedia.org/wiki/Flexible_array_member\" rel=\"nofollow noreferrer\">FAM</a>, adding an <a href=\"https://en.wikipedia.org/wiki/Minimax\" rel=\"nofollow noreferrer\">AI</a>, adding a <a href=\"https://en.wikipedia.org/wiki/Tic-tac-toe_variants\" rel=\"nofollow noreferrer\">variant</a> or <a href=\"https://beej.us/guide/bgnet/\" rel=\"nofollow noreferrer\">network</a> play.</p>\n<pre><code>#include <stdbool.h>\n#include <stdint.h>\n#include <stdio.h>\n\nstruct TicTacToePosition {\n uint8_t ply;\n uint8_t board_len;\n uint8_t side_len;\n char board[3][3];\n};\n\nstruct TicTacToePosition ttt_init() {\n struct TicTacToePosition ttt_pos = {};\n ttt_pos.board_len = sizeof ttt_pos.board;\n ttt_pos.side_len = sizeof ttt_pos.board[0];\n return ttt_pos;\n}\n\nchar ttt_current_player(const struct TicTacToePosition *pos) {\n return pos->ply % 2 ? 'O' : 'X';\n}\n\nchar ttt_last_player(const struct TicTacToePosition *pos) {\n return pos->ply % 2 ? 'X' : 'O';\n}\n\nbool ttt_is_board_full(const struct TicTacToePosition *pos) {\n return pos->ply >= pos->board_len;\n}\n\nbool ttt_legal_move(const struct TicTacToePosition *pos, int row, int col) {\n return row >= 0 && row < pos->side_len && \n col >= 0 && col < pos->side_len && !pos->board[row][col];\n}\n\nbool ttt_try_move(struct TicTacToePosition *pos, int row, int col) {\n if (!ttt_legal_move(pos, row, col)) {\n return false;\n }\n\n pos->board[row][col] = ttt_current_player(pos);\n pos->ply++;\n return true;\n}\n\nbool ttt_line_win(const unsigned int len, const char *arr) {\n for (int i = 1; i < len; i++) {\n if (!arr[0] || !arr[i] || arr[0] != arr[i]) {\n return false;\n }\n }\n \n return true;\n}\n\nbool ttt_is_won(const struct TicTacToePosition *pos) {\n if (pos->ply < 5) return false;\n\n const uint8_t len = pos->side_len;\n char left_diag[len];\n char right_diag[len];\n\n for (int i = 0; i < len; i++) {\n char column[len];\n left_diag[i] = pos->board[i][i];\n right_diag[i] = pos->board[i][len-i-1];\n\n for (int j = 0; j < len; j++) {\n column[j] = pos->board[j][i];\n }\n\n if (ttt_line_win(len, pos->board[i]) || ttt_line_win(len, column)) {\n return true;\n }\n }\n\n return ttt_line_win(len, left_diag) || ttt_line_win(len, right_diag);\n}\n\nchar ttt_fmt_square(const struct TicTacToePosition *pos, int i, int j) {\n return pos->board[i][j] ? pos->board[i][j] : i * pos->side_len + j + '1';\n}\n\nvoid ttt_print_board(const struct TicTacToePosition *pos) {\n puts("");\n\n for (int i = 0; i < pos->side_len; i++) {\n for (int j = 0; j < pos->side_len - 1; j++) {\n printf(" |");\n }\n\n printf("\\n %c ", ttt_fmt_square(pos, i, 0));\n\n for (int j = 1; j < pos->side_len; j++) {\n printf("| %c ", ttt_fmt_square(pos, i, j));\n }\n\n if (i < pos->side_len - 1) {\n printf("\\n___");\n\n for (int j = 1; j < pos->side_len; j++) {\n printf("|___");\n }\n }\n\n puts("");\n }\n\n for (int i = 0; i < pos->side_len - 1; i++) {\n printf(" |");\n }\n\n puts("\\n");\n}\n\nint ttt_get_num(const char *failure_prompt) {\n for (;;) {\n int result;\n char buf[128];\n fgets(buf, sizeof buf, stdin);\n\n if (sscanf(buf, "%d", &result)) {\n return result;\n }\n \n printf("%s", failure_prompt);\n }\n}\n\nvoid ttt_get_move(struct TicTacToePosition *ttt_pos) {\n for (;;) {\n printf("Choose a square for %c's move: ", \n ttt_current_player(ttt_pos));\n int move = ttt_get_num("Invalid input. Try again: ") - 1;\n int row = move / ttt_pos->side_len;\n int col = move % ttt_pos->side_len;\n\n if (ttt_try_move(ttt_pos, row, col)) {\n break;\n }\n\n puts("Invalid move. Pick an empty square between 1 and 9.");\n }\n}\n\nvoid ttt_play_game() {\n for (struct TicTacToePosition ttt_pos = ttt_init();;) {\n ttt_print_board(&ttt_pos);\n ttt_get_move(&ttt_pos);\n\n if (ttt_is_won(&ttt_pos)) {\n ttt_print_board(&ttt_pos);\n printf("%c won!\\n", ttt_last_player(&ttt_pos));\n break;\n }\n else if (ttt_is_board_full(&ttt_pos)) {\n ttt_print_board(&ttt_pos);\n puts("The game is a draw");\n break;\n }\n }\n}\n\nint main() {\n ttt_play_game();\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T22:19:10.427",
"Id": "481405",
"Score": "0",
"body": "Curious, why `unsigned short ply, board_len, side_len` vs. `unsigned` or `unsigned char`. What advantage with `unsigned short`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T00:59:41.697",
"Id": "481412",
"Score": "0",
"body": "No advantage--it could be a `char` but I always think of `char` as being semantically tied to characters rather than numbers even though they're the same. I could change it if you think `char` is normal for digits since that's really the width I want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T07:49:34.050",
"Id": "481434",
"Score": "1",
"body": "So use `uint8_t` instead."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T20:15:25.250",
"Id": "245156",
"ParentId": "245132",
"Score": "15"
}
},
{
"body": "<p>In addition to what's already been said, here's some misc remarks about using obsolete style:</p>\n<ul>\n<li><p><code>void switchPlayers();</code> Functions with an empty parenthesis is obsolete style in C since over 20 years back. You should be writing <code>void switchPlayers(void);</code> instead, because in C the <code>()</code> means "accept any parameter", which is type unsafe and outdated style.</p>\n<p>(Note that C and C++ are different here - in C++ <code>()</code> and <code>(void)</code> are equivalent.)</p>\n</li>\n<li><p>Instead of using <code>int</code> with <code>1</code> or <code>0</code> for true/false, you should be using boolean types from <code>stdbool.h</code>: <code>bool</code>, <code>true</code> and <code>false</code>. The built-in C keyword <code>_Bool</code> type is also OK to use.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T14:36:15.667",
"Id": "481471",
"Score": "0",
"body": "Don't use `_Bool` directly. https://stackoverflow.com/a/4767954/313768"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T06:18:48.547",
"Id": "481516",
"Score": "0",
"body": "@Reinderien There's reasons to use `_Bool` directly, such as when writing code that must be portable to C++. stdbool.h might not be available and then you can `#define _Bool bool` in the C++ build etc. Some manner of pre-processor tricks are unavoidable no matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T11:00:09.580",
"Id": "481540",
"Score": "0",
"body": "In that situation it's equally possible to wrap the inclusion of stdbool in an `#if`, which I would consider preferable."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T07:56:17.917",
"Id": "245170",
"ParentId": "245132",
"Score": "2"
}
},
{
"body": "<p>As both players are handled the same:</p>\n<pre><code>// TODO: define marker = char array {' ', 'X', 'O'}\n\nvoid switchPlayers(){\n printf(" Player %d choose: ", player);\n scanf("%d", &choice);\n // I inverted logic of the if!\n if (!markBoard(marker[player])) {\n player = 3 - player;\n }\n // ... the else can be dropped as player did not change and does not need to be changed\n}\n</code></pre>\n<p>(Not a great improvement. In case of more players this would be wise.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T17:29:29.243",
"Id": "245197",
"ParentId": "245132",
"Score": "3"
}
},
{
"body": "<p>When I run the game, it allows me to select a side. I selected 'x'. Then the display changed to add the 'o' side, then the display commenced to flash with no (discernible) way for me/computer to make a move.</p>\n<p>suggest the <code>system( "clear" );</code> only be called after a side inputs a move.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T22:41:50.257",
"Id": "245247",
"ParentId": "245132",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "245156",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T13:46:32.023",
"Id": "245132",
"Score": "11",
"Tags": [
"c",
"tic-tac-toe"
],
"Title": "Simple Tic Tac Toe game inside terminal"
}
|
245132
|
<p>folks.
I have recently started writing software using Modern C++ 11-14. I have been developing software for more than a decade and just wanted to broaden my skillset. I am practicing building some simple design components using Modern C++. I dont have any friend or a colleague who knows c++ and noone can review my practice problems. I would be very grateful if you can review a couple of my code snippets and provide your feedback. Thank you.</p>
<p>Below is my recent implementation of the <strong>Reactor</strong>. Please criticize :)
At the core of the reactor lies a thread called <strong>main_thread</strong>. Reactor will be receiving messages of type <strong>struct Message</strong> which is defined in Message.hpp file.</p>
<p>Messages will be delivered using <strong>virtual method WaitForMessage</strong>.</p>
<p>Users should be able to register their concrete event handlers which are derived from the base class <strong>IEventHandler</strong>. Reactor will call <strong>OnMessage</strong> of the handler if the received message type matches the type that <strong>IEventHandler</strong> was registered to.</p>
<p>Inside <strong>AbstractReactor</strong> the handlers will be wrapped in a class named <strong>MessageListener</strong> and AbstractReactor will keep MessageListeners inside the vector. Would a map be a better choice?.
I decided to use vector therefore MessageListeners can be sorted by the type of the message that they are looking for and we will be able to use binary search(this is what <strong>std::lower_bound</strong> is used for) rather than looping.</p>
<p>One of the requirements was.
A user should be able to call <strong>registerHandler and unregisterHandler</strong> from within the OnMessage routine of a concrete handler. I am using push_back on every handler which is registered while I am running in the context of main_thread and sort it after the message has been processed. When registerHandler is called outside the main_thread context it will search the appropriate position in the vector where the handler should be inserted and will insert it at that position. If deregisterHandler is called while we are at the main_thread context the listener will not be removed from the vector immediately. Flag m_handlersBeenUnregistered will be set and only after the message is processed we will check which of the
listeners have to be removed and will call erase method.</p>
<p>Thank you</p>
<p>File AbstractReactor.cpp</p>
<pre><code>#include <mutex>
#include <algorithm>
#include "AbstractReactor.hpp"
#include "IEventHandler.hpp"
int MessageListener::m_IdCount = 0;
AbstractReactor::AbstractReactor()
{}
AbstractReactor::~AbstractReactor()
{
if (!m_stopThread)
stopThread();
}
void AbstractReactor::mainThread()
{
while(!m_stopThread)
{
/* Block until message gets available
* mainThread now owns a message */
std::unique_ptr<Message> m_ptr = waitForMessage();
if (m_ptr.get() == nullptr)
{
/* Reactor process may have received a signal to abort */
/* TODO: this may be reported calling some error handler */
continue;
}
/* Lock the list of listeners, I am using recursive mutex, because
* we may call registerHandler and unregisterHandler functions while invoking a handler function of the listener */
std::unique_lock<std::recursive_mutex> lock;
/* All handler entries are sorted by message type handlers are looking for
* find the position of the first message listener whose type matches the type of the message. We may have multiple message listeners registered
* for the same message type */
m_searchValue.m_type = m_ptr->type;
m_searchValue.m_handleId = -1;
auto pos = std::lower_bound(m_listeners.begin(), m_listeners.end(), m_searchValue, [](const MessageListener& one, const MessageListener& two)
{
if (one.m_type < two.m_type)
return true;
else
return false;
}
);
if (pos == m_listeners.end())
{
/* We couldnt find any message listener which was registered for this message type
* we will keep listenning for new events
* We may add some statistics for future references */
continue;
}
/* Set the flag that we are processing a message
* When this flag is set registerHandler will not try to insert a handler to the proper position, rather it will push_back a handler to the end of the vector.
* All newly registered handlers will be at the end of the list
* When reactor finishes calling handlers he will sort its handlers table again.*/
m_processing = true;
auto size = m_listeners.size();
auto i = pos - m_listeners.begin();
while(i < static_cast<int>(size) && m_listeners[i].m_type == m_ptr->type){
/* Handlers are user-defined.
* If listener fails it shouldn't affect our Reactor */
try
{
m_listeners[i].m_hptr->OnMessage(m_ptr.get());
}
catch(...)
{
/* We may need to report an exception.
* Reactor should not have any error handling but it will need to somehow to log this error */
}
i++;
}
m_processing = false;
if (m_listeners.size() > size)
{
/* If the list has grown while we were invoking handlers, we will need to sort it again and place new handlers
* at appropriate positions in the vector according to the message type */
std::sort(m_listeners.begin(), m_listeners.end(), [](const MessageListener& first, const MessageListener& second){
if (first.m_type <= second.m_type)
return true;
else
return false;
});
}
/* If there there was at least one unregisterHandler call while we were processing a message
* we will need to go through the whole table and remove the ones which have to be unregistered */
if (m_handlersBeenUnregistered == true)
{
for (auto it = m_listeners.begin(); it != m_listeners.end(); ++it)
{
if (it->m_mustRemove)
it = m_listeners.erase(it);
}
m_handlersBeenUnregistered = false;
}
}
}
int AbstractReactor::unregisterHandler(int handleId, int32_t type)
{
if (handleId < 0)
return -1;
std::unique_lock<std::recursive_mutex> lock;
m_searchValue.m_type = type;
m_searchValue.m_handleId = handleId;
auto pos = std::lower_bound(m_listeners.begin(), m_listeners.end(), m_searchValue, [](const MessageListener& theirs, const MessageListener& my)
{
if (theirs.m_type < my.m_type )
return true;
else
return false;
}
);
if (pos == m_listeners.end())
{
/* If we were unable to find a match for this handler in the listeners table
* we will return negative status to the user */
return -1;
}
auto i = pos - m_listeners.begin();
while(i < static_cast<int>(m_listeners.size()) && m_listeners[i].m_type == type)
{
if (m_listeners[i].m_handleId == handleId)
{
if (m_processing == false)
m_listeners.erase(m_listeners.begin() + i);
else
m_listeners[i].m_mustRemove = true;
break;
}
i++;
}
/* Set a global flag that will indicate that a handler has been marked to be deleted */
if (m_processing == true)
m_handlersBeenUnregistered = true;
return 0;
}
void AbstractReactor::start()
{
m_thread = std::thread(&AbstractReactor::mainThread, this);
}
void AbstractReactor::stopThread()
{
m_stopThread = true;
m_thread.join();
}
void AbstractReactor::stop()
{
/* we will just stop processing messages, but we will not delete
* all message listeners
* Message listeners entries will be deleted on destruction */
stopThread();
}
</code></pre>
<p>File AbstractReactor.hpp</p>
<pre><code>#pragma once
#include <vector>
#include <mutex>
#include <thread>
#include <memory>
#include <algorithm>
#include "IEventHandler.hpp"
#include "Message.hpp"
struct MessageListener
{
int32_t m_type{-1};
int m_handleId{-1};
bool m_mustRemove{false};
static int m_IdCount;
std::unique_ptr<IEventHandler> m_hptr;
public:
MessageListener() = default;
MessageListener(int32_t type, std::unique_ptr<IEventHandler> h):
m_type(type),
m_handleId(m_IdCount++),
m_hptr(std::move(h))
{}
MessageListener(int32_t type, int handleId):
m_type(type),
m_handleId(handleId)
{}
};
class AbstractReactor
{
public:
AbstractReactor();
virtual ~AbstractReactor();
/* This is an virtual function which must be implemented in the concrete reactor which you
* derive from the AbstractReactor class. This function will be the source of the messages
* to the reactor.
* It will block until an OS informs us that an event occurred and message is available
* Concrete implementation of Abstract reactor must override it */
virtual std::unique_ptr<Message> waitForMessage() = 0;
void start();
void stop();
/* Register handler is a templated function which will require
* message type and parameters used for constructing concrete user handler derived from IEventHandler
* */
template<typename HandlerType, typename ...HandlerParametersType>
int registerHandler(int type, HandlerParametersType&&... handlerParams)
{
std::unique_lock<std::recursive_mutex> lock;
auto pos = m_listeners.end();
if (m_processing == false)
{
/* Add message listeners in sorted order sorting by their message type,
* so we will be able to use binary search when trying to find listener registered for a specific message type
* Not sure how many message types there are. If the number if huge then simply iterating over the list of big length
* with not be an ideal solution */
m_searchValue.m_type = type;
m_searchValue.m_handleId = -1;
pos = std::lower_bound(m_listeners.begin(), m_listeners.end(), m_searchValue, [](const MessageListener& theirs, const MessageListener& my)
{
if (theirs.m_type < my.m_type)
return true;
else
return false;
}
);
}
pos = m_listeners.emplace(pos, type, std::move(std::make_unique<HandlerType>(std::forward<HandlerParametersType>(handlerParams)...)));
if (m_processing == false)
return pos->m_handleId;
else
return m_listeners.back().m_handleId;
}
int unregisterHandler(int handleId, int32_t type);
private:
std::recursive_mutex m_mutex;
std::vector<MessageListener> m_listeners;
std::thread m_thread;
MessageListener m_searchValue;
bool m_stopThread{false};
bool m_processing{false};
bool m_handlersBeenUnregistered{false};
void stopThread();
void mainThread();
};
</code></pre>
<p>File IEventHandler.hpp</p>
<pre><code>#pragma once
#include "Message.hpp"
class IEventHandler
{
public:
virtual ~IEventHandler() {};
virtual void OnMessage(const Message *msg) = 0;
};
</code></pre>
<p>File Message.hpp</p>
<pre><code>#pragma once
#include <cstdint>
struct Message
{
int32_t type;
char data[32];
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T14:07:55.910",
"Id": "481352",
"Score": "0",
"body": "Does all of that currently work as intended or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:38:02.447",
"Id": "481388",
"Score": "0",
"body": "What is this a reactor \"for\"? Is it intended to service web requests? Game events? Something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T01:12:24.023",
"Id": "481413",
"Score": "0",
"body": "Reactor was working I tested it using socket. WaitForMessage function was listenning on a linux domain socket and I had another process sending messages to that socket with random message types. I can write code which is working I would like to know whether it is implemented using modern C++ conventions. I would like to know also whether keeping handlers sorted in a vector was a good choice or it should be done differently. Reactor is intended to listen on a socket and demultiplex messages from socket to corresponding message handlers."
}
] |
[
{
"body": "<p>No comment on the design, just style improvements.</p>\n<pre><code> auto pos = std::lower_bound(m_listeners.begin(), m_listeners.end(), m_searchValue, [](const MessageListener& one, const MessageListener& two)\n {\n if (one.m_type < two.m_type)\n return true;\n else\n return false;\n }\n );\n</code></pre>\n<p>I find this snippet very hard to read, especially because the lambda's parameter-list runs off the right side of the screen. I would write it with "Python-style" indentation:</p>\n<pre><code> auto pos = std::lower_bound(\n m_listeners.begin(),\n m_listeners.end(),\n m_searchValue,\n [](const auto& a, const auto& b) {\n return (a.m_type < b.m_type);\n }\n );\n</code></pre>\n<p>Notice that <code>if (x) return true; else return false;</code> is a too-verbose way of writing <code>return x;</code></p>\n<p>Also notice that we can use a generic lambda (<code>auto</code>) to shorten the parameter list, assuming that the reader already knows that <code>m_listeners</code> is a list of <code>MessageListener</code> objects so we don't have to explicitly repeat that type's name.</p>\n<hr />\n<pre><code>if (m_ptr.get() == nullptr)\n</code></pre>\n<p>Treat smart pointers like normal pointers. Using any named member function on a smart pointer is a code smell. If you want to test a pointer (smart <em>or</em> raw) for null, write simply:</p>\n<pre><code>if (m_ptr == nullptr)\n</code></pre>\n<hr />\n<p><code>typename ...HandlerParametersType</code> — I strongly recommend naming packs something plural. This isn't a <em>type</em>; it's a pack of <em>types</em>. So: <code>class... HandlerParameterTypes</code>, or simply <code>class... Params</code>, or simply <code>class... Ts</code>.</p>\n<hr />\n<pre><code>std::move(std::make_unique~~~\n</code></pre>\n<p>The result of a function call expression like <code>std::make_unique<T>(args...)</code> is already a prvalue. You don't have to cast it with <code>std::move</code>. (Remove the call to <code>std::move</code>.)</p>\n<hr />\n<pre><code>if (!m_stopThread)\n stopThread();\n</code></pre>\n<p>I strongly recommend using curly braces around the body of every control-flow construct in your program. Consider what happens if you add a logging statement temporarily:</p>\n<pre><code>if (!m_stopThread)\n std::cout << "stopping the thread\\n"; // Oops!\n stopThread();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T06:01:14.647",
"Id": "481623",
"Score": "0",
"body": "Quuxplusone, thank you very much. I really appreciate your time. I completely agree with all that you said above. Will fix it. Everything that you mentioned is very valuable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T04:42:50.397",
"Id": "245260",
"ParentId": "245133",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245260",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T13:52:07.510",
"Id": "245133",
"Score": "2",
"Tags": [
"c++11",
"c++14"
],
"Title": "C++ reactor bad implementation"
}
|
245133
|
<p>I am building the list of items (TEST) with <code>loadMore</code> button with filter and want to have loading state in LoadMore button and items itself.</p>
<p>After loading the item I will fetch the detail of the first item for the first time and after that load the detail of the test.</p>
<p>This code does not contain the fetching of the detail.</p>
<p>If the item is clicked again load the detail of another test.</p>
<pre><code>function TeacherTest() {
let { moduleId, url } = useModuleContext();
const [tests, setTests] = useState(null);
const [loading, setLoading] = useState(true);
const [activeTestId, setActiveTestId] = useState(null);
const [limit, setLimit] = useState(1);
const [offset, setOffset] = useState(0);
const [moreTest, setMoreTest] = useState(true);
const [loadingMore, setLoadingMore] = useState(false);
const [filter, setFilter] = useState("all");
const fetchTests = () => {
console.log(offset, "offset fetchTest");
axios({
method: "get",
url: `${url}/teacher/test?limit=${limit}&offset=${offset}`,
withCredentials: true,
}).then((res) => {
let newTests = res.data.tests;
newTests.length < limit && setMoreTest(false);
console.log(newTests === []);
console.log(newTests);
tests ? setTests([...tests, ...newTests]) : setTests(newTests);
});
};
useMemo(() => {
setTests(null);
setOffset(0);
}, [filter])
const showMoreTest = () => {
setOffset(offset + limit);
};
useEffect(() => {
fetchTests();
}, [url, offset, filter]);
return (
<div className="w-100" id="dash__wrapper">
<div className="dashboard__container mt-4">
<div className="main_dash">
<div className="row">
<div className="col-md-4 col-12 mb-2 px-0">
<div className="pt-0">
<div className="btn btn-block p-0 my-0">
<form action="./quiz-setup.php">
<Link to={`/${moduleId}/teacher/test/add`}>
<button
className="btn btn-lightblue p-2 w-100 mb-2"
id="addTest"
>
<i className="fas fa-plus pr-1" />
Add New Test
</button>
</Link>
</form>
</div>
</div>
<TestSchedule
tests={tests}
moreTest={moreTest}
filter={filter}
setFilter={setFilter}
showMoreTest={showMoreTest}
loadingMore={loadingMore}
/>
</div>
<div className="col-md-8">
<TestDetail />
<TestResult />
</div>
<div className="row">
<div className="col-md-4 col-12 mb-2 pl-md-2 px-0"></div>
</div>
</div>
</div>
</div>
</div>
);
}```
</code></pre>
<pre><code>function TestSchedule({ tests, showMoreTest, setFilter, loadingMore, moreTest }) {
return (
<div className="bg-white p-3 chart_contain dash__shadow dash__border">
<div className="w-100 clearfix mb-2">
<h6 className="py-2" style={{ fontWeight: 600 }}>
Test Schedule
</h6>
<div className="float-right">
{/* Dropdown to select test logs */}
<form>
<select
defaultValue="all"
onChange={(e) => {
setFilter(e.target.value);
}}
className="custom-select border-0"
>
<option value="all">All</option>
<option value="active">Active</option>
<option value="scheduled">Scheduled</option>
<option value="completed">Completed</option>
</select>
</form>
</div>
</div>
<div className="bg-light radius-10 p-2 mb-1">
<p className="quest__name">Weekly test 12</p>
<ul className="list-inline description-ans text-muted">
<li className="list-inline-item">
<i className="far fa-clock" />
&nbsp;40 min
</li>
<li className="list-inline-item">
<i className="fas fa-bullseye" />
&nbsp;80 Marks
</li>
<li className="list-inline-item">
<i className="fas fa-desktop" />
&nbsp;40 Questions
</li>
<li className="list-inline-item">
<i className="fas fa-users" />
&nbsp;MBBS 1st Year
</li>
</ul>
<div className="row control-question d-flex justify-content-between">
<div>
<span className="badge badge-pill badge-success">Active</span>
<small className="text-muted">June 20, 2020 - 17:00 NPT</small>
</div>
<div>
<div className="major__btn test-log">
<a href="#">
<button className="major__btn__type button__blue p-0 m-0">
<i className="fas fa-edit" />
</button>
</a>
<a href="#">
<button className="major__btn__type button__red p-0 m-0 ml-2">
<i className="fas fa-trash" />
</button>
</a>
</div>
</div>
</div>
</div>
<div className="bg-light radius-10 p-2 mb-1">
<p className="quest__name">Weekly test 12</p>
<ul className="list-inline description-ans text-muted">
<li className="list-inline-item">
<i className="far fa-clock" />
&nbsp;40 min
</li>
<li className="list-inline-item">
<i className="fas fa-bullseye" />
&nbsp;80 Marks
</li>
<li className="list-inline-item">
<i className="fas fa-desktop" />
&nbsp;40 Questions
</li>
<li className="list-inline-item">
<i className="fas fa-users" />
&nbsp;MBBS 1st Year
</li>
</ul>
<div className="row control-question d-flex justify-content-between">
<div>
<span className="badge badge-pill badge-danger">Expired on</span>
<small className="text-muted">June 20, 2020 - 17:00 NPT</small>
</div>
<div>
<div className="major__btn test-log">
<a href="#">
<button className="major__btn__type button__blue p-0 m-0">
<i className="fas fa-edit" />
</button>
</a>
<a href="#">
<button className="major__btn__type button__red p-0 m-0 ml-2">
<i className="fas fa-trash" />
</button>
</a>
</div>
</div>
</div>
</div>
{tests ?
tests.map((t, index) => {
// console.log(t, "From single test");
let { duration, id, end, name } = t;
return (
<div key={index} className="bg-light radius-10 p-2 mb-1">
<p className="quest__name">{name}</p>
<ul className="list-inline description-ans text-muted">
<li className="list-inline-item">
<i className="far fa-clock" />
&nbsp;{duration} min
</li>
<li className="list-inline-item">
<i className="fas fa-bullseye" />
&nbsp;80 Marks
</li>
<li className="list-inline-item">
<i className="fas fa-desktop" />
&nbsp;40 Questions
</li>
<li className="list-inline-item">
<i className="fas fa-users" />
&nbsp;MBBS 1st Year
</li>
</ul>
<div className="row control-question d-flex justify-content-between">
<div>
<span className="badge badge-pill badge-info">
Scheduled for
</span>
<small className="text-muted">
June 20, 2020 - 17:00 NPT
</small>
</div>
<div>
<div className="major__btn test-log">
<a href="#">
<button className="major__btn__type button__blue p-0 m-0">
<i className="fas fa-edit" />
</button>
</a>
<a href="#">
<button className="major__btn__type button__red p-0 m-0 ml-2">
<i className="fas fa-trash" />
</button>
</a>
</div>
</div>
</div>
</div>
);
}): <div> Loading Tests </div> }
{moreTest && (
<div className="row">
<button onClick={showMoreTest} className="btn btn-lightblue w-100">
{!loadingMore ? <>
<i className="fas fa-chevron-down pr-1" />
Show More
</> : "Loading..."}
</button>
</div>
)}
</div>
);
}
</code></pre>
<pre><code></code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T14:07:06.730",
"Id": "481350",
"Score": "0",
"body": "It wrok but I am looking for how i can improve it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T14:10:05.847",
"Id": "481355",
"Score": "0",
"body": "No detail is not fetched. Code is not complete. Only Tests is fetched for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T14:25:26.337",
"Id": "481360",
"Score": "0",
"body": "Updated the description. Thanks for helping to make the question clear."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T14:03:41.427",
"Id": "245134",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "Items with LoadMore Button, filter and the detail of first item or clicked item in React hooks"
}
|
245134
|
<p>Back from a long C++ hiatus. I thought to implement mergesort from memory, using containers and not based on CLRS's pseudocode and arrays. The compiles and runs ok on the test cases.</p>
<pre><code>/* TODOs
* Optimizations:
* [1] Have Mergesort sort values in-place: leftVec and rightVec contains references
*
* Improvements:
* [1] Have Mergesort take template arguments, allowing it to sort user classes
*/
#include "../template/template.h"
// Forward declarations
vector<int> Merge(const vector<int>& leftHalf, const vector<int>& rightHalf, int indentLevel);
vector<int> Mergesort(vector<int>& vals, int clogLevel = 0)
{
// Base case is vals.size >= 2
if (vals.size() <= 1) return vals;
// Divide vals into two sub-containers: leftHalf, rightHalf
int r = (vals.size() / 2);
auto leftHalf = vector<int>(vals.begin(), vals.begin() + r);
auto rightHalf = vector<int>(vals.begin() + r, vals.end());
// Debug print
//clog("leftHalf: " + StrItems(leftHalf, false), true, clogLevel);
//clog("rightHalf: " + StrItems(rightHalf, false), true, clogLevel);
auto sortedLeft = Mergesort(leftHalf, clogLevel + 1);
auto sortedRight = Mergesort(rightHalf, clogLevel + 1);
auto sorted = Merge(sortedLeft, sortedRight, clogLevel);
//clog("Sorted: " + StrItems(sorted, false), true, clogLevel);
return sorted;
}
// Returns a vector containing elements from leftHalf and rightHalf in ascending value
vector<int> Merge(const vector<int>& leftHalf, const vector<int>& rightHalf, int clogLevel = 0)
{
// If leftHalf is empty, returning an empty (or non-empty) rightHalf is what user would expect
if (leftHalf.begin() == leftHalf.end()) return rightHalf;
if (rightHalf.begin() == rightHalf.end()) return leftHalf; // Vice-versa
//clog("Merging: leftHalf & rightHalf; sizes " + to_string(leftHalf.size()) + "," + to_string(rightHalf.size()), true, clogLevel);
auto mergedVec = vector<int>();
auto leftItr = leftHalf.begin();
auto rightItr = rightHalf.begin();
while (leftItr != leftHalf.end() && rightItr != rightHalf.end()) {
if (*leftItr < *rightItr) {
mergedVec.push_back(*leftItr);
leftItr++;
} else if (*leftItr > *rightItr) {
mergedVec.push_back(*rightItr);
rightItr++;
} else {
// Both elements are equal: append both elements
mergedVec.push_back(*leftItr);
mergedVec.push_back(*rightItr);
leftItr++;
rightItr++;
}
}
// If both vectors are exhausted of elements, return
if (leftItr == leftHalf.end() && rightItr == rightHalf.end())
return mergedVec;
// If leftHalf is exhausted, append the rest of elements from rightHalf; vice-versa
if (leftItr == leftHalf.end())
mergedVec.insert(mergedVec.end(), rightItr, rightHalf.end());
else
mergedVec.insert(mergedVec.end(), leftItr, leftHalf.end());
return mergedVec;
}
int main(int argc, char **argv)
{
vector<int> Test1 {-1, 10, -2, 4, -5, 1, 3, 5};
cout << "Test1 (before sort): " << StrItems(Test1, true);
auto Result1 = Mergesort(Test1);
cout << "Test1 (after sort): " << StrItems(Result1, true);
vector<int> Test2 {3, -2, 3, 3, 0};
cout << "Test2: (before sort): " << StrItems(Test2, true);
auto Result2 = Mergesort(Test2);
cout << "Test2: (after sort): " << StrItems(Result2, true);
return 0;
}
</code></pre>
<p><strong>Template.h (Boilerplate)</strong></p>
<pre><code>#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <iostream>
#include <vector>
#include <array>
using std::string;
using std::to_string;
using std::cout;
using std::vector;
using std::array;
// Returns a string representation of the container as a space-separated concatenation of its
// elements. If newline is true, appends newline to the end of the string. The string is
// preceded by (indentLevel * indentWidth) number of indentChars.
template <class T>
string StrItems(T container, bool newline = true, int indentLevel = 0, int indentWidth = 2, char indentChar = ' ')
{
string repr = string(indentWidth * indentLevel, indentChar);
for (auto it = container.begin(); it != container.end(); it++) {
repr.append(to_string(*it) + " ");
}
if (newline)
repr.back() = '\n';
else
repr.erase(repr.end() - 1); // Removes the trailing space
return repr;
}
// Console-log. Writes msg to console. If newline is true (default), appends newline to the end of the
// string. The msg is preceded by (indentLevel * indentWidth) number of indentChars.
void clog(const string& msg, bool newline = true, int indentLevel = 0, int indentWidth = 2, char indentChar = ' ')
{
string indentation = string(indentWidth * indentLevel, indentChar);
cout << indentation << msg;
if (newline) cout << '\n';
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T15:48:33.367",
"Id": "481370",
"Score": "2",
"body": "Whereas your generic review question is basically on-topic, those specific questions (1-5) are not - to have them answered specifically, you would need to approach a different StackExchange site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T19:00:30.863",
"Id": "481392",
"Score": "0",
"body": "Questions removed."
}
] |
[
{
"body": "<h2>Don't <code>using std</code></h2>\n<p>...especially in a header. In a source file it's not so bad; but in a header, you're forcing anyone who includes it to pollute their namespace.</p>\n<h2>Const references</h2>\n<p>Since <code>Mergesort</code> is not in-place, <code>vals</code> should be passed as <code>const</code>.</p>\n<h2>Make your tests tests</h2>\n<p>The tests currently in main should have <code>assert</code>s so that they act as actual tests.</p>\n<h2>Your questions</h2>\n<blockquote>\n<p>By having <code>Merge</code> take references to <code>leftHalf</code> and <code>rightHalf</code>, I'm working with whatever memory was allocated (in this case, stack memory from <code>Mergesort</code>) and not <em>copies</em> of those vectors right?</p>\n</blockquote>\n<p>You're correct that <code>Merge</code> will not make copies at the beginning of the call due to the reference. However, accepting a reference does not guarantee that the referred variable was allocated on the stack, nor should that matter to the function.</p>\n<blockquote>\n<p>Lastly, I don't need to worry about free-ing <code>leftHalf</code>, <code>rightHalf</code>, <code>sortedLeft</code>, <code>sortedRight</code>, <code>sorted</code>, and <code>mergedVec</code> because they're allocated on the stack and returned by value, right?</p>\n</blockquote>\n<p>Right(ish). Even if you did need to free the memory, you wouldn't use <code>free()</code> - this is C++, so you would use <code>delete</code>.</p>\n<blockquote>\n<p>Is there a way to check which region of memory an object lies in (e.g., stack, heap, global, etc.)?</p>\n</blockquote>\n<p>You should never need to do this outside of maybe a very narrow and non-production debugging or profiling effort.</p>\n<blockquote>\n<p>we can say the address range 0x4FFFFFFFDDDDDDDD to 0x5000000000000000 is always where a program stores stack frames</p>\n</blockquote>\n<p>Absolutely not, and this is dependent on a number of things, including OS and processor (32-bit vs. 64-bit).</p>\n<p>Some operating systems go out of their way to <a href=\"https://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow noreferrer\">randomize this range</a> to make certain exploits more difficult.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:00:56.300",
"Id": "481451",
"Score": "0",
"body": "`Don't using std` Good advice in general. It was more for convenience. It's annoying to have to prepend everything with `std::` but I [see](https://www.youtube.com/watch?v=4NYC-VU-svE) why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:40:18.393",
"Id": "481453",
"Score": "0",
"body": "`Since Mergesort is not in-place, vals should be passed as const`. Fair enough. I didn't have a good reason for making vals `const` but I suppose it's better to be conservative until you have a good reason to keep it non-const (like implementing in-place sorting)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:43:09.550",
"Id": "481454",
"Score": "0",
"body": "`The tests currently in main should have asserts so that they act as actual tests.` If I were writing unit tests, I'd look for or write my own method that checks two containers for element-wise equality. I thought it'd be overkill for this example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:50:00.787",
"Id": "481455",
"Score": "0",
"body": "`Right(ish). Even if you did need to free the memory, you wouldn't use free() - this is C++, so you would use delete.` Good catch. Yep -- it's `new/delete` not `malloc/free`. Also, I recently read [SO: Do vectors use stack or heap memory](https://stackoverflow.com/a/8036528/3396951) and it seems the container elements are actually created on the heap but the class cleans up itself when it goes out of [scope](https://www.youtube.com/watch?v=iNuTwvD6ciI)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:52:04.597",
"Id": "481456",
"Score": "0",
"body": "`You should never need to do this outside of maybe a very narrow and non-production debugging or profiling effort.` I wanted to use it for educational purposes, not for development reasons."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T17:39:48.953",
"Id": "245144",
"ParentId": "245135",
"Score": "3"
}
},
{
"body": "<h2>Overview</h2>\n<p>A couple of things I would note:</p>\n<p>1: Your code only works for integers. Why do you care? You have shown you know about templates so it would be reasonable to make this sort any type of object that is comparable.</p>\n<p>I suppose you acknowledge this in the comments:</p>\n<pre><code> // Have Mergesort take template arguments, allowing it to sort user classes\n</code></pre>\n<p>But when you try this it will throw up questions around copy (the default and not bad for integers) against move (A better idea for complex/expensive objects).</p>\n<p>2: Why only vectors. It is fine to internally use vectors for storage for the intermediate results. But the interface should not limit you to sorting one specific type of container.</p>\n<p>Now you could templatize on the container type. But usually in C++ we abstract the container from the algorithm by using iterators. So I would have used iterators as the input to the sort (so that you can use any container simply passing the iterators to the algorithm).</p>\n<p>3: You use an "Extra" <code>2x</code> the input size of memory compared the input data as temporary storage. You can do this with only <code>1x</code> extra memory and with a bit of work you only do the allocation once (doing the allocation again and again can be expensive).</p>\n<p>4: You return a new array (with the sorted content). Why not sort the content in place. You don't need to force the creation of a new container. If the original user wants a new container then the user can make a copy and then use a sort in place algorithm. I think the creation of a new container is an extra unnecessary step that you are forcing your user to pay for that they may not want to.</p>\n<p>You sort of mention this as an improvement:</p>\n<pre><code> // Have Mergesort sort values in-place: leftVec and rightVec contains references \n</code></pre>\n<p>But I don't think you can have l/r Vec be references when you do this.</p>\n<h2>Comments</h2>\n<blockquote>\n<p>Back from a long C++ hiatus.</p>\n</blockquote>\n<p>Welcome Back.</p>\n<blockquote>\n<p>I thought to implement mergesort from memory</p>\n</blockquote>\n<p>Its a fun learning example. I like bubble sort my self.</p>\n<blockquote>\n<p>using containers and not based on CLRS's pseudocode and arrays.</p>\n</blockquote>\n<p>I had to look up what CLRS mean. You learn something new every day.</p>\n<blockquote>\n<p>The compiles and runs ok on the test cases.</p>\n</blockquote>\n<p>Good. That means you read the rules :-)</p>\n<h2>Code review:</h2>\n<p>If you are not modifying the orignal pass by const reference to catch mistakes.</p>\n<pre><code>vector<int> Mergesort(vector<int> const& vals, int clogLevel = 0)\n ^^^^^\n</code></pre>\n<hr />\n<p>auto leftHalf = vector(vals.begin(), vals.begin() + r);\nauto rightHalf = vector(vals.begin() + r, vals.end());</p>\n<p>Worth mentioning this is a copy operation. For anything more complex a move would be better (but that would also require the original be modifiable which suggests a merge sort in place).</p>\n<p>Note: There are specific move iterators that you can use.</p>\n<hr />\n<p>Remove Dead code:</p>\n<pre><code> // Debug print\n //clog("leftHalf: " + StrItems(leftHalf, false), true, clogLevel);\n //clog("rightHalf: " + StrItems(rightHalf, false), true, clogLevel);\n</code></pre>\n<p>That is what source control is for.</p>\n<hr />\n<p>How I hate redundant comments.</p>\n<pre><code>// Returns a vector containing elements from leftHalf and rightHalf in ascending value\n</code></pre>\n<p>Don't explain what the code should do. That should be done using self documenting code (function/variable names). Your comments should explain things that are not easy to see be captured by the code (WHY).</p>\n<p>The problem is that comments rot over time. So they need to be maintained with the code. If your comments rot to a point where they don't reflect the code which is wrong? What do you fix. So let the code explain how it does it let the comments explain why (or things that are not obvious in the code).</p>\n<hr />\n<p>Why are you testing the iterators here?</p>\n<pre><code> if (leftHalf.begin() == leftHalf.end()) return rightHalf;\n if (rightHalf.begin() == rightHalf.end()) return leftHalf; // Vice-versa\n</code></pre>\n<p>I think the more meaningful test is to simply test to see if it is empty.</p>\n<pre><code> if (leftHalf.empty()) return rightHalf;\n if (rightHalf.empty()) return leftHalf;\n</code></pre>\n<p>I believe that conveys the intent of the code much more clearly.</p>\n<hr />\n<p>I would simplify this:</p>\n<pre><code> if (*leftItr < *rightItr) {\n mergedVec.push_back(*leftItr); \n leftItr++;\n } else if (*leftItr > *rightItr) {\n mergedVec.push_back(*rightItr);\n rightItr++;\n } else {\n // Both elements are equal: append both elements\n mergedVec.push_back(*leftItr);\n mergedVec.push_back(*rightItr);\n leftItr++;\n rightItr++;\n }\n\n\n // Like this:\n\n if (*leftItr <= *rightItr) {\n mergedVec.push_back(*leftItr); \n ++leftItr;\n }\n else {\n mergedVec.push_back(*rightItr);\n ++rightItr;\n }\n\n // PS:\n // prefer pre-increment over post.\n ++rightItr;\n</code></pre>\n<p>Most of the time they are equivalent. But now and then the pre-increment is slightly more efficient. Based on the standard way of implementing it.</p>\n<p>see: <a href=\"https://stackoverflow.com/a/3846374/14065\">How to overload the operator++ in two different ways for postfix a++ and prefix ++a?</a></p>\n<hr />\n<p>Again you are complicating this.</p>\n<pre><code> // If both vectors are exhausted of elements, return\n if (leftItr == leftHalf.end() && rightItr == rightHalf.end())\n return mergedVec;\n\n // If leftHalf is exhausted, append the rest of elements from rightHalf; vice-versa\n if (leftItr == leftHalf.end())\n mergedVec.insert(mergedVec.end(), rightItr, rightHalf.end());\n else\n mergedVec.insert(mergedVec.end(), leftItr, leftHalf.end());\n\n\n // Simplify like this:\n\n mergedVec.insert(mergedVec.end(), rightItr, rightHalf.end());\n mergedVec.insert(mergedVec.end(), leftItr, leftHalf.end());\n</code></pre>\n<p>Yes one of those vectors will be empty. But inserting an empty range is not going to have a cost.</p>\n<hr />\n<p>Tiny bit generic for guards.</p>\n<pre><code>#ifndef TEMPLATE_H\n#define TEMPLATE_H\n</code></pre>\n<p>Put your code into your own namespace. Then add your namespace as part of your include guard.</p>\n<hr />\n<p>Never do this.</p>\n<pre><code>using std::string;\nusing std::to_string;\nusing std::cout;\nusing std::vector;\nusing std::array;\n</code></pre>\n<p>Its bad in a source file. In a header file you can break other peoples code. Its simpler to just always use the prefix <code>std::</code> (its only 5 more characters). Don't be lazy.</p>\n<hr />\n<pre><code> string repr = string(indentWidth * indentLevel, indentChar);\n</code></pre>\n<p>Sure you can build a string using append and addition. But I would personally use a <code>std::stringstream</code>. Just like a stream but does it into a string. Nice for building printable objects.</p>\n<hr />\n<p>A recent addition to the C++ language is range based for:</p>\n<pre><code> for (auto it = container.begin(); it != container.end(); it++) {\n repr.append(to_string(*it) + " ");\n }\n</code></pre>\n<p>This can be written as:</p>\n<pre><code> for(auto const& val: container) {\n repr.append(to_string(val)) + " ");\n }\n</code></pre>\n<p>The range based for uses <code>std::begin()</code> and <code>std::end()</code> on the <code>container</code> object and assigns the result of the de-referenced object to the <code>val</code>.</p>\n<pre><code> for(Type val: container) {\n <CODE>\n }\n</code></pre>\n<p>Is syntactically equivalent to:</p>\n<pre><code> {\n ContainerType::iterator end = std::end(container);\n ContainerType::iterator loop = std::begin(container);\n\n for(;loop != end; ++loop) {\n Type Val = *loop;\n\n <CODE>\n }\n } \n</code></pre>\n<hr />\n<h2>Example</h2>\n<p>I have done a previosu code review on merge sort.</p>\n<p><a href=\"https://codereview.stackexchange.com/a/137939/507\">https://codereview.stackexchange.com/a/137939/507</a></p>\n<p>At the end of my answer I provide a good implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:55:06.530",
"Id": "481457",
"Score": "0",
"body": "`1. Your code only works for integers.` If I knew how to apply templates, I would have done so :-). I thought to improve this code incrementally -- make it work for ints, `git commit`, make it sort in place, `git commit`, make it work for any user types, etc. Copy/move constructors are one of those concepts I haven't learned yet. Will get to it soon, though. [Cherno](https://www.youtube.com/watch?v=BvR1Pgzzr38) has some good tuts for [this](https://www.youtube.com/watch?v=ehMg6zvXuMY)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:00:51.173",
"Id": "481458",
"Score": "0",
"body": "`2. I would have used iterators as the input to the sort (so that you can use any container simply passing the iterators to the algorithm).` Good idea. It sounds like this advice goes in tandem with advice #1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:03:06.297",
"Id": "481459",
"Score": "0",
"body": "`make vals const to prevent inadvertently modifying its value.` Fair point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:11:04.677",
"Id": "481460",
"Score": "0",
"body": "`// Returns a vector containing elements from leftHalf and rightHalf in ascending value` Oh common. It wasn't that bad! It was meant to be a brief doc string because I figured just by looking at the signature of `Merge`, it wasn't immediately obvious whether the function returned sorted values in ascending or descending order. I suppose renaming the method `MergeAscending()` or `Merge(bool ascending)` would have been just as clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:17:12.210",
"Id": "481462",
"Score": "0",
"body": "`Your comments should explain things that are not easy to see be captured by the code (WHY).` I'm familiar with the coding guideline that advocates explaining *why* code does something and not *how* it's done. [Stroustrup](https://www.youtube.com/watch?v=fX2W3nNjJIo) has a nice note on this @1:01:54. I'd never write a comment that could be ascertained by simply reading the code. However, it's a judgement call -- I've seen functions that read as sentences (i.e., unit test functions), which can look just as bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:20:17.203",
"Id": "481463",
"Score": "0",
"body": "`I think the more meaningful test is to simply test to see if it is empty.` Agreed `Interator.empty()` is more concise. I just didn't know about it at the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:27:07.483",
"Id": "481464",
"Score": "0",
"body": "`Yes one of those vectors will be empty. But inserting an empty range is not going to have a cost.` I agree your suggestion is more simple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:34:53.667",
"Id": "481465",
"Score": "0",
"body": "`Its simpler to just always use the prefix std:: (its only 5 more characters). Don't be lazy.` :-( there are trade offs and I think its usage must be accompanied with an understanding of how the code will be used. This isn't going to be production code; it's boilerplate code for small one-off programs used to test C++ features. It kind of annoys me that python has f-strings, C# has string-interpolation, C has printf but C++ is stuck with std::cout << to_string() << std::endl; ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:36:18.530",
"Id": "481466",
"Score": "0",
"body": "`use a std::stringstream. Just like a stream but does it into a string. Nice for building printable objects.` Interesting. Didn't know about stringstream. Will look into some examples, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:41:27.577",
"Id": "481467",
"Score": "0",
"body": "`A recent addition to the C++ language is range based for`. It's a handy feature indeed but in this case, I didn't need to iterate over an entire collection. I needed `leftItr` or `rightItr` to point to the remaining container elements when one (or both gets exhausted)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T18:11:53.247",
"Id": "481483",
"Score": "0",
"body": "`This isn't going to be production code; it's boilerplate code for small one-off programs used to test C++ features` That's a dangerous road to go down. The problem here is the way you normally do things. If you keep doing this as normal then you will inevitably slip and do it in production (that's when things screw up). The best technique is to always treat your code as production code and avoid bad habits that we they don't become part of your muscle memory and slip in where they are not intended. PS/ don't use `std::endl` use `\"\\n\"` (see a lot of other reviews)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T18:19:35.427",
"Id": "481484",
"Score": "0",
"body": "`I needed leftItr or rightItr to point to the remaining container elements`. The beauty of the \"range based for\" is that it is based on other base level concepts so you can mold its behavior by using simple wrapper types (with a bunch being added to the standard in C++20). You can create a simple wrapper that returns `leftItr and end` very easily. Then create this wrapper object inside the for statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T18:27:19.827",
"Id": "481486",
"Score": "0",
"body": "`I suppose renaming the method MergeAscending() or Merge(bool ascending)`. I would not limit yourself to ascending/descending. I would speiify this in terms of a comparator: `template<typename I, typename Comparator> merge(I begin, I end);` Where `Comparator` is a function that compares objects of the type to provide the correct type of sort. Now you can have a default Comparator of `std::less()` to provide your default ascending merge."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T07:07:55.483",
"Id": "245168",
"ParentId": "245135",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T14:25:10.693",
"Id": "245135",
"Score": "3",
"Tags": [
"c++",
"mergesort",
"heap"
],
"Title": "Mergesort (using vectors) and some questions about memory"
}
|
245135
|
<p>We have a new service where an admin can upload a spreadsheet of new users they want to add to our application. During our processing we make a union map of all the users both existing and new additions, and check to make sure that the users will still be in a valid tree structure(s) after the update goes through.</p>
<p><strong>Requirements:</strong><br />
For the user relationship tree structure to be valid,</p>
<ul>
<li>There can be no circular references (ex. Users cannot be each other's manager)</li>
<li>A single branch of the tree cannot exceed 50 users (ex. There should not be 50 middle-management managers between CEO and Janitor).</li>
<li>Its ok if the tree is severed into multiple trees when a user does not have a manager. Separate warnings are generated for that circumstance.</li>
</ul>
<p>This may need to scale to up to 1,000,000 user relationships, so far, the current solution supports at least 10,000 user relationships in a reasonable amount of time (less than 1 minute running locally).</p>
<p>FYI this is Groovy/Java</p>
<p><strong>Solution So Far:</strong><br />
I have a method that takes a HashMap of user relationships and it returns a list of invalid users ids.</p>
<pre><code>Map<String, String> userRelationships = [["userId1": "userId2"], ["userId2": "userId3"], ...]
def invalidRelationships = findInvalidRelationships(userRelationships)
</code></pre>
<p>.</p>
<pre><code>/**
* Takes a map of user relationships (user with corresponding manager)
* For each relationship, climb up the tree and look to see if the user is repeated in their branch
* If user is found again up the tree branch, that is a bad circular reference
* If the current branch goes on past 50 users, that is too long and also invalid
* Report all users that are part of that bad relationship
* userRelationship.key is the user
* userRelationship.value is the manager
*/
def findInvalidUserRelationships(Map<String, String> userRelationships) {
Set<String> invalidUserRelationshipUsers = []
userRelationships.each { Entry<String, String> currentUserRelationship ->
Set<String> usersInCurrentBranch = []
Entry<String, String> nextIterationRelationship = currentUserRelationship
while (
nextIterationRelationship?.value && //while not top of tree (not null manager)
!invalidUserRelationshipUsers.contains(nextIterationRelationship.key) && //while user not part of circular relationship
!usersInCurrentBranch.contains(nextIterationRelationship.key) //while user not connected to other circular relationship
) {
usersInCurrentBranch << nextIterationRelationship.key
//if bad circular relationship found or branch has more than max users, report users as invalid
if (nextIterationRelationship.value == currentUserRelationship.key || usersInCurrentBranch?.size() > 50) {
invalidUserRelationshipUsers += usersInCurrentBranch
}
//set next user relationship to check in next iteration (manager's manager) - (go upline)
nextIterationRelationship = new MapEntry(
nextIterationRelationship.value, //manager of current iteration user will be next user
userRelationships[nextIterationRelationship.value as String] //manager's manager
)
}
}
return invalidUserRelationshipUsers as List<String>
}
</code></pre>
<p>I have already made lots of optimizations, at least compared to how bad it was before using only Lists instead of Maps and Sets, but I was wondering if there would be a more efficient solution to this problem. I wondered if a Java TreeMap would be appropriate somewhere here, but could not figure out how it could improve performance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T17:48:26.087",
"Id": "481380",
"Score": "0",
"body": "Great first question!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T17:42:14.230",
"Id": "245145",
"Score": "2",
"Tags": [
"java",
"algorithm",
"tree",
"validation",
"groovy"
],
"Title": "Find Invalid User Relationships in User to Manager Map (validate map as valid tree structure with no circular relationships)"
}
|
245145
|
<p>I've made a Discord Bot in Python that uses the Psycopg module to make calls to a PostgreSQL database in order to display information.</p>
<p><a href="https://github.com/Chombler/cardbot" rel="nofollow noreferrer">https://github.com/Chombler/cardbot</a></p>
<p>Specifically, I call this function when a user calls the bot:</p>
<pre><code>def pullCardRecord(recordName):
success = True
try:
print("Trying")
connection = psycopg2.connect(user = db_credentials[0],
password = db_credentials[1],
host = db_credentials[2],
port = db_credentials[3],
database = db_credentials[4])
print("connected")
cursor = connection.cursor()
join_table_query = '''
SELECT id
FROM card
WHERE card.name = ('%s') ''' % (recordName)
cursor.execute(join_table_query)
results = cursor.fetchall()
print(results)
if len(results) < 1:
success = False
raise ValueError('The name that was given to cardbot didn\'t exist in the card table.')
join_table_query = '''
SELECT name,
cardclass.cardclass,
tribe.tribe, cardtype.cardtype,
cost, side.side, strength, trait.strengthmodifier, health, trait.healthmodifier,
trait.trait,
ability,
flavor,
cardset.cardset,
rarity.rarity
FROM card
LEFT JOIN cardtoclass ON card.id = cardtoclass.cardid
LEFT JOIN cardclass ON cardtoclass.classid = cardclass.id
LEFT JOIN cardtotrait ON cardtotrait.cardid = card.id
LEFT JOIN trait ON cardtotrait.traitid = trait.id
LEFT JOIN cardtotribe ON card.id = cardtotribe.cardid
LEFT JOIN tribe ON cardtotribe.tribeid = tribe.id
LEFT JOIN cardtype ON cardtype.id = card.typeid
LEFT JOIN cardset ON cardset.id = card.setid
LEFT JOIN rarity ON card.rarityid = rarity.id
LEFT JOIN side ON card.sideid = side.id
WHERE card.name = ('%s') ''' % (recordName)
cursor.execute(join_table_query)
results = cursor.fetchall()
print("Printing Results")
for row in results:
for col in row:
print(col)
print()
cardInstance = cardObject(results)
print(cardInstance.information())
# Print PostgreSQL version
cursor.execute("SELECT version();")
record = cursor.fetchone()
print("You are connected to - ", record,"\n")
except (Exception, psycopg2.Error) as error :
print ("Error retrieving card information using PostgreSQL,", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
return(cardInstance.information() if success else "I'm sorry, I couldn't find a card with that name.")
</code></pre>
<p>I want to make sure that the bot is protected from any direct sql injections before I deploy it. Is it currently fairly safe or do I need to add anything to protect its integrity?</p>
|
[] |
[
{
"body": "<h2>Unpacking</h2>\n<p>Try this rather than hard-coded indexing:</p>\n<pre><code> user, password, host, port, database = db_credentials\n connection = psycopg2.connect(user, ...)\n</code></pre>\n<p>Or, if you're able to rearrange those parameters such that they match those of the <a href=\"https://www.psycopg.org/docs/module.html#psycopg2.connect\" rel=\"nofollow noreferrer\"><code>connect</code> signature</a>:</p>\n<blockquote>\n<ul>\n<li>dbname – the database name (database is a deprecated alias)</li>\n<li>user – user name used to authenticate</li>\n<li>password – password used to authenticate</li>\n<li>host – database host address (defaults to UNIX socket if not provided)</li>\n<li>port – connection port number (defaults to 5432 if not provided)</li>\n</ul>\n</blockquote>\n<p>then you can simply do</p>\n<pre><code>connection = psycopg2.connect(*db_credentials)\n</code></pre>\n<h2>Logs</h2>\n<p>Consider replacing</p>\n<pre><code> print("Trying")\n print("connected")\n</code></pre>\n<p>with calls to the actual <code>logging</code> module, which is more configurable and maintainable.</p>\n<h2>Quote escapes</h2>\n<pre><code>'The name that was given to cardbot didn\\'t exist in the card table.'\n</code></pre>\n<p>can be</p>\n<pre><code>"The name that was given to cardbot didn't exist in the card table."\n</code></pre>\n<h2>In-application queries</h2>\n<p>Your <code>join_table_query</code> is long. There are several approaches to improve this - either save a view in the database (my favourite), or a stored procedure (common but I think it's overkill in this case).</p>\n<h2>Injection</h2>\n<blockquote>\n<p>the bot is protected from any direct sql injections before I deploy it</p>\n</blockquote>\n<p>This is directly vulnerable:</p>\n<pre><code>'''... WHERE card.name = ('%s') ''' % (recordName)\n</code></pre>\n<p>Never (ever) use string formatting to insert parameters to a query. All DB connection libraries have anticipated this concern and most approach it using "prepared statements".</p>\n<p><a href=\"https://www.psycopg.org/articles/2012/10/01/prepared-statements-psycopg/\" rel=\"nofollow noreferrer\">This article</a> is old but relevant. The <a href=\"https://www.psycopg.org/docs/cursor.html#cursor.execute\" rel=\"nofollow noreferrer\">actual reference</a> shows that you should be passing <code>vars</code> as a sequence or a mapping, which will prevent injection.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:26:56.997",
"Id": "245148",
"ParentId": "245146",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245148",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T17:52:44.310",
"Id": "245146",
"Score": "4",
"Tags": [
"python",
"postgresql"
],
"Title": "Discord bot with Psycopg"
}
|
245146
|
<p><strong>What I wanted to do</strong></p>
<p>As part of a larger project, I needed a simple text editor with line numbers. The editor should also be able to highlight the current line (line number in bold) and define the tab size.</p>
<p>The result looks like this:</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/85pWY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/85pWY.png" alt="enter image description here" /></a></p>
</blockquote>
<p><strong>My solution</strong></p>
<p>After searching the internet for a while, I found out about the possibility of using a <code>DocumentListener</code> and adding a sepearate text-component with the line-numbers as <code>RowHeader</code>:</p>
<ul>
<li><a href="https://stackoverflow.com/a/23163153/13634030">DocumentListener</a></li>
<li><a href="https://stackoverflow.com/a/4618934/13634030">RowHeader</a></li>
</ul>
<p>I also found <a href="https://www.javaprogrammingforums.com/java-swing-tutorials/915-how-add-line-numbers-your-jtextarea.html" rel="nofollow noreferrer">this</a> complete solution, but nevertheless implemented the class it on my own - for learning purposes.</p>
<p>My implementation of it looks like this:</p>
<pre><code>import java.awt.Color;
import java.awt.Font;
import java.awt.Dimension;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
/**
*
* @author Philipp Wilhelm
* Provides a JScrollPane with line-numbers
*/
public class EditorScrollPane extends JScrollPane {
private static final long serialVersionUID = 1L;
private JTextPane inputArea;
private String indentation = " ";
private JTextPane lineNumbers;
/*
* Here the constructor creates a TextPane as an editor-field and another TextPane for the
* line-numbers.
*/
public EditorScrollPane(int width, int height) {
// Editor-field
inputArea = new JTextPane();
inputArea.setPreferredSize(new Dimension(width, height));
Document doc = inputArea.getDocument();
// Replacing tabs with two spaces
((AbstractDocument) doc).setDocumentFilter(new DocumentFilter() {
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
throws BadLocationException {
super.insertString(fb, offset, text.replace("\t", indentation), attrs);
}
});
// Line-numbers
lineNumbers = new JTextPane();
lineNumbers.setBackground(Color.GRAY);
lineNumbers.setEditable(false);
// Line-numbers should be right-aligned
SimpleAttributeSet rightAlign = new SimpleAttributeSet();
StyleConstants.setAlignment(rightAlign, StyleConstants.ALIGN_RIGHT);
lineNumbers.setParagraphAttributes(rightAlign, true);
doc.addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
lineNumbers();
}
@Override
public void insertUpdate(DocumentEvent e) {
lineNumbers();
}
@Override
public void removeUpdate(DocumentEvent e) {
lineNumbers();
}
});
// Setting font
this.setFont(new Font("Monospaced", 12, Font.PLAIN));
// Sets the main-component in the JScrollPane. this.add(inputArea) wasn't
// enough in this case
this.getViewport().add(inputArea);
// Adds lineNumbers as row header on the left side of the main JTextPane
this.setRowHeaderView(lineNumbers);
}
private void lineNumbers() {
try {
String str = inputArea.getText();
// Plain Style
SimpleAttributeSet plain = new SimpleAttributeSet();
StyleConstants.setFontFamily(plain, "Monospaced");
StyleConstants.setFontSize(plain, 12);
// Bold style
SimpleAttributeSet bold = new SimpleAttributeSet();
StyleConstants.setBold(bold, true);
// Remove all from document
Document doc = lineNumbers.getDocument();
doc.remove(0, doc.getLength());
// Calculating the number of lines
int length = str.length() - str.replaceAll("\n", "").length() + 1;
// Adding line-numbers
for (int i = 1; i <= length; i++) {
// Non-bold line-numbers
if (i < length) {
doc.insertString(doc.getLength(), i + "\n", plain);
// Last line-number bold
} else {
doc.insertString(doc.getLength(), i + "\n", bold);
}
}
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/*
* Setting indentation size in editor-field
*/
public void setIndentationSize(int size) {
String cache = indentation;
indentation = "";
for (int i = 0; i < size; i++) {
indentation += " ";
}
// Replace all previous indentations (at beginning of lines)
inputArea.setText(inputArea.getText().replaceAll(cache, indentation));
}
/*
* Overrides the method getText().
*/
public String getText() {
return inputArea.getText();
}
/*
* Overrides the method setText().
*/
public void setText(String str) {
inputArea.setText(str);
}
}
</code></pre>
<p><strong>Minimal working example</strong></p>
<p>If you want to test the class, you can use the following class to run the code:</p>
<pre><code>// Just for testing purposes
import javax.swing.*;
public class Test {
public static void main(String[] args) {
// Frame
JFrame frame = new JFrame("Editor-Field");
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panel
JPanel panel = new JPanel();
EditorScrollPane editor = new EditorScrollPane(400,400);
panel.add(editor);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}
</code></pre>
<p><strong>Questions</strong></p>
<ul>
<li>How can this code be improved in general?</li>
<li>Can the line-numbering be done in a more efficient way?</li>
<li>Does this class miss anything important that you would expect from such a class?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T14:44:32.070",
"Id": "481472",
"Score": "1",
"body": "Lines (paragraphs) may vary in height (which would argue for a line number as part of an extra paragraph margin). You may use StyledDocument as using their attributes; the base class of HTML and RTF (Rich Text Format). Lighter background for line numbers, width based on log10(number of lines). Very nice beginning."
}
] |
[
{
"body": "<h2>Awkward Container</h2>\n<p>you create a composite component - the child items are</p>\n<ul>\n<li><code>JTextPane inputArea</code></li>\n<li><code>JTextPane lineNumbers</code></li>\n</ul>\n<p>as container for these you use a <code>JScrollPane</code> - why is that so? why don't you use a simple container (like a <code>JPanel</code>) instead?</p>\n<p>When you use a <code>JScrollPane</code> instead a mere <code>JPanel</code> you bring in more complexity than required. Additionally i would not expect <strong>any component</strong> to be a scrollPanel except a - well yes, except a <code>JScrollPane</code> itself...</p>\n<h2>Inconsistent Font Handling</h2>\n<p>the font size of your LineNumberComponent should be equal to the EditorComponent font size - if they differ, the line numbers start to drift for each line a bit more</p>\n<p><strong>additional</strong></p>\n<p>you set the font in the container (the <code>JScrollPane</code>) - that makes no sense in my opinion. (I think it's a typo and should be <code>inputArea.setFont(...)</code> )</p>\n<pre><code>// Setting font\nthis.setFont(new Font("Monospaced", 12, Font.PLAIN));\n</code></pre>\n<h2>method naming</h2>\n<ul>\n<li><code>lineNumbers</code> is not a verb but should be - maybe something like <code>adjustLineNumbering</code>?</li>\n<li><code>setIndentationSize</code> does not, what a setter should do: set a value - instead rename it into what it really does: <code>adjustIndentation</code></li>\n</ul>\n<h2>Line Highlightning</h2>\n<p>you can get the cursors position by using the <a href=\"https://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#getCaretPosition()\" rel=\"nofollow noreferrer\">getCaretPosition</a> to determine the selected line - even thou you'll have to do some math on your own. have a look at <a href=\"https://stackoverflow.com/questions/2713863/how-to-display-bold-text-in-only-parts-of-jtextarea\">this answer on stackoverflow</a> how you can make parts of a <code>JTextArea</code> in bold.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:41:08.790",
"Id": "245182",
"ParentId": "245147",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245182",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:16:45.117",
"Id": "245147",
"Score": "2",
"Tags": [
"java",
"swing"
],
"Title": "JTextPane with line-numbers"
}
|
245147
|
<p>I wrote a bash script to move certain files within a group of directories with filenames that match certain conditions to another group of directories, but it is very cluttered. If possible, I want some help and tips regarding optimizing it:</p>
<pre><code>#!/bin/bash
#Asks for user confirmation
echo "This will move all files in the School folder that are not text files to the SchoolOld folder"
echo
echo "P.S. It will move everything with a name timestamp less than or equal to today."
echo
echo -n "Press [Y] to move all of the schoolwork you've already done to a separate folder or [N] to cancel: "
old_stty_cfg=$(stty -g)
stty raw -echo
answer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )
stty $old_stty_cfg
if echo "$answer" | grep -iq "^y" ;then
sleep 1
else
echo -e "\n"
exit 1
fi
#Sets variables
mn=$(date +'%m')
dy=$(date +'%d')
mf=$((10#$mn))
df=$((10#$dy))
txt=$((0))
#Asks user how many days to go back
while [[ $count -gt 91 ]] 2> /dev/null || [[ $count -lt 1 ]] 2> /dev/null
do
echo -e "\n"
echo -n "How many days do you want to go back and save? (max. 90): "
read -e count
if [[ $count -gt 90 ]] 2> /dev/null || [[ $count -lt 1 ]] 2> /dev/null ; then
echo -e "\n"
echo "Please try again."
fi
done
if ! [ $count -eq $count 2> /dev/null ]; then #Checks if entered value is an integer
echo
echo "Only integers are allowed. Exiting."
exit 1
fi
#Asks for user confirmation
echo
echo "Do you also want to delete any text files with a timestamp less than or equal to today? [Y/N]"
old_stty_cfg=$(stty -g)
stty raw -echo
answer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )
stty $old_stty_cfg
if echo "$answer" | grep -iq "^y" ;then
((txt=1))
else
((txt=0))
fi
#Moves files
while [[ $df -gt 0 ]] && [[ $count -gt 0 ]]; do
echo "The curent month in <span class="math-container">\$mf is $mf"
echo "The current day in \$</span>df is $df"
find ./School/Art -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Art" \;
find ./School/Comp -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Comp" \;
find ./School/Cont -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Cont" \;
find ./School/Eng -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Eng" \;
find ./School/Esp -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Esp" \;
find ./School/Geo -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Geo" \;
find ./School/Hist -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Hist" \;
find ./School/LPT -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/LPT" \;
find ./School/Math -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Math" \;
find ./School/P.E -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/P.E" \;
find ./School/Port -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Port" \;
find ./School/Sci -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Sci" \;
if [[ $txt -eq 1 ]]; then
find ./School -iname "*$df*-*$mf*.txt" -exec rm -i "{}" \; #Deletes the text files
fi
if [[ $df -eq 1 ]]; then #Sets month values
if [[ $mf -eq 02 ]]; then
((df=31))
fi
if [[ $mf -eq 4 ]] || [[ $mf -eq 6 ]] || [[ $mf -eq 9 ]] || [[ $mf -eq 11 ]]; then
((df=30))
else
((df=31))
fi
if [[ $mf -eq 1 ]] && [[ $df -eq 1 ]]; then
echo "Cannot return back more than a year."
exit 1
fi
((mf=mf-1))
echo "the month now is $mf"
fi
((df=df-1))
((count=count-1))
done
</code></pre>
|
[] |
[
{
"body": "<p>Your code doesn't contain sample data, so any following code adjustments are made on just what I read from your code.</p>\n<pre><code>answer=$( while ! head -c 1 | grep -i '[ny]' ;do true ;done )\nstty $old_stty_cfg\nif echo "$answer" | grep -iq "^y" ;then\n sleep 1\nelse\n echo -e "\\n"\n exit 1\nfi\n</code></pre>\n<p>Could be written as:</p>\n<pre><code>read -p "Are you sure? " -n 1 -r\nif ! [[ $REPLY =~ ^[Yy]$ ]] ; then\n exit 1 \nfi\n</code></pre>\n<p>Not only is this way easier to read, but requires so much less hacking of the tty sessions to do so. Also, I'm of the opinion, if they answer anything but "Y" then exit the script immediately. In your case, YN is a funny mistype, but is a valid input which would cause your script to continue.</p>\n<pre><code>if [[ $count -gt 90 ]] 2> /dev/null || [[ $count -lt 1 ]] 2> /dev/null\n</code></pre>\n<p>Should be written as:</p>\n<pre><code>if [[ ( $count -gt 90 ) && ( $count -lt 1 ) ]] ; then\n</code></pre>\n<p>This is one statement which represent multiple conditions. Again, this is sanitizing your variables and only using what you expect to happen.</p>\n<p>I do not know why you are redirecting stderr to /dev/null and would be interested to see what bash flags here as errors which would be crucial to critiquing your code.</p>\n<pre><code> find ./School/Art -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Art" \\;\n find ./School/Comp -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Comp" \\;\n find ./School/Cont -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/Cont" \\;\n</code></pre>\n<p>Whenever you do something multiple times, consider using a for loop.</p>\n<pre><code>for DIRECTORY in Art Comp Cont Eng Esp Geo Hist LPT; do \n find ./School/${DIRECTORY} -iname "*$df*-*$mf*.*" ! '(' -iname "*.txt" ')' -exec mv "{}" -t "./SchoolOld/${DIRECTORY}" \\;\ndone\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-27T22:19:10.550",
"Id": "246099",
"ParentId": "245150",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:35:34.037",
"Id": "245150",
"Score": "6",
"Tags": [
"bash"
],
"Title": "Optimizing script to move files"
}
|
245150
|
<p><a href="https://github.com/CascadeIllusion/DesmOEIS" rel="noreferrer">https://github.com/CascadeIllusion/DesmOEIS</a></p>
<p>Recently began work on a Python project called DesmOEIS to build up my portfolio. It's a simple console program that looks up integer sequences from the OEIS, parses them, and converts them into Desmos lists using the Desmos API.</p>
<p>The program works fine, I just want general feedback to make sure I'm doing things the right way (not just code-wise, but also in terms of project structuring). Unit tests succeeded on my end, but then again maybe I'm not building good unit tests.</p>
<p><strong>console.py</strong></p>
<pre><code>import sys
import webbrowser
from parsing import *
from desmos import *
from sequence import Sequence
def main():
intro = \
"DesmOEIS\n" \
"A tool for converting OEIS sequences to Desmos lists.\n" \
"\n" \
"Type id=<OEIS id> (without the brackets) to convert a sequence. \n" \
"Type help for a list of all valid commands. \n" \
"Type exit to close the application. \n" \
help = \
"\nSyntax: (Command Name)=(Argument)\n\n" \
"id: Attempts to convert an OEIS id argument into a Desmos list. \n" \
"The \"A\" is optional, and trailing zeros may be excluded.\n\n" \
\
"name: Assigns the resulting Desmos list to a variable with the given name. \n" \
"Names must be exactly one letter character (except \"e\"), no numbers or special characters.\n\n" \
\
"trim: Filters a list using Python-style slicing syntax. For A:B:C:\n" \
"A is the starting index (inclusive), default 0.\n" \
"B is the ending index (exclusive), default is the list length.\n" \
"C is a step value that is used to skip every C elements, default is 1 (don't skip anything).\n\n" \
\
"ext: Pass Y to this to output the extended version of the OEIS sequence.\n" \
"WARNING: Passing an entire extended sequence this way is usually not a good idea, as such\n" \
"sequences can be hundreds of elements long, and can cause your browser to hang. You may want\n" \
"to combine this with trimming syntax to reduce the number of elements.\n\n" \
\
"view: Opens the .html file containing the last converted sequence since starting the program. \n" \
"Does not work if used before converting a sequence.\n\n" \
\
"help: View a list of all valid commands.\n\n" \
\
"exit: Closes the application." \
print(intro)
file = None
while True:
cmd = input()
if cmd == "help":
print(help)
continue
if cmd == "view":
if file is None:
print("No sequence converted yet.")
continue
webbrowser.open(f"file://{os.path.realpath(file)}")
continue
if cmd == "exit":
sys.exit()
# Multiple commands are comma separated
cmds = cmd.split(', ')
cmds[-1] = cmds[-1].replace(',', '')
if not cmds[0].startswith("id"):
print("First argument must be id.")
continue
args = dict()
for i in cmds:
i = i.split("=")
cmd = i[0]
value = i[1]
args[cmd] = value
id = parse_id(args)
results = find_id(id)
if results:
sequence = Sequence(id)
sequence.args = args
sequence.results = results
else:
print("Invalid id.")
continue
sequence.integers = parse_integers(sequence)
name = sequence.args.get("name")
if name:
if len(name) > 1:
print("Variable names must be one character only.")
continue
if str.isdecimal(name) or name == 'e':
print("Numeric names and the constant e (2.71828...) are not allowed.")
continue
sequence.name = name
file = create_expression(sequence, create_desmos_list)
print("Sequence converted successfully! \n")
if __name__ == '__main__':
main()
</code></pre>
<p><strong>parsing.py</strong></p>
<pre><code>import requests
def parse_id(args):
id = args.get("id")
# Remove the preceding A if included
id = id.replace('A', '')
# Add trailing zeros if necessary
length = len(id)
if length < 6:
for i in range(0, 6 - length):
id = "0" + id
# Add A at the beginning of the query
id = 'A' + id
return id
def find_id(id):
url = f"https://oeis.org/search?q=id:{id}&fmt=text"
r = requests.get(url)
if "No results." in r.text:
return None
return r
def parse_integers(sequence):
text = sequence.results.text
text = str.splitlines(text)
rows = []
if sequence.args.get("ext") == "Y":
b_id = sequence.id.replace('A', 'b')
url = f"https://oeis.org/{sequence.id}/{b_id}.txt"
r = requests.get(url)
sequence.results = r
text = r.text
text = str.splitlines(text)
for line in text:
space = line.find(" ")
row = line[space + 1:]
row = row.split(', ')
rows.append(row)
else:
for line in text:
if line.startswith('%S') or line.startswith('%T') or line.startswith('%U'):
# integers start 11 characters into the line
row = line[11:]
row = row.split(',')
rows.append(row)
rows = [row for integer in rows for row in integer]
# Remove empty elements resulting from commas at the end of the %S and %T rows
rows = list(filter(None, rows))
trim = sequence.args.get("trim")
if trim:
if ":" not in trim:
print("Trim argument missing colons ( : ).")
return
trim = trim.split(":")
if not (trim[0] is "" or trim[1] is ""):
for i in trim:
if i.isdigit() and trim[0] >= trim[1]:
print("Start value must be less than the end value.")
return
if trim[0] is "":
trim[0] = '0'
if trim[1] is "":
trim[1] = len(rows)
for i in trim:
i = str(i)
if not i.isdigit():
print("Invalid input for trim argument.")
return
trim = list(map(int, trim))
start = trim[0]
end = trim[1]
if len(trim) == 3:
if trim[2] is 0:
print("Step value cannot be zero.")
return
step = trim[2]
rows = rows[start:end:step]
else:
rows = rows[start:end]
return rows
</code></pre>
<p><strong>desmos.py</strong></p>
<pre><code>import os
from sequence import Sequence
def create_expression(sequence, func):
graph = open("../resources/desmos_graph_base.html")
graph = graph.read()
expr = func(sequence)
# Add another placeholder comment below the expression to allow for further expressions
graph = graph.replace("<!-- PLACEHOLDER -->", f"{expr} \n <!-- PLACEHOLDER -->")
sequence.graph = graph
dir = "../graphs/"
if not os.path.exists(dir):
os.makedirs(dir)
filename = f"{dir}{sequence.id}.html"
out_graph = open(filename, "w")
out_graph.write(graph)
return filename
def create_desmos_list(sequence):
integers = sequence.integers
desmos_list = str(integers)
desmos_list = desmos_list.replace("'", "")
name = sequence.name
if sequence.args.get("name") is not None:
name = name + "="
else:
name = ""
expr = f"calculator.setExpression({{ id: 'graph1', latex:\"{name}{desmos_list}\" }});"
return expr
</code></pre>
<p><strong>sequence.py</strong></p>
<pre><code>class Sequence():
def __init__(self, id):
self._id = id
@property
def id(self):
return self._id
@property
def args(self):
return self._args
@args.setter
def args(self, args):
self._args = args
@property
def integers(self):
return self._integers
@integers.setter
def integers(self, integers):
self._integers = integers
@property
def results(self):
return self._results
@results.setter
def results(self, results):
self._results = results
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
</code></pre>
<p><strong>test_parsing.py</strong></p>
<pre><code>import unittest
from parsing import *
from sequence import *
"""
# Example sequences used:
http://oeis.org/A000045
http://oeis.org/A000047
http://oeis.org/A139827
"""
class TestIdParsing(unittest.TestCase):
def test_parse_id(self):
args = {"id": "A000045"}
self.assertEqual("A000045", parse_id(args))
def test_parse_id_no_prefix(self):
args = {"id": "000045"}
self.assertEqual("A000045", parse_id(args))
def test_parse_id_no_trailing_zeros(self):
args = {"id": "A45"}
self.assertEqual("A000045", parse_id(args))
def test_parse_id_no_trailing_zeros_no_prefix(self):
args = {"id": "45"}
self.assertEqual("A000045", parse_id(args))
def test_parse_id_six_digit(self):
args = {"id": "A139827"}
self.assertEqual("A139827", parse_id(args))
def test_parse_id_six_digit_no_prefix(self):
args = {"id": "139827"}
self.assertEqual("A139827", parse_id(args))
class TestIdFinding(unittest.TestCase):
def test_find_id_success(self):
id = "A000045"
self.assertNotEqual(None, find_id(id))
def test_find_id_fail(self):
id = "A123ABC"
self.assertEqual(None, find_id(id))
class TestIntegerParsing(unittest.TestCase):
def test_parse_integers(self):
args = {"": ""}
id = "A000045"
integers = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946,
17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578,
5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155]
integers = list(map(str, integers))
url = f"https://oeis.org/search?q=id:{id}&fmt=text"
r = requests.get(url)
sequence = Sequence(id)
sequence.integers = integers
sequence.results = r
sequence.args = args
self.assertEqual(integers, parse_integers(sequence))
# Use a different sequence because most extended sequences are too big to reasonably fit
def test_parse_integers_ext(self):
args = {"ext": "Y"}
id = "A000047"
integers = [1, 2, 3, 5, 8, 15, 26, 48, 87, 161, 299, 563, 1066, 2030, 3885, 7464, 14384, 27779, 53782, 104359,
202838, 394860, 769777, 1502603, 2936519, 5744932, 11249805, 22048769, 43248623, 84894767,
166758141, 327770275, 644627310, 1268491353, 2497412741, 4919300031, 9694236886, 19112159929]
integers = list(map(str, integers))
url = f"https://oeis.org/search?q=id:{id}&fmt=text"
r = requests.get(url)
sequence = Sequence(id)
sequence.integers = integers
sequence.results = r
sequence.args = args
self.assertEqual(integers, parse_integers(sequence))
if __name__ == '__main__':
unittest.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:50:46.533",
"Id": "481391",
"Score": "2",
"body": "Great first question!"
}
] |
[
{
"body": "<h2>Line continuations</h2>\n<p>Multi-line strings like this:</p>\n<pre><code>intro = \\\n "DesmOEIS\\n" \\\n "A tool for converting OEIS sequences to Desmos lists.\\n" \\\n "\\n" \\\n "Type id=<OEIS id> (without the brackets) to convert a sequence. \\n" \\\n "Type help for a list of all valid commands. \\n" \\\n "Type exit to close the application. \\n" \\\n</code></pre>\n<p>are better-represented as parenthesized expressions:</p>\n<pre><code>intro = (\n "DesmOEIS\\n" \n "A tool for converting OEIS sequences to Desmos lists.\\n" \n "\\n" \n "Type id=<OEIS id> (without the brackets) to convert a sequence.\\n" \n "Type help for a list of all valid commands.\\n" \n "Type exit to close the application.\\n" \n)\n</code></pre>\n<p>Also note that the second level of indentation should be at four spaces and not two.</p>\n<h2>Consider case-insensitive commands</h2>\n<p>It would be easy, and a user quality-of-life improvement, to compare strings against lowered input:</p>\n<pre><code>cmd = input().lower()\n</code></pre>\n<p>If you want to get really fancy you could implement unambiguous prefix string matching, i.e. <code>hel</code> would match <code>help</code>, but that is more advanced.</p>\n<h2>List parsing</h2>\n<p>Rather than this:</p>\n<pre><code> # Multiple commands are comma separated\n cmds = cmd.split(', ')\n</code></pre>\n<p>it would be safer to split only on a comma, and then strip every resulting entry.</p>\n<h2>Dictionary literals</h2>\n<pre><code>args = dict()\n</code></pre>\n<p>can be</p>\n<pre><code>args = {}\n</code></pre>\n<h2>Unpacking</h2>\n<pre><code> i = i.split("=")\n\n cmd = i[0]\n value = i[1]\n</code></pre>\n<p>can be</p>\n<pre><code>cmd, value = i.split('=')\n</code></pre>\n<h2>Replace or ltrim</h2>\n<pre><code># Remove the preceding A if included\nid = id.replace('A', '')\n</code></pre>\n<p>does not do what you say it does. It replaces 'A' <em>anywhere</em> in the string. Instead, consider <code>lstrip('A')</code> which removes any number of 'A' from the left, or if you want to be more precise, use regular expressions and <code>'^A'</code>.</p>\n<h2>Character repetition</h2>\n<pre><code> for i in range(0, 6 - length):\n id = "0" + id\n</code></pre>\n<p>can be</p>\n<pre><code>id = '0'*(6 - length) + id\n</code></pre>\n<h2>Requests parameters</h2>\n<pre><code>url = f"https://oeis.org/search?q=id:{id}&fmt=text"\nr = requests.get(url)\n</code></pre>\n<p>should use a dict argument to <code>params</code> instead of baking those into the URL; read\n<a href=\"https://2.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls\" rel=\"nofollow noreferrer\">https://2.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls</a></p>\n<h2>Requests checking for failure</h2>\n<p>Call <code>r.raise_for_status()</code> after your <code>get</code>. Otherwise the failure mode for HTTP requests will be hidden.</p>\n<h2>Pathlib</h2>\n<p>Consider the <code>pathlib.Path</code> alternatives to these calls:</p>\n<pre><code>if not os.path.exists(dir):\n os.makedirs(dir)\n</code></pre>\n<h2>Setters and getters</h2>\n<p>This kind of boilerplate:</p>\n<pre><code>@property\ndef args(self):\n return self._args\n\n@args.setter\ndef args(self, args):\n self._args = args\n</code></pre>\n<p>is somewhat unpythonic. <code>_args</code> is not a strictly private variable by anything other than convention. You are not gaining anything from these properties. Delete them and rename <code>_args</code> to <code>args</code> if you're going to let users modify this member.</p>\n<h2>Unit tests</h2>\n<p>Great; you have some! Consider mocking away <code>requests.get</code> in your tests; otherwise this could not strictly be considered a unit test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T19:51:41.557",
"Id": "481394",
"Score": "2",
"body": "`id` is a python builtin, so it shouldn't be used as a variable name. Padding the id with leading zeros can be done with an f-string: `f\"{seq_id:0>6s}\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T20:44:34.390",
"Id": "481397",
"Score": "0",
"body": "@RootTwo I've never once used `id`, the only time I've seen it used is to explain how `is` is different to `==`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T21:59:17.293",
"Id": "481403",
"Score": "1",
"body": "Wow, thanks a bunch for your feedback! I'm really glad I asked; I didn't know about some of the syntax tricks like with the unpacking or the character repetition. Also did not know about the request parameters either. Very, very much appreciated!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T22:01:05.300",
"Id": "481404",
"Score": "0",
"body": "@Peilonrayz it was in the original code. I was adding a comment to Reinderien's answer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T19:05:58.010",
"Id": "245154",
"ParentId": "245151",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "245154",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T18:39:39.733",
"Id": "245151",
"Score": "6",
"Tags": [
"python",
"parsing",
"unit-testing",
"console",
"web-scraping"
],
"Title": "Tool for converting OEIS sequences into Desmos lists"
}
|
245151
|
<p>I made a simple console basketball game using Java.</p>
<pre><code>/*
* Java Basketball
* by Clint
* 2020.07.08 | 3:59AM
* This Java program let's the player play basketball in console.
*/
import java.util.Random;
import java.util.Scanner;
public class Basketball {
static String[] shoot = {"1 POINT!", "2 POINTS!", "3 POINTS!", "MISSED!"};
static String player;
public static void main(String[] args) {
System.out.println("WELCOME TO JAVA CONSOLE BASKETBALL\n" +
"how to play:\n" +
"press \"s\" or type \"shoot\" to shoot the basketball.\n");
while (true) {
shootBall();
}
}
public static void shootBall() {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
int shot = random.nextInt(shoot.length);
System.out.print("SHOOT: ");
player = scanner.nextLine();
switch (player) {
case "s", "S", "shoot", "Shoot", "SHOOT" -> System.out.println(shoot[shot] + "\n");
default -> System.out.println("SHOOT THE BALL PROPERLY.\n");
}
}
}
</code></pre>
<p>ps: ik that there's <code>while (true)</code> in my code, but it's the thing that I know so far that keeps the programme running. I'm open for suggestions on how to improve my coding.</p>
|
[] |
[
{
"body": "<p>You only need one instance of <code>Random</code> and <code>Scanner</code> for the whole programm. Especially creating new instances of <code>Scanner</code> is bad, because it locks resources, that you never free by closing it.</p>\n<p>For the <code>switch</code> you are unnecessarily using the new expression syntax which is used when you want to return a value which you don't. The more conventional syntax would be:</p>\n<pre><code>switch (player) {\n case "s", "S", "shoot", "Shoot", "SHOOT":\n System.out.println(shoot[shot] + "\\n");\n break;\n default:\n System.out.println("SHOOT THE BALL PROPERLY.\\n");\n break;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T07:20:30.710",
"Id": "245169",
"ParentId": "245155",
"Score": "1"
}
},
{
"body": "<h2>Descriptive variable names</h2>\n<p>You have this:</p>\n<pre><code>player = scanner.nextLine();\n</code></pre>\n<p>Does the input reflect a player?</p>\n<p>I think a more descriptive name would be <code>playerInput</code>. That makes the switch more readable as well.</p>\n<h2>Make methods do one thing (single responsibility principle)</h2>\n<p>Your <code>shootBall</code> method does three things: asking for input, calculating the result, and printing the result. Ideally this would be split up:</p>\n<ul>\n<li><code>private String getInput()</code></li>\n<li><code>private String shootBall(String input)</code></li>\n<li><code>private String printResult(String result)</code></li>\n</ul>\n<p>This makes it easier to change the implementation of a responsibility and easier to read the logic of your program.</p>\n<p>The main while loop would become</p>\n<pre><code>while(true) {\n String input = getInput();\n String result = shootBall(input);\n printResult(result);\n}\n</code></pre>\n<p>This makes it easier for coding some exit value as well;</p>\n<pre><code>while (true) {\n String input = getInput();\n if (input.equals("QUIT"))\n break;\n String result = shootBall(input);\n printResult(result);\n} \n</code></pre>\n<p>Or, if you don't like the <code>while-true-break</code></p>\n<pre><code>String input;\nwhile (!(input = getInput()).equals("QUIT")) {\n printResult(shootBall(input));\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T11:07:55.410",
"Id": "481446",
"Score": "2",
"body": "`if (input.equals(\"QUIT\"))` - i thought you meant: `if(isQuitCommand(input))` ... nice answer +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T11:15:34.193",
"Id": "481447",
"Score": "2",
"body": "@MartinFrank yes, good suggestion!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T01:29:51.530",
"Id": "481507",
"Score": "0",
"body": "Thank you for the help. I made different methods for different parts of the program: https://pastebin.com/WfGrQtdV, how was it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T07:07:03.067",
"Id": "481520",
"Score": "1",
"body": "You should look into passing variables as method parameters :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T10:07:24.700",
"Id": "245176",
"ParentId": "245155",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T20:09:39.413",
"Id": "245155",
"Score": "4",
"Tags": [
"java",
"game",
"console"
],
"Title": "I made basketball program using Java that runs on console"
}
|
245155
|
<p>My main problems are making draw case and any player can choose a place which is chosen by another player here is the code :</p>
<pre><code>#include <iostream>
using namespace std;
char board[3][3] = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
static int turnnumber = 1 ;
bool winner = false, flag = false ;
bool win(){
if(board[0][0]==board[1][1]&&board[1][1]==board[2][2])
winner = true ;
if(board[0][2]==board[1][1]&&board[1][1]==board[2][0])
winner = true ;
if(board[1][0]==board[1][1]&&board[1][1]==board[1][2])
winner = true ;
if(board[0][0]==board[0][1]&&board[0][1]==board[0][2])
winner = true ;
if(board[2][0]==board[2][1]&&board[2][1]==board[2][2])
winner = true ;
if(board[0][0]==board[1][0]&&board[1][0]==board[2][0])
winner = true ;
if(board[0][1]==board[1][1]&&board[1][1]==board[2][1])
winner = true ;
if(board[0][2]==board[1][2]&&board[1][2]==board[2][2])
winner = true ;
if(winner==true&&turnnumber==1)
cout << "player2 won \n\n" ;
if(winner==true&&turnnumber==2)
cout << "player1 won \n\n" ;
return winner;
}
void view()
{
for (int i = 0; i < 3; i++)
{
for (int x = 0; x < 3; x++)
{
cout << "[" << board[i][x] << "] ";
}
cout << endl
<< "-------------" << endl;
}
}
void players()
{
char player1 = 'X', player2 = 'O';
int number;
cout << "\nplayer " << turnnumber << " it's your turn ";
if(turnnumber==1)
turnnumber++;
else if(turnnumber==2)
turnnumber--;
char player;
if(turnnumber==1)
player=player2;
if(turnnumber==2)
player=player1;
cin >> number ;
switch(number){
case 1:
board[0][0] = player;
break;
case 2:
board[0][1] = player;
break;
case 3:
board[0][2] = player;
break;
case 4:
board[1][0] = player;
break;
case 5:
board[1][1] = player;
break;
case 6:
board[1][2] = player;
break;
case 7:
board[2][0] = player;
break;
case 8:
board[2][1] = player;
break;
case 9:
board[2][2] = player;
break;
default:
cout << "\nwrong number\n";
players();
}
system("cls");
view();
if(!win())
players();
}
int main()
{
view();
players();
}
</code></pre>
|
[] |
[
{
"body": "<p>You can address both of the your problems using "struct".</p>\n<p>By making something like this:</p>\n<pre><code>struct myBorad \n{\n char board[3][3] = { {'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'} };\n bool bMyBoardStatus[9] = { false };\n};\nmyBorad g_myBoard;\n</code></pre>\n<p>You then need to change each of the fields as "taken" by setting them to "true".\nafter each player play.</p>\n<pre><code>g_myBoard.bMyBoardStatus[0] = true;\n</code></pre>\n<p>Now that you have this in place you can add two ifs:</p>\n<ol>\n<li>Check if the status of selected by player place is "taken" aka not false.</li>\n<li>Check if all the array aka all nine of them are true and you didn't meet the win condition yet that means its draw.</li>\n</ol>\n<p>there are more elegant solutions but this will help you get what you need, and this does not have to be in struct. i prefer this way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T22:16:27.577",
"Id": "481499",
"Score": "0",
"body": "Welcome to Code Review! Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they might make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are [tons of on-topic questions](https://codereview.stackexchange.com/questions/tagged/c%2b%2b?tab=Unanswered) to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T15:00:40.543",
"Id": "245190",
"ParentId": "245157",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T20:21:56.540",
"Id": "245157",
"Score": "1",
"Tags": [
"c++"
],
"Title": "tic tac toe code in c++ with two players"
}
|
245157
|
<p>I've spent some time on this as an answer elsewhere, and did my best to optimize it. But looking at the hill of indents seems like this can be improved. I've tried to implement an <code>any()</code> statement to replace the <code>for</code> <code>break</code> part, without any luck. Does anyone have any suggestions?</p>
<pre><code>Groups = [[['NM1', 'OP', '1', 'SMITH', 'JOHN', 'PAUL', 'MR', 'JR'],
['ABC', '1L', '690553677'],
['DIR', '348', 'D8', '20200601'],
['DIR', '349', 'D8', '20200630']],
[['NM1', 'OP', '1', 'IMA', 'MEAN', 'TURD', 'MR', 'SR'],
['ABC', '1L', '690545645'],
['ABC', '0F', '001938383',''],
['DIR', '348', 'D8', '20200601']]]
def ids(a, b):
l = []
for group in Groups:
for lst in group:
if lst[0] == a and lst[1] == b:
if lst[2] == 'D8':
l.append(lst[3])
else:
l.append(lst[2])
break
else:
l.append(None)
return l
current_id = ids('ABC', '1L')
prior_id = ids('ABC', '0F')
start_date = ids('DIR', '348')
end_date = ids('DIR', '349')
print(current_id)
print(prior_id)
print(start_date)
print(end_date)
</code></pre>
<p>Output:</p>
<pre><code>['690553677', '690545645']
[None, '001938383']
['20200601', '20200601']
['20200630', None]
</code></pre>
<p>So basically, I have this <code>Groups</code> list, in that list are 2 nested lists. <br>Assuming the output lists are <code>[x, y]</code>, the first nested list in <code>Groups</code> is <code>x</code>, and the second is <code>y</code>.</p>
<p>You see my function has two parameters, <code>a</code> and <code>b</code>. <br><code>x</code> and <code>y</code> are determined when their corresponding nested list has a list that has <code>a</code> as the first index, and <code>b</code> as the second index.</p>
<p>If the nested list doesn't have a list that meets that requirement, the <code>x</code> or <code>y</code> will be <code>None</code>.</p>
<hr />
<p>UPDATE: Is there any way to flatten the series of indents? At least a few?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T02:00:24.397",
"Id": "481414",
"Score": "1",
"body": "Can you provide some context, like what this program does and other background information?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T02:31:03.340",
"Id": "481416",
"Score": "0",
"body": "@Linny I've added more context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:00:45.380",
"Id": "481420",
"Score": "2",
"body": "please provide a) the full description of the data format; b) a description of what you were supposed to implement. we need both to check if your implementation is correct and to review whether there are better implementations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:19:22.243",
"Id": "481423",
"Score": "0",
"body": "flatten - depends on your assignment. is the `None` output required?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:20:04.330",
"Id": "481424",
"Score": "0",
"body": "@stefan That's right."
}
] |
[
{
"body": "<h1>Type Hints</h1>\n<p>Use these to direct users what types of values your functions accept, and what types of values are returned.</p>\n<pre><code>from typing import List\n\ndef ids(a: str, b: str) -> List[str]:\n ...\n</code></pre>\n<h1>Meaningful names</h1>\n<p>I would rename <code>l</code> to <code>results</code>, as that better demonstrates what you're returning.</p>\n<p>You code now looks something like this:</p>\n<pre><code>from typing import List\n\ngroups = [\n [\n ['NM1', 'OP', '1', 'SMITH', 'JOHN', 'PAUL', 'MR', 'JR'],\n ['ABC', '1L', '690553677'],\n ['DIR', '348', 'D8', '20200601'],\n ['DIR', '349', 'D8', '20200630']\n ],\n [\n ['NM1', 'OP', '1', 'IMA', 'MEAN', 'TURD', 'MR', 'SR'],\n ['ABC', '1L', '690545645'],\n ['ABC', '0F', '001938383',''],\n ['DIR', '348', 'D8', '20200601']\n ]\n]\n\ndef ids(a: str, b: str) -> List[str]:\n results = []\n for group in groups:\n for lst in group:\n lst = list(filter(None, lst))\n if lst[:2] == [a, b]:\n results.append(lst[-1])\n break\n else:\n results.append(None)\n return results\n\nif __name__ == '__main__':\n\n current_id = ids('ABC', '1L')\n prior_id = ids('ABC', '0F')\n start_date = ids('DIR', '348')\n end_date = ids('DIR', '349')\n\n print(current_id)\n print(prior_id)\n print(start_date)\n print(end_date)\n</code></pre>\n<p><em>Spaced out <code>groups</code> so I could understand the layout easier.</em></p>\n<h1>List slicing</h1>\n<p>Instead of checking the first two elements with different checks, slice the array and check that array against an array of the passed elements.</p>\n<h1>Simpler checking</h1>\n<p>Since you want to add the last element, instead of checking the length of the array then appending a specific index, just append the last element using <code>[-1]</code>.</p>\n<h1>Filtering</h1>\n<p>I noticed there was a <code>''</code> at the end of one of the lists. If you expect this type of data, you should filter it out since it isn't involved with the rest of the function.</p>\n<pre><code>lst = list(filter(None, lst))\n</code></pre>\n<p>This filters out every None type value in <code>lst</code>. Since an empty string is a None type, it gets removed.</p>\n<h1>Main Guard</h1>\n<p>This prevents the outside code from running if you decide to import this from another file / program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T03:16:24.887",
"Id": "481418",
"Score": "0",
"body": "Is importing `List` necessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T03:50:05.770",
"Id": "481419",
"Score": "0",
"body": "@user227321 For type hinting, yes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T02:52:57.203",
"Id": "245164",
"ParentId": "245163",
"Score": "0"
}
},
{
"body": "<p>As we do not know the task given we cannot fully review. While the code itself looks reasonable there is some smell.</p>\n<h1>date</h1>\n<p>To me it is very smelly, that a function named <code>id()</code> returns a date</p>\n<pre><code>start_date = ids('DIR', '348')\n</code></pre>\n<p>This is also requiring a switch inside your function, so most probably there are two functions intermingled that should not be.</p>\n<h1>data structure</h1>\n<p><code>list()</code> is a bad structure to search in. While this may be the data format you read or get passed, you most probably should convert it to a structure allowing direct lookup (converting once). The description of the current structure is missing, also we do not know if there are other functions accessing the data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:26:43.767",
"Id": "481425",
"Score": "0",
"body": "Why is `['690553677', '690545645']` a date?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T04:38:14.233",
"Id": "481426",
"Score": "0",
"body": "I did not claim that. Your code (see in my answer) clams that for a specifiq query. As we are still missing description of data and task I cannot say if the name is wrong or the implementation. But one is wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T13:58:51.283",
"Id": "481468",
"Score": "0",
"body": "In your answer: *\"`id()` returns a date\"*."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T03:52:30.177",
"Id": "245165",
"ParentId": "245163",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T01:32:43.600",
"Id": "245163",
"Score": "1",
"Tags": [
"python",
"performance",
"comparative-review"
],
"Title": "Looking at the hill of indents seems like this can be improved"
}
|
245163
|
<p>I need to log in users to web app in Javascript and PHP. So I have Javascript interface which send me accessToken to PHP which stores users data to DB and log user in. But the result code does not look like OOP but like a peace of garbage. May be I dont know how to write that code, so the question is if this peace of PHP code is ok or if it is possible to rewrite it to real OOP. Cause OOP exists because of people who use the code. It should make sense for humans. It seems this make sense only for authors of the code.</p>
<pre><code>$code = $_POST['code'];
try
{
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/../model/JsonData/GoogleCredentials.json');
$client->setRedirectUri( self::REDIRECT_URI );
$accessToken = $client->fetchAccessTokenWithAuthCode( $code );
$client->setAccessToken( $accessToken );
$peopleService = new \Google_Service_PeopleService( $client );
$me = $peopleService->people->get('people/me', ['personFields' => 'emailAddresses,names,metadata,coverPhotos']); // This is extra feature which does not accept spaces....
}
catch ( \Exception $e )
{
Debugger::log( $e );
$this->sendJson( array( 'errCode' => 1, 'error' => 'Log in fails.' ) );
}
/** @var \Google_Service_PeopleService_EmailAddress $email */
foreach ( $me->getEmailAddresses() as $email )
{
if ( $email->getMetadata()->getPrimary() ) $user_email = $email->value; // Oh really? I want to log in user....
}
/** @var \Google_Service_PeopleService_Name $name */
foreach ( $me->getNames() as $name )
{
if ( $email->getMetadata()->getPrimary() ) $user_name = $name->displayName;
}
if ( ! isset( $user_email ) ) $this->sendJson( array( 'errCode' => 0, 'error' => 'Email is required.' ) );
if ( ! isset( $user_name ) ) $this->sendJson( array( 'errCode' => 0, 'error' => 'Name is required' ) );
// Hello ID is missing. How to uniquely identify user?
</code></pre>
<p>May be I am wrong but is it possible to write it better way to get relevant data for log in? Where is ID which can uniquely identify user?</p>
<p>Look at this JS interface. This looks like OOP <a href="https://developers.google.com/identity/sign-in/web/people" rel="nofollow noreferrer">https://developers.google.com/identity/sign-in/web/people</a></p>
|
[] |
[
{
"body": "<p>If I had to make this OOP, I'd begin by hedging concerns :</p>\n<ul>\n<li>a class for user data handling (retrieving the POST and using it)</li>\n<li>a service (that you'd dependency inject) to handle the configuration of the Google Service</li>\n<li>a <code>GoogleUser</code> class for encapsulating the result of the service and abstracting all those <code>foreach</code></li>\n</ul>\n<p>Then, orchestrate those in some kind of controller (I guess you have already since you use a <code>$this->sendJson</code> method)</p>\n<p>I like custom Exception cascade but that's just me :</p>\n<pre><code>try{\n //everything working well\n}catch(GoogleLoginException $e){\n}catch(RequiredEmailException $e){\n}catch(RequiredNameException $e){\n}\n</code></pre>\n<p>GoogleSDK is notoriously verbose and looks a lot like enterprise java and is always a pain to make elegant.</p>\n<p>In the end you'd have something like :</p>\n<pre><code>\nclass LoginController{\n private $google;\n\n public function __construct(GoogleService $google){\n $this->google = $google;\n }\n\n public function oauthCallbackAction($postRequest){\n $code = $postRequest->get("code");\n try{\n $authentifiedClient = $google->authentifiedClientWithCode($code);\n $googleUser = $authentifiedClient->getMe();\n return $this->json([\n "user_name" => $googleUser->getUserName(),\n "email" => $googleUser->getEmail(),\n ], 200);\n }catch(GoogleAuthException $e){ //thrown by GoogleService\n return $this->json("blah", 500);\n }catch(RequiredEmailException $e){ //thrown by GoogleUser::getEmail\n return $this->json("gimme email !", 400);\n }catch(RequiredNameException $e){ //thrown by GoogleUser::getUserName\n return $this->json("gimme name !", 400);\n }\n\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T09:33:01.260",
"Id": "481440",
"Score": "0",
"body": "No this is not the point. Cause if it will be necessary to encapsulate all packages and its classes to another classes I end up with huge number of classes. It is not the goal of OOP."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T09:39:01.777",
"Id": "481441",
"Score": "1",
"body": "Having a huge number of class is precisely the goal of OOP : each class should do a single thing and that thing well, and in the end, the orchestrator should be human readable because classes reflects the \"business\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T14:48:08.723",
"Id": "481473",
"Score": "0",
"body": "I dont think so. Every package should have its internal classes separated inside and give user public interface which will be readable by humans. This is not the case.... This is what we call haystack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T04:24:29.597",
"Id": "481510",
"Score": "1",
"body": "@Čamo public interface should be first of all easy to consume. The Google api is not easy to consume, that's why it Is a good idea to encapsilate it in a specialized interface that will be easy to consume by your specialized controller/service. You're asking for OOP approach, then dismiss the approach as unsuitable. What is it exactly that you want?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T07:12:22.143",
"Id": "481521",
"Score": "0",
"body": "What I want is to force people to use their brains if they produces code for others. Look at that Javascript example. Thats what I want."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T16:15:15.333",
"Id": "481558",
"Score": "0",
"body": "@Čamo the javascript you're linking adopt a functionnal approach with callbacks. That's not really OOP. You could try to build such an architecture (maybe even asynchronously !) using PHP (PHP 7.4 has bells and whistles to help you do that)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T09:26:38.400",
"Id": "245174",
"ParentId": "245171",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T07:57:58.410",
"Id": "245171",
"Score": "1",
"Tags": [
"php",
"object-oriented"
],
"Title": "Google People PHP best practise to get OOP"
}
|
245171
|
<p>I am new to programming and have been taking the time to learn C# by reading, doing some classes online for Unity, and using Youtube. I think you learn more from doing your own projects so I decided to write a program that asked the user to enter a movie they have not seen and then store the movie titles into a list and print out the movies they listed. I had problems getting it to take multiple movies but finally figured a way to do it but I believe there is a better way to write the program. So just asking general advice to improve upon what I have already written. Thank you.</p>
<pre><code> using System;
using System.Collections.Generic;
namespace MovieListProjectWithSwitch
{
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Enter a movie you want to see but have not seen it");
var movieNotSeen = new List<string>();
movieNotSeen.Add(Console.ReadLine());
Console.WriteLine("Do you want to enter another movie? Y/N?");
const string answerYes = "y";
const string answerNo = "n";
string userInput;
while (true)
{
userInput = Console.ReadLine().ToLower();
switch (userInput)
{
case answerYes:
{
Console.WriteLine("Enter your next movie you wish to add to the list");
movieNotSeen.Add(Console.ReadLine());
Console.WriteLine("Now the movies on your list are:");
Console.WriteLine();
foreach (var movie in movieNotSeen)
Console.WriteLine(movie);
Console.WriteLine();
Console.WriteLine("Enter another movie? Y/N?");
var userInput2 = Console.ReadLine().ToLower();
if (userInput2 == "y")
{
goto case answerYes;
}
else
{
goto case answerNo;
}
}
case answerNo:
{
Console.WriteLine("Your movies in your list are:\n");
foreach (var movies in movieNotSeen)
Console.WriteLine(movies);
return;
}
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T11:56:11.023",
"Id": "481450",
"Score": "1",
"body": "An example of a better title might be \"List the movies I haven't seen\"."
}
] |
[
{
"body": "<p>Welcome to codereview. Here are my suggestions:</p>\n<h3>Functional decomposition and Naming</h3>\n<p>The trickiest part of programming is to decouple your complex problem into smaller easier (sub)problems. It is easier to tackle small and focused problems than one large and vague. So, my first suggestion would be to try to find small and independent pieces of functionalities.</p>\n<p>In your case here is one way to decompose:</p>\n<ul>\n<li>Ask for a movie and store it</li>\n<li>Ask for continuation</li>\n<li>Print out the already gathered movies</li>\n</ul>\n<p>You can directly map these to functions:</p>\n<pre><code>void EnterANewMovieAndStoreIt()\nbool WishToContinue()\nvoid PrintOutMovies()\n</code></pre>\n<p>Then you can compose them like this:</p>\n<blockquote>\n<p><em>Ask</em> for a movie and store it <strong>then</strong><br />\n<em>Print</em> out the already gathered movies <strong>until</strong><br />\nthe consumer <em>Answers</em> with yes for continuation<br />\n<strong>when</strong> (s)he <em>Answers</em> with no then <em>Print</em> out already gathered movies</p>\n</blockquote>\n<p>With that in hand your <code>Main</code> function will look like this:</p>\n<pre><code>static void Main(string[] args)\n{\n do\n {\n EnterANewMovieAndStoreIt();\n\n PrintOutMovies();\n\n } while (WishToContinue());\n\n PrintOutMovies();\n}\n</code></pre>\n<h3>Store and Retrieve functionalities</h3>\n<p>Because we have separated storage and retrieval functionalities that's why they can be really small and concise functions:</p>\n<pre><code>private static void EnterANewMovieAndStoreIt()\n{\n Console.WriteLine();\n Console.WriteLine("Please enter a movie you want to see but have not seen it yet.");\n var movieName = Console.ReadLine();\n ToBeWatchedMovies.Add(movieName);\n}\n\nprivate static void PrintOutMovies()\n{\n Console.WriteLine();\n Console.WriteLine("Your haven't seen but to be watched movies:");\n foreach (var movie in ToBeWatchedMovies)\n Console.WriteLine(movie);\n}\n</code></pre>\n<p>As you can see they rely on a shared resource called <code>ToBeWatchedMovies</code>. It is defined on a class level like this: <code>static readonly List<string> ToBeWatchedMovies = new List<string>();</code></p>\n<h3>Error handling</h3>\n<p>Your current implementation does not handle that case when the user enters something different then Y or N. It is a good practice to assume that a <code>userInput</code> can be anything and handle that accordingly. In this example we can easily ask them nicely to try to provide the answer again.</p>\n<p>So, the <code>WishToContinue</code> would look like this:</p>\n<pre><code>private static bool WishToContinue()\n{\n while(true)\n {\n Console.WriteLine();\n Console.WriteLine("Do you want to enter another movie? Y/N?");\n var userInput = Console.ReadLine();\n\n if (string.Equals(userInput, AnswerYes, StringComparison.OrdinalIgnoreCase))\n return true;\n\n if (string.Equals(userInput, AnswerNo, StringComparison.OrdinalIgnoreCase))\n return false;\n\n Console.WriteLine($"Please provide either '{AnswerYes}' or '{AnswerNo}' ");\n }\n}\n</code></pre>\n<p>Obviously this code could be further optimized but my main point here is that you should try to handle the wrong inputs as well.</p>\n<hr />\n<p>Let's put everything together:</p>\n<pre><code>class Program\n{\n static readonly List<string> ToBeWatchedMovies = new List<string>();\n const string AnswerYes = "y", AnswerNo = "n";\n static void Main(string[] args)\n {\n do\n {\n EnterANewMovieAndStoreIt();\n\n PrintOutMovies();\n\n } while (WishToContinue());\n\n PrintOutMovies();\n }\n\n private static void EnterANewMovieAndStoreIt()\n {\n Console.WriteLine();\n Console.WriteLine("Please enter a movie you want to see but have not seen it yet.");\n var movieName = Console.ReadLine();\n ToBeWatchedMovies.Add(movieName);\n }\n\n private static void PrintOutMovies()\n {\n Console.WriteLine();\n Console.WriteLine("Your movies in your list are:");\n foreach (var movie in ToBeWatchedMovies)\n Console.WriteLine(movie);\n }\n\n private static bool WishToContinue()\n {\n while(true)\n {\n Console.WriteLine();\n Console.WriteLine("Do you want to enter another movie? Y/N?");\n var userInput = Console.ReadLine();\n\n if (string.Equals(userInput, AnswerYes, StringComparison.OrdinalIgnoreCase))\n return true;\n\n if (string.Equals(userInput, AnswerNo, StringComparison.OrdinalIgnoreCase))\n return false;\n\n Console.WriteLine($"Please provide either '{AnswerYes}' or '{AnswerNo}' ");\n }\n }\n}\n</code></pre>\n<p>I hope this helped you a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T10:24:37.950",
"Id": "245178",
"ParentId": "245175",
"Score": "22"
}
},
{
"body": "<p>One of the things you might want to consider as an extension to this program is to store the list of movies in a file and read the list back from a file. Also there should be a way to delete movies once they have been seen. Any other suggestions I would give have already been given in another review.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T12:03:52.513",
"Id": "245179",
"ParentId": "245175",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "245178",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T09:30:59.517",
"Id": "245175",
"Score": "9",
"Tags": [
"c#"
],
"Title": "List the movies I haven't seen"
}
|
245175
|
<p>I'm beginning (for the third time in 5 years) to learn Haskell and decided to do a "More or less" console game (game pick a random number, you then have to guess which).</p>
<p>First the code, then my question :</p>
<pre class="lang-hs prettyprint-override"><code>import System.Random
import Text.Read(readMaybe)
main :: IO ()
main = do
gen <- getStdGen
let maxSecret = 1000
let (secret, newGen) = randomR (1,maxSecret) gen :: (Int, StdGen)
-- putStrLn $ show secret
let oracle = compareToSecret secret
askForNumber oracle 1 (1, maxSecret)
data Guess = SecretIsLess | SecretIsMore | Win deriving (Show)
askForNumber :: (Int -> Guess) -> Int -> (Int, Int) -> IO ()
askForNumber oracle tries range = do
let (min, max) = range
putStrLn $ "Guess the number between " ++ (show min) ++ " and " ++ (show max) ++ " !"
guessInput <- getLine
let guess = readMaybe guessInput :: Maybe Int
case (oracle) <$> guess of
Just SecretIsMore -> do
putStrLn "Guess more !"
askForNumber oracle (tries+1) (maybe min id guess, max)
Just SecretIsLess -> do
putStrLn "Guess less !"
askForNumber oracle (tries+1) (min, maybe max id guess)
Just Win -> do
putStrLn "You win !"
putStrLn $ "It took you " ++ (show tries) ++ " tries."
return ()
Nothing -> do
putStrLn "That is not a number"
askForNumber oracle tries range
compareToSecret :: Int -> Int -> Guess
compareToSecret secret guess
| secret > guess = SecretIsMore
| secret < guess = SecretIsLess
| secret == guess = Win
</code></pre>
<p>I'd like to improve that code to make it idiomatic and learn in the process.</p>
<p>I made a choice : at first I had<br />
<code>compareToSecret :: Int -> Int -> (Guess, Int)</code><br />
and in the <code>case of</code> I had something like<br />
<code>Just (SecretIsMore, newmin) -> do askForNumber oracle (tries+1) (newmin, max)</code></p>
<p>Do you think it's better to kind of unpack with <code>maybe</code> there or to pass the value around and keep it pure ? Or is there another solution ?</p>
|
[] |
[
{
"body": "<h1>Prelude</h1>\n<p>I think your code (sans bug) is fine. Your question is already a little nit-picky so my comments will mostly be nit-picks. I am not a Haskell expert either, so don't place too much authority in my comments. Evaluate them for yourself.</p>\n<p>My comments are in a somewhat arbitrary order, but I've organized them with headers. The section pertaining specifically to your question is titled "What to do with the <code>case</code>".</p>\n<p>The revised code is included at the end.</p>\n<h1>The <code>Guess</code> datatype</h1>\n<p>A datatype that is used precisely like this already exists, it's called <a href=\"https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Ord.html#t:Ordering\" rel=\"nofollow noreferrer\"><code>Ordering</code></a> and can be found in <code>Data.Ord</code> (although I believe it's included by default). No need to reinvent the wheel here. Especially because you'll see later that you can use already-made functions that work with <code>Ordering</code>.</p>\n<h1>Input validation</h1>\n<p>You correctly check that the input is a well-formed number, but you don't check that it's between the min and max value of the range. Here's an example of how this bug manifests itself.</p>\n<pre><code>Guess the number between 1 and 1000 !\n50\nGuess more !\nGuess the number between 50 and 1000 !\n20\nGuess more !\nGuess the number between 20 and 1000 !\n</code></pre>\n<p>Notice how the value goes down. The fix, which I will put in the section addressing your questions about <code>Maybe</code>, is to add another case that deals with a well-formed, but invalid guess.</p>\n<h1>Syntax and other small details</h1>\n<p><code>min</code> and <code>max</code> are built-in functions, it's best not to shadow them. I would call them <code>minValue</code> and <code>maxValue</code>.</p>\n<p>You can pattern match in function definitions so that you don't need to unpack <code>range</code> – you can instead have</p>\n<pre class=\"lang-hs prettyprint-override\"><code>askForNumber oracle tries (minValue, maxValue) = do\n...\n</code></pre>\n<p>Function application has the highest precedence in Haskell, so you don't need parens around <code>(show min)</code>. <code>(oracle) <$> guess</code> doesn't need the parens either.</p>\n<p><code>maybe value id = fromMaybe value</code>, so use that instead. You can get <code>fromMaybe</code> from <code>Data.Maybe</code>, but it might be included by default.</p>\n<h1><code>oracle</code></h1>\n<p>If you switch to using <code>Ordering</code>, you can nix your <code>compareToSecret</code> function and define <code>oracle = compare secret</code>.</p>\n<h1>What to do with the <code>case</code></h1>\n<p>I think it's kind of clunky to extract a value from a <code>Maybe</code> after you've cased on it, which is what you're doing right now. A big utility of <code>case</code> is knowing that your value must be of a certain form in each branch. In that branch, <code>guess</code> must be of the form <code>Just _</code>. While you as a programmer know this to be true, it's much more helpful to have the type system be able to prove this.</p>\n<p>As I see it, there are two ways to handle your <code>case</code> statement.</p>\n<p>The first is to have two nested <code>case</code> statements. The first branches on <code>guess</code>. If <code>guess</code> is <code>Nothing</code>, it prompts the user for another input. If <code>guess</code> is <code>Just g</code>, it cases on <code>oracle g</code>.</p>\n<p>The second is to do a slight modification of what you're doing. Instead of <code>fmap</code>ping <code>oracle</code>, you can <code>fmap</code> the function <code>\\g -> (oracle g, g)</code>. This allows you to extract the guess safely without having to use <code>Maybe</code>. I believe this is what you were doing originally.</p>\n<p>I prefer to avoid nesting <code>case</code>s when I can, so I opted for the second one.</p>\n<p>If you would also like to validate the input (I chose to), then you will want to add a case at the beginning matching <code>Just (_, guess)</code> – i.e. one that ignores the comparison – to deal with invalid guesses. This pattern, however, will match both invalid and valid guesses. We need to add a guard that asserts that <code>guess > max</code> or <code>guess < min</code>. This looks like:</p>\n<pre class=\"lang-hs prettyprint-override\"><code> ...\n Just (_, guess) | guess < min || guess > max -> do\n putStrLn "Guess out of range"\n askForNumber oracle tries range\n ...\n</code></pre>\n<h1>Small note on using <code>oracle</code></h1>\n<p>I use the function <code>\\g -> (oracle g, g)</code> which might feel slightly clunky. Indeed, there are a few alternatives, but I warn you that they are somewhat arcane. In general, I would avoid using "cute" or "slick" code like this unless you know everyone who sets eyes on the code will understand it.</p>\n<p>All of the below are equivalent (for your use case):</p>\n<pre><code>\\g -> (oracle g, g) -- plain definition\noracle &&& id -- (&&&) needs to be imported from Control.Arrow\n(,) =<< oracle -- using the Reader Monad\n(,) <$> oracle <*> id -- using the Reader Applicative\n</code></pre>\n<p>I would be most inclined to use <code>oracle &&& id</code> because it'd be the most recognizable, but even it is a little arcane. I pretty much only included the last example because you'll see code that looks like <code>f <$> g <*> h <*> i …</code> a lot; it's a common idiom for other <code>Applicative</code>s (but I would advise against using it in this case). No matter what people say or do, there's nothing wrong with writing "plain" or "simple" Haskell.</p>\n<h1>Revised code</h1>\n<p>You'll find that not too much is different.</p>\n<pre class=\"lang-hs prettyprint-override\"><code>import System.Random \nimport Text.Read (readMaybe)\n\nmain :: IO ()\nmain = do \n gen <- getStdGen\n let maxSecret = 1000\n let (secret, newGen) = randomR (1,maxSecret) gen :: (Int, StdGen)\n\n -- putStrLn $ show secret\n let oracle = compare secret\n askForNumber oracle 1 (1, maxSecret)\n\naskForNumber :: (Int -> Ordering) -> Int -> (Int, Int) -> IO ()\naskForNumber oracle tries range@(minValue, maxValue) = do\n putStrLn $ "Guess the number between " ++ show minValue ++ " and " ++ show maxValue ++ " !"\n guessInput <- getLine\n let guessMaybe = readMaybe guessInput :: Maybe Int\n\n case (\\guess -> (oracle guess, guess)) <$> guessMaybe of \n Nothing -> do\n putStrLn "That is not a number"\n askForNumber oracle tries range\n Just (_, guess) | guess < minValue || guess > maxValue -> do\n putStrLn "Guess out of range"\n askForNumber oracle tries range\n Just (LT, guess) -> do\n putStrLn "Guess less !"\n askForNumber oracle (tries+1) (minValue, guess)\n Just (GT, guess) -> do\n putStrLn "Guess more !"\n askForNumber oracle (tries+1) (guess, maxValue)\n Just (EQ, _) -> do\n putStrLn "You win !"\n putStrLn $ "It took you " ++ (show tries) ++ " tries."\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T04:39:16.810",
"Id": "481618",
"Score": "0",
"body": "Thanks a lot ! In my first version I had indeed two nested cases, one dealing with the user error and the other inside the `Just` match but that was clunky to edit since you have to respect indentation and I spent more time reindenting than actually thinking :) Your answer regarding the \"maybe unpacking\" is the perfect middle ground between the two options I thought of ! (and I learned in the proces)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T08:16:08.340",
"Id": "481630",
"Score": "0",
"body": "Glad to help; you’ll find that casing on tuples like this, though seemingly clunky at first, oftentimes cleans up the code a decent deal. Especially when you reach the point in a code base where you have to have a lot of nested `case`s."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T01:35:52.937",
"Id": "245255",
"ParentId": "245177",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245255",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T10:17:24.393",
"Id": "245177",
"Score": "3",
"Tags": [
"beginner",
"haskell"
],
"Title": "Should I unpack a Maybe with maybe or pass value around"
}
|
245177
|
<p>I searched on the internet for an algorithm for permutations in C and I found the following function:</p>
<pre><code>void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf("%s\n", a);
else
{
for (i = l; i <= r; i++)
{
swap((a + l), (a + i));
permute(a, l + 1, r);
swap((a + l), (a + i)); //backtrack
}
}
}
</code></pre>
<p>The link to the page is: <a href="https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/" rel="noreferrer">https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/</a></p>
<p>The function looks elegant and short but quite frankly, I don't understand how it works, so I decided to implement my own understanding of the problem and came up with the following code:</p>
<pre><code>#include <stdio.h>
#include <string.h>
void fn(char *str, int k, int n);
int main(void)
{
char str[] = "abcd";
fn(str, strlen(str), strlen(str));
return 0;
}
void swap(char *a, char *b)
{
char tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
void fn(char *str, int k, int n)
{
for (int i = 1; i <= k; i++)
{
if (i == 1)
{
puts(str);
}
else
{
for (int j = 1; j < i; j++)
{
if (i == n)
putchar('\n');
swap(str + n - i, str + n - i + j);
fn(str, i - 1, n);
swap(str + n - i, str + n - i + j);
}
}
}
}
</code></pre>
<p>My question is, should I be using that function or my function? Is there any advantage to that function over my function, given that my function has two loops?</p>
|
[] |
[
{
"body": "<blockquote>\n<p>should I be using that function or my function?<br />\nIs there any advantage to that function over my function, given that my function has two loops?</p>\n</blockquote>\n<p>Let us look at each.</p>\n<p><strong>The l with it</strong></p>\n<p>See any problem with <code>swap((a+1), (a+i));</code>? That code swaps the wrong elements. Correct code, like what is posted, is <code>swap((a+l), (a+i));</code>. Moral of the story. Do not use an object called <code>l</code>. Too easy to confuse with <code>1</code>. Makes review unnecessarily difficult - even when code is right.</p>\n<p>Advantage: OP</p>\n<p><strong>Unneeded <code>()</code></strong></p>\n<p>Both below are the same. One <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">drier</a> than the other.</p>\n<pre><code>swap((a+l), (a+i));\nswap(a+l, a+i);\n</code></pre>\n<p>Advantage: OP</p>\n<p><strong>Check the zero case</strong></p>\n<p>Both work well enough with <code>""</code> (does not print anything), yet original code could have trouble with <code>permute("", 0, strlen("") - 1);</code> given <code>strlen("") - 1</code> is <code>SIZE_MAX</code>.</p>\n<p>The <code>""</code> case deserves explicit definition. I could see <code>f("")</code> printing one line of nothing - after all 0! is 1.</p>\n<p>Advantage: OP</p>\n<p><strong>Check the wide case</strong></p>\n<p>With very long strings, longer than <code>INT_MAX</code>, code breaks down as <code>int</code> is insufficient whereas <code>size_t</code> is best for array indexing. Yet time to print such a set of permutations is many times the <a href=\"https://en.wikipedia.org/wiki/Age_of_the_universe\" rel=\"nofollow noreferrer\">age of the universe</a>, so we will set aside this concern.</p>\n<p>Advantage: Neither.</p>\n<p><strong>Not <code>const</code></strong></p>\n<p>More useful to have a function that does not require a <code>char *</code>, but can work with a <code>const char *</code></p>\n<p>Advantage: Neither.</p>\n<p><strong>Functional difference!: Extra lines</strong></p>\n<p>OP's code for <code>"abc"</code> prints the below. Original code does not print the extraneous empty lines</p>\n<pre><code>abc\nacb\n\nbac\nbca\n\ncba\ncab\n</code></pre>\n<p>Suggest dropping the <code>if (i == n) putchar('\\n');</code></p>\n<p>Advantage: Original</p>\n<p><strong>Repeated test within loop</strong></p>\n<p>Why test for <code>k==1</code> repeatedly? Perhaps</p>\n<pre><code>void fn(char *str, int k, int n) {\n if (k >= 1) {\n puts(str);\n for (int i = 2; i <= k; i++) {\n for (int j = 1; j < i; j++) {\n swap(str + n - i, str + n - i + j);\n fn(str, i - 1, n);\n swap(str + n - i, str + n - i + j);\n }\n }\n }\n}\n</code></pre>\n<p>Advantage: Original</p>\n<p><strong>Function name, parameter names</strong></p>\n<p>Both are wanting in their declaration. <code>fn</code> is not an informative name for printing string permutations. What is <code>k</code>? How it should be called lacks guidance on correct usage.</p>\n<pre><code>void permute(char *a, int l, int r) {\nvoid fn(char *str, int k, int n) {\n</code></pre>\n<p>Perhaps instead a wrapper function? Then make <code>permute(), fn()</code> <code>static</code>.</p>\n<pre><code>void print_str_permute(char *str) {\n int length = (int) strlen(str); \n permute(str, 0, length - 1); \n // or \n fn(str, length, length);\n}\n</code></pre>\n<p>Advantage: Original</p>\n<p><strong><a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"nofollow noreferrer\">Big O</a></strong></p>\n<p>I put a function counter in both approaches. OP was O(n!) and apparently so was the original. Thus OP's concern about "my function has two loops" did not worsen <code>O()</code>.</p>\n<p>Advantage: Neither</p>\n<hr />\n<p>Recommend: Use the best parts of the two.</p>\n<p>For me, I would prefer a solution that worked with a <code>const char *</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T16:40:19.643",
"Id": "245195",
"ParentId": "245185",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245195",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T14:11:45.983",
"Id": "245185",
"Score": "5",
"Tags": [
"performance",
"c",
"combinatorics"
],
"Title": "Permutations in C"
}
|
245185
|
<p>I have built a Express.js proxy server using TypeScript to be able to hide my front-end API keys.</p>
<p>I designed it to be able to include multiple API services and to reject connections that are not from allowed domains.</p>
<p>It is working as expected, but I'm new to TypeScript and wanted to get some feedback, also on the overall design of the project.</p>
<p>This is <code>app.ts</code>:</p>
<pre class="lang-js prettyprint-override"><code>import { Request, Response, NextFunction } from 'express';
import Debug from 'debug';
import dotenv = require('dotenv');
import proxies from './proxies';
dotenv.config();
import express = require('express');
const debug = Debug('express:server');
const app = express();
function notFound(req: Request, res: Response, next: NextFunction) {
res.status(404);
const error = new Error('Not Found');
next(error);
}
function errorHandler(error: Error, req: Request, res: Response) {
res.status(res.statusCode || 500);
res.json({
message: error.message,
});
}
proxies.forEach((proxy) => app.use(proxy));
app.use(notFound);
app.use(errorHandler);
const port = process.env.PORT || 5000;
app.listen(port, () => debug(`Listening on port ${port}`));
</code></pre>
<p>This is <code>proxies.ts</code> which is responsible for creating the proxies using the <code>http-proxy-middleware</code> and the proxies defined on the <code>config.ts</code> file:</p>
<pre class="lang-js prettyprint-override"><code>import querystring, { ParsedUrlQueryInput } from 'querystring';
import { Request } from 'express';
import { createProxyMiddleware, Options, Filter } from 'http-proxy-middleware';
import config from './config';
const { allowedDomains: globalAllowedDomains = [], proxies } = config;
export default proxies.map(
({
route,
target,
allowedDomains = [],
allowedMethods = ['GET'],
queryparams = {},
headers = {},
auth,
}) => {
const filter: Filter = (pathname: string, req: Request) => {
if (typeof req.headers.origin === 'string') {
return (
pathname.startsWith(route) &&
allowedMethods.includes(req.method) &&
[...globalAllowedDomains, ...allowedDomains].includes(
req.headers.origin
)
);
}
return false;
};
const options: Options = {
target,
changeOrigin: true,
headers,
auth,
pathRewrite(path: string, req: Request) {
const qp = querystring.stringify({
...req.query,
...queryparams,
} as ParsedUrlQueryInput);
const newPath = `${path.split('?')[0].replace(route, '')}?${qp}`;
return newPath;
},
logLevel: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
};
return createProxyMiddleware(filter, options);
}
);
</code></pre>
<p>And this is <code>config.ts</code> which is a configuration file where I can enable multiple API services:</p>
<pre class="lang-js prettyprint-override"><code>import { Options } from 'http-proxy-middleware';
import { ParsedUrlQueryInput } from 'querystring';
export interface Proxy extends Options {
route: string;
allowedMethods: string[];
queryparams?: ParsedUrlQueryInput;
allowedDomains?: string[];
}
export interface Config {
allowedDomains: string[];
proxies: Proxy[];
}
const config: Config = {
allowedDomains:
process.env.NODE_ENV === 'production'
? ['https://www.mauriciorobayo.com']
: ['http://localhost:8080'],
proxies: [
{
route: '/weather',
allowedMethods: ['GET'],
target: 'https://api.openweathermap.org/data/2.5/weather',
queryparams: {
appid: process.env.WEATHER_API_KEY,
},
},
{
route: '/ipinfo',
allowedMethods: ['GET'],
target: 'https://ipinfo.io/',
queryparams: {
token: process.env.IPINFO_TOKEN,
},
},
{
route: '/github',
allowedMethods: ['GET'],
target: 'https://api.github.com',
headers: {
Accept: 'application/vnd.github.v3+json',
Authorization: `Token ${process.env.GITHUB_TOKEN}`,
},
},
],
};
export default config;
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T14:52:43.157",
"Id": "245187",
"Score": "1",
"Tags": [
"api",
"typescript",
"express.js",
"proxy"
],
"Title": "TypeScript Express.js proxy server overall design and structure"
}
|
245187
|
<p>Any advice on how to make this code; cleaner, more effective, just overall better!</p>
<p>Program creates a 'post' in the console. The post has a:</p>
<ol>
<li>message</li>
<li>create on date</li>
<li>score for 'upvotes' and 'downvotes'</li>
</ol>
<p>Users are able to upvote or downvote the post using upvote or downvote with a simple trim and to lower applied to the string.</p>
<p>Any feedback is good feedback. I am currently a working programmer but being self-taught the confidence is not always there..</p>
<p>Want to see it in action? <a href="https://repl.it/repls/RoughGhostwhiteApplet" rel="nofollow noreferrer">https://repl.it/repls/RoughGhostwhiteApplet</a></p>
<pre><code>namespace StackOverflowPost
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Write a post!");
string post = Console.ReadLine();
Post newPost = new Post();
newPost.AddPostMessage(post);
bool val = true;
while (val)
{
newPost.ShowPost();
Console.WriteLine("What would you like to do now? \n You can 'UpVote', 'DownVote'");
string inputData = Console.ReadLine();
string cleanData = inputData.Trim().ToLower();
if (cleanData == "upvote")
{
newPost.Upvote();
}
else if (cleanData == "downvote")
{
newPost.DownVote();
}
else
{
val = false;
}
}
}
class Post
{
int voteScore;
string postMessage;
DateTime postDate;
public Post()
{
this.postDate = DateTime.Now;
}
public void AddPostMessage(string post)
{
postMessage = post;
}
public void Upvote()
{
voteScore++;
}
public void DownVote()
{
voteScore--;
}
public void ShowPost()
{
Console.WriteLine("------------------------------------");
Console.WriteLine($"Original Post Date {postDate}");
Console.WriteLine($"User wrote: {postMessage}");
Console.WriteLine($"Votes: {voteScore}");
Console.WriteLine("------------------------------------");
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T18:53:51.997",
"Id": "481488",
"Score": "0",
"body": "Instead of `while (val)` you could do `while (true)` and use `break` instead of a `val = false`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T08:17:41.100",
"Id": "481526",
"Score": "1",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Two assumptions (because it is simplet for me with them)</p>\n<ol>\n<li>Code works as it should</li>\n<li>This code should be prepared to go "the enterprise road" (e.g. we assume many people maintaining it for a long time in the future).</li>\n</ol>\n<p><strong>Note</strong> belows are opinions only, please do not treat is as a source of truth because your company might have a different guidelines. Since it is C# code I'm trying to stick to MSFT gudielines and, where not possible, with my own preference.</p>\n<h1>Overall comments</h1>\n<ul>\n<li>I'm really happy that you provided a working 'ready to run' example.</li>\n<li>I think you should start thinking about unit testing your code if you haven't already. Simple unit tests as a start. For example 'does <code>Upvote()</code> increases the score`'.</li>\n<li>I <strong>really</strong> like 'make your functions as short as it is convinient and logical' approach to writing code. Here, it would mean that ideally we would split the main function to a couple of small ones. I would be very happy if you refactored it to small logical functions and posted a new question so we can pick it up from there. I would suggest something similar to the below.</li>\n</ul>\n<pre><code>Main(){\n WriteWelcomeMessage();\n var userInput = ReadUserInput();\n var newPost = CreateNewPost(userInput);\n while(val){\n DisplayPost(newPost);\n userInput = ReadUserInput();\n ExecutePostAction(userInput, newPost);\n }\n}\n</code></pre>\n<p>Or something similar, I think you get the idea. This can be further split so Main has only two or one function calls.\nI consider this approach an implementation of <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns</a> and <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>.</p>\n<ul>\n<li>This is still early in the project but if you would proceed with this as an enterprise application I would suggest reading on <a href=\"https://en.wikipedia.org/wiki/Dependency_injection#:%7E:text=In%20software%20engineering%2C%20dependency%20injection,object%20is%20called%20a%20service.\" rel=\"nofollow noreferrer\">dependency injection</a>. Here you can inject classes like reader, writer, postFactory or similar. This will make the testing much simpler in the future.</li>\n<li>I highly recommend to include some style checker (e.g. <a href=\"https://github.com/StyleCop/StyleCop\" rel=\"nofollow noreferrer\">stylecop</a>) this will ensure that you can spot more guidelines issues.</li>\n</ul>\n<h1>Main function</h1>\n<ul>\n<li><p>Don't couple your implementation to <code>Console</code> class. I personally would write a class that would encapsulate writing/reading (or maybe two classes?) so you can easily replace it with for example reading from a WPF textbox or writing to a file.</p>\n</li>\n<li><p>I strongly believe in descriptive variable naming, variable always should be describing its content. Below variables are IMHO missnamed:</p>\n<ul>\n<li><code>post</code> - should be 'postContent'</li>\n<li><code>val</code> - <code>shouldContinue</code> (?)</li>\n<li><code>inputData</code> - <code>userChoice</code></li>\n</ul>\n</li>\n<li><p>If you would rename the variables to be descriptive, you can drop type declarations. <code>string</code> or <code>bool</code> are not giving much context. See <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/implicitly-typed-local-variables\" rel=\"nofollow noreferrer\">here</a> for more info.</p>\n</li>\n</ul>\n<h1>Post class</h1>\n<ul>\n<li>I like that you encapsulated upvoting and downvoting to functions.</li>\n<li>Is there any reason why content of the post is not passed through the constructor? This might lead to null reference exception if the user of this class would forget to call <code>AddPostMessage</code>.</li>\n<li>I would add <code>private</code> infront of the fields</li>\n<li>You could inject a writer class to Post in order to decouple it from <code>Console</code> class.</li>\n<li>You could also inject some <code>DateTime</code> provider in order to unit test this class easier.</li>\n<li>I prefer using <code>DateTime.UtcNow</code> instead, this makes handling multiple timezones easier.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T19:00:56.990",
"Id": "245199",
"ParentId": "245193",
"Score": "4"
}
},
{
"body": "<p>My take: ergonomics.</p>\n<p>To improve <strong>user experience</strong> and keeping in mind the constraints of a console application, I would minimize the number of <strong>keystrokes</strong> required to operate the program.\nTo downvote or upvote a post, pressing <kbd>u</kbd> or <kbd>d</kbd> respectively should be sufficient.</p>\n<p>The actions on the posts (currently: downvote, upvote) could be made an <strong>Enum</strong>.\nIt is possible that in the future, as your application grows you will want to add more actions eg. flag post, delete etc. I would build the app with flexibility and mind. So the Downvote action should be <em>mapped</em> to letter <kbd>d</kbd> etc.</p>\n<p>But an Enum must contain integral values so we have to find another alternative. Here is my try inspired on <a href=\"https://stackoverflow.com/a/37399406/6843158\">this post</a>.\nNote the conversion of char to string in the switch block - required for comparing values. Response is converted to lowercase too.</p>\n<p>TODO: wrap the code in a while loop to handle invalid responses.</p>\n<pre><code>using System;\n\nclass MainClass {\n\n /* possible actions on a post */\n public static class PostAction\n {\n public const string \n Downvote = "d",\n Upvote = "u";\n }\n\n public static void Main (string[] args) {\n char response;\n\n Console.WriteLine("What would you like to do now? \\nYou can 'UpVote', 'DownVote'");\n response = Console.ReadKey().KeyChar;\n response = char.ToLower(response);\n Console.WriteLine("You answered: {0}", response);\n\n switch (response.ToString())\n {\n case PostAction.Downvote:\n Console.WriteLine("Downvote");\n break;\n case PostAction.Upvote:\n Console.WriteLine("Upvote");\n break;\n default:\n Console.WriteLine("Not a valid answer");\n break;\n }\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T21:01:00.620",
"Id": "245207",
"ParentId": "245193",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "245199",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T15:49:46.117",
"Id": "245193",
"Score": "6",
"Tags": [
"c#",
"console"
],
"Title": "C# Better structure in my code & any other critiques"
}
|
245193
|
<p>Initially, this is not an attempt at early optimization, though it's thoroughly possible I'm looking in the wrong place :).</p>
<p>The following function returns a height value for aliased columns in a kind of voxel-style height-map renderer.</p>
<p>It is called many, many times for both AI and player controlled entities and used for collision detection. It is not being called unnecessarily, by any entities that are static by nature. So, it's really a question of whether there are any tricky operations I'm missing that could allow the interpreter to better JIT-compile my code.</p>
<p>Please assume that 'mapcol' is an array of [0,255] Numbers with a length of mapscalex*mapscalez. The map dimensions may actually be quite a bit bigger than is suggested here; relevant only because I think any memoization would flood RAM.</p>
<p>I've made my best attempt to sanitize this code for brevity. It naturally references variables that are necessarily augmented on level-load, here represented as simple globals.</p>
<pre><code>var mapscalex = 256;
var mapscalez = 256;
var tilescale = 16;
var tilescaley = 4;
//Returns the Y value for a pair of X/Zs
function getmapheight(x,z){
//Drop the coordinate to the map scale
x = x/tilescale;
z = z/tilescale;
//Clamp the coordinate to the map dims
x = Math.min(mapscalex-1,Math.max(0,Math.floor(x)));
z = Math.min(mapscalez-1,Math.max(0,Math.floor(z)));
//Project the 2D coord into a 1D coord for map sampling,--
//and then return the map value scaled into world coordinates
return(mapcol[(x+z*mapscalex)]*tilescaley);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/6ZJXa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6ZJXa.png" alt="Many little pixel guys, all of whom must call the above function :)" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T09:49:01.887",
"Id": "481533",
"Score": "0",
"body": "What is the value range for mapcol? Is it also 0 to 255?"
}
] |
[
{
"body": "<p>From a short review;</p>\n<ul>\n<li><p>the <code>tilescale</code> is <code>16</code> which is a great value to multiply or divide with, so</p>\n<pre><code>x = x/tilescale;\nz = z/tilescale;\n</code></pre>\n<p>can become</p>\n<pre><code>x = x >> 4; //Divide by 16 (tilescale)\nz = z >> 4; //Divide by 16 (tilescale)\n</code></pre>\n<p>this does mean that changing the tilescale can become a performance drag (like in real games)</p>\n</li>\n<li><p>So are <code>256</code> and <code>4</code>, so</p>\n<pre><code>return(mapcol[(x+z*mapscalex)]*tilescaley);\n</code></pre>\n<p>could be</p>\n<pre><code>return(mapcol[(x+z<<8)]<<2); //Nice comment here\n</code></pre>\n</li>\n<li><p><code>~~</code> is faster than <code>Math.floor()</code> but for negative values it does return ~~-6.3 -> 6</p>\n</li>\n<li><p>Don't count on <code>Math</code> to be fast, I dont think I've ever seen <code>Math</code> be faster in anything, <a href=\"https://stackoverflow.com/questions/4924842/javascript-math-object-methods-negatives-to-zero\">even an <code>if</code> statement is faster than <code>Math.max(0,Math.floor(x))</code></a></p>\n</li>\n<li><p>When you know that x or z are either negative or greater than 255, why not just exit with a fixed value?</p>\n</li>\n<li><p>Check out <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array\" rel=\"nofollow noreferrer\">8 bit arrays</a>, they might reduce the need for clamping in your code</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T02:24:25.250",
"Id": "481609",
"Score": "0",
"body": "Thanks so much! I face palmed on the bit shifts. Should have been obvious, though I hadn't known it was a faster op in Javascript. And I hadn't ever heard of the '~~'. That'll be useful just about everywhere! Cheers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T09:47:09.097",
"Id": "245220",
"ParentId": "245194",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245220",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T16:07:46.177",
"Id": "245194",
"Score": "3",
"Tags": [
"javascript",
"performance",
"game"
],
"Title": "Reduce an X/Y Value to an Index In a 1D array and Return the Array Value"
}
|
245194
|
<blockquote>
<p>Given an integer , compute the minimum number of operations(+1, x2, x3) needed
to obtain the number starting from the number 1.</p>
</blockquote>
<p>I did this using this code:</p>
<pre><code>#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n+1, 0);
v[1] = 1;
for(int i = 1; i < v.size(); i++)
{
if((v[i + 1] == 0) || (v[i + 1] > v[i] + 1))
{
v[i + 1] = v[i] + 1;
}
if((2*i <= n) && (v[2*i] == 0 || v[2*i] > v[i] + 1))
{
v[2*i] = v[i] + 1;
}
if((3*i <= n) && (v[3*i] == 0 || v[3*i] > v[i] + 1))
{
v[3*i] = v[i] + 1;
}
}
cout << v[n] - 1 << endl;
vector<int> solution;
while(n > 1)
{
solution.push_back(n);
if(v[n - 1] == v[n] - 1)
{
n = n-1;
}
else if(n%2 == 0 && v[n/2] == v[n] - 1)
{
n = n/2;
}
else if(n%3 == 0 && v[n/3] == v[n] - 1)
{
n = n/3;
}
}
solution.push_back(1);
reverse(solution.begin(), solution.end());
for(size_t k = 0; k < solution.size(); k++)
{
cout << solution[k] << ' ';
}
}
</code></pre>
<p>Input:</p>
<pre><code>5
</code></pre>
<p>Output:</p>
<pre><code>3
1 2 4 5
</code></pre>
<p>Do you have any optimized way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T19:04:44.320",
"Id": "481489",
"Score": "2",
"body": "The algorithm looks good already. What clue make you think it is possible to improve it ? Bad performance on a competitive site ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T10:59:19.430",
"Id": "481539",
"Score": "0",
"body": "@Damien yes exactly, the grader is not accepting it!"
}
] |
[
{
"body": "<h1><code>using namespace std;</code></h1>\n<p>Stop doing this. It is a easy, but sloppy, way to code; a change to the standard library that introduces a new identifier can break your code.</p>\n<p>Being explicit, and writing <code>std::vector</code> instead of <code>vector</code> everywhere would be painful. But there is a middle ground:</p>\n<pre><code>#include <vector>\nusing std::vector;\n</code></pre>\n<p>Now you can lazily use <code>vector</code>, without fear that something you are not using from the standard library will suddenly become defined, colliding with your identifiers, and causing carnage.</p>\n<h1>White space</h1>\n<p>Either put white space around all binary operators, like <code>v[i + 1]</code>, or never put the white space around the binary operators, like <code>v[i*2]</code>. But be consistent.</p>\n<h1><code>cout << endl;</code></h1>\n<p>Don't use this; it slows your code down. The <code>endl</code> manipulator does two things: it adds <code>\\n</code> to the stream <strong>AND</strong> it flushes the stream. If you don't need to flush the stream (and you rarely do), simply write</p>\n<pre><code>cout << '\\n';\n</code></pre>\n<h1>Avoid repeated calls to functions that return the same result</h1>\n<pre><code>for(int i = 1; i < v.size(); i++)\n</code></pre>\n<p>What is the value of <code>v.size()</code>? Will it ever change? Can the compiler tell it won't, and optimize it out? Could you store the value in a local variable to avoid the repeated function calls?</p>\n<p>Or ... you could use the variable that already exists: <code>n</code>.</p>\n<pre><code>for(int i = 1; i <= n; i++)\n</code></pre>\n<h1>Don't Repeat Yourself (DRY)</h1>\n<pre><code> if((v[i + 1] == 0) || (v[i + 1] > v[i] + 1))\n {\n v[i + 1] = v[i] + 1;\n }\n if((2*i <= n) && (v[2*i] == 0 || v[2*i] > v[i] + 1))\n {\n v[2*i] = v[i] + 1;\n }\n if((3*i <= n) && (v[3*i] == 0 || v[3*i] > v[i] + 1))\n {\n v[3*i] = v[i] + 1;\n }\n</code></pre>\n<p>These statements look very similar.</p>\n<pre><code> if((target <= n) && (v[target] == 0 || v[target] > v[i] + 1))\n {\n v[target] = v[i] + 1;\n }\n</code></pre>\n<p>You could pull them out into a function:</p>\n<pre><code>inline void explore_step(vector<int> &v, int n, int i, int target) {\n if ((target <= n) && (v[target] == 0 || v[target] > v[i] + 1)) {\n v[target] = v[i] + 1;\n }\n}\n</code></pre>\n<p>And then write:</p>\n<pre><code> explore_step(v, n, i, i+1);\n explore_step(v, n, i, i*2);\n explore_step(v, n, i, i*3);\n</code></pre>\n<h1>Optimization</h1>\n<p>You approach takes <span class=\"math-container\">\\$O(n)\\$</span> time, because you explore each value from <code>1</code> to <code>n</code>.</p>\n<p>You do this, because you don't know which values are going to be useful in reaching the target value, and test things like <code>v[2*i] > v[i] + 1</code> because you don't know which values could be reached via a faster path.</p>\n<p>A slightly better approach:</p>\n<ul>\n<li>seed <code>1</code> into a list of values to explore</li>\n<li>for each value in the list of values to explore:\n<ul>\n<li>for each of the 3 target values <code>i+1</code>, <code>i*2</code>, & <code>i*3</code> if <code><= n</code>:\n<ul>\n<li>if <code>v[target] == 0</code>, then\n<ul>\n<li>store <code>v[target] = i</code></li>\n<li>add <code>target</code> to the list of values to explore</li>\n<li>if <code>target == n</code>, stop</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>Consider <code>n = 10</code>.</p>\n<pre><code>explore = [1], value = 1, targets = [2, -, 3]\nexplore = [1, 2, 3], value = 2, targets = [-, 4, 6]\nexplore = [1, 2, 3, 4, 6], value = 3, targets = [-, -, 9]\nexplore = [1, 2, 3, 4, 6, 9], value = 4, targets = [5, 8, -]\nexplore = [1, 2, 3, 4, 6, 9, 5, 8], value = 6, targets = [7, -, -]\nexplore = [1, 2, 3, 4, 6, 9, 5, 8, 7], value = 9, targets = [10, -, -]\n</code></pre>\n<p>You could use a <code>queue</code> for <code>explore</code>, but a <code>vector</code> of length <code>n</code>, and just walking forward through the items works fine.</p>\n<p>Notice that all values reachable after 1 step <code>[2, 3]</code> are processed before values reachable after 2 steps [4, 6, 9], and would be processed before those values reachable after 3 steps [5, 8, 7], and so on.</p>\n<p>More over, we've built up a trail of breadcrumbs for the fastest path.</p>\n<pre><code>v[10] = 9\nv[9] = 3\nv[3] = 1\n</code></pre>\n<p>So no searching is required to find the correct path.</p>\n<p>Implementation left to student.</p>\n<hr />\n<p>Can we do better? What if we started with <code>n</code>, and explored <code>n-1</code>, <code>n/2</code>, and <code>n/3</code>? An odd value can't lead to an <code>n/2</code> point, and a non-multiple-of-3 can't lead to a <code>n/3</code> point, so you may be pruning more values out of the search, so might be slightly faster.</p>\n<pre><code>[28] -> [27, 14]\n -> [26, 9, 13, 7]\n -> [25, 13, 8, 3, 12, 6]\n -> [24, 12, 4, 2, 1!, ....]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T02:20:52.587",
"Id": "245212",
"ParentId": "245196",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245212",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T17:12:13.587",
"Id": "245196",
"Score": "2",
"Tags": [
"c++",
"c++17",
"dynamic-programming"
],
"Title": "Find sequence to a target number using restricted set of primitive operations"
}
|
245196
|
<p>So i have a server which I send a Request to and it sends me back a list of rooms,Now i made a window for joining rooms and I'm trying to refresh it every 3 seconds but when i use the Timer thread to refresh the list it doesn't work if I use the normal refresh method with the Timer it works just fine.
Here's some code:</p>
<pre><code>private void AutoRefresh()
{
System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromMilliseconds(3000).TotalMilliseconds);
timer.AutoReset = true;
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.Refresh);
timer.Start();
}
private void Refresh(object sender, System.Timers.ElapsedEventArgs elapsedEventArg)
{
GetRoomsResponse response;
response = SendAndRecv();
Button temp;
foreach (RoomData room in response.rooms)
{
temp = new Button { Content = room };
temp.Click += (sender, e) =>
{
JoinRoomClick(sender, e);
};
temp.Content = room.Name;
buttons.Add(temp);
}
ListBoxRooms.ItemsSource = buttons;
}
</code></pre>
<p>If I call refresh from the main it works perfectly if I call AutoRefresh it doesn't I think it gets stuck on the for each loop no error's just doesn't do it's job</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T18:24:41.407",
"Id": "481485",
"Score": "0",
"body": "Could it be a question for stack overflow instead? Not sure if code review is a good place to solve your problem/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T08:19:27.263",
"Id": "481528",
"Score": "1",
"body": "We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T17:45:13.263",
"Id": "245198",
"Score": "2",
"Tags": [
"c#",
"wpf",
"timer"
],
"Title": "Refresh the List box with new rooms from the server every 3 seconds"
}
|
245198
|
<h1>Is this a performant strategy to implement a stack in Kotlin to compare and delete values?</h1>
<h1>Expect</h1>
<p>Create a stack in order to compare an array of asteroids (ASTs) and handle collisions (deletions), returning the final array of ASTs after collisions.</p>
<ul>
<li>Each AST moves at the same speed</li>
<li>Negative numbers move left, positive numbers move right</li>
<li>Smaller ASTs explode (are deleted), the same size both explode, and same direction ASTs do nothing</li>
</ul>
<p><em>See: <a href="https://github.com/AdamSHurwitz/DSA-LC-AsteroidCollision/tree/root" rel="nofollow noreferrer">LeetCode</a></em></p>
<pre><code>Example 1:
Input: asteroids = [5, 10, -5]
Output: [5, 10]
Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
</code></pre>
<h1>ArrayList Stack Strategy</h1>
<p>Create a stack using an ArrayList to compare asteroid (AST) direction, values, and remove ASTs.</p>
<p>The solution performs as expected in terms of achieving the correct results. However, I'm looking to improve speed and memory performance.</p>
<p><em>See: <a href="https://github.com/AdamSHurwitz/DSA-LC-AsteroidCollision/tree/root" rel="nofollow noreferrer">GitHub repository</a></em></p>
<ol>
<li>Build ArrayList used as a stack and add the AST values to the stack</li>
<li>Start <code>curIndex</code> at the top of the stack and check the stack until <code>curIndex</code> is at the second element of the stack, thus checking for all possible AST collisions.</li>
<li>Using the current <code>cur</code> and previous <code>prev</code> values, check whether a collision will occur. A collision occurs when <code>prev</code> is positive and <code>cur</code> is negative.</li>
<li>Given a collision with ASTs with equal value, remove both ASTs. If the <code>curIndex</code> is not at the end of the stack after removing ASTs, continue to check for right-most collisions by decrementing <code>curIndex--</code>. Otherwise, fully decrement <code>curIndex-=2</code></li>
<li>Given a collision with one AST with a larger value, remove the smaller AST. Only decrement when <code>curIndex</code> is at the end of the stack.</li>
<li>If there are no collisions, decrement the stack <code>curIndex--</code>.</li>
</ol>
<h1>Implement</h1>
<pre class="lang-kotlin prettyprint-override"><code>fun asteroidCollision(asteroids: IntArray): IntArray {
val stack = ArrayList<Int>()
for (a in asteroids) stack.add(a)
var curIndex = stack.size - 1
while (curIndex >= 1) {
val cur = stack.get(curIndex)
val prev = stack.get(curIndex - 1)
if (prev.isRight() && cur.isLeft()) {
if (Math.abs(cur) == Math.abs(prev)) {
stack.removeAt(curIndex)
stack.removeAt(curIndex - 1)
if (curIndex - 2 == stack.size - 1)
curIndex -= 2
else curIndex--
} else if (Math.abs(prev) > Math.abs(cur)) {
stack.removeAt(curIndex)
if (curIndex - 1 == stack.size - 1)
curIndex--
} else {
stack.removeAt(curIndex - 1)
curIndex--
}
} else curIndex--
}
return stack.toIntArray()
}
fun Int.isLeft() = this < 0
fun Int.isRight() = this > 0
</code></pre>
<h1>Potential improvement</h1>
<p>This seems like it could be a potential improvement. However, it still requires creating a new data structure vs. working with the original array and requires converting the data structure back into an array to return the results.</p>
<ol>
<li>Build a double LinkedList class.</li>
<li>Pass in one element at a time.</li>
<li>Check the top/last element to see if it collides with the previous element.</li>
<li>Continue to check previous elements after all of the original elements are added.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T15:12:45.390",
"Id": "481965",
"Score": "1",
"body": "We cannot comment on a broad notion of \"what is the best strategy\", but we _can_ comment on whether the implementation that you have shown is a good one. I'm going to nudge your title in that direction."
}
] |
[
{
"body": "<p>An array to list can be done by the function <code>toList()</code>.<br />\nlist.size-1 is an existing property on a list called <code>lastIndex</code>.</p>\n<p>'Math.abs' is from Java. Kotlin has its own <code>abs</code>, which isn't prefixed by a class.</p>\n<p>List provides an operator function to access by index:\n<code>stack.get(curIndex)</code> can be written as <code>stack[curIndex]</code></p>\n<pre><code>fun asteroidCollision(asteroids: IntArray): IntArray {\n val stack = asteroids.toMutableList()\n var curIndex = stack.lastIndex\n while (curIndex >= 1) {\n val cur = stack[curIndex]\n val prev = stack[curIndex - 1]\n if (prev.isRight() && cur.isLeft()) {\n if (abs(cur) == abs(prev)) {\n stack.removeAt(curIndex)\n stack.removeAt(curIndex - 1)\n if (curIndex - 2 == stack.lastIndex)\n curIndex -= 2\n else curIndex--\n } else if (abs(prev) > abs(cur)) {\n stack.removeAt(curIndex)\n if (curIndex - 1 == stack.lastIndex)\n curIndex--\n } else {\n stack.removeAt(curIndex - 1)\n curIndex--\n }\n } else curIndex--\n }\n return stack.toIntArray()\n}\n</code></pre>\n<h1>flow</h1>\n<p>The <code>if</code>-<code>else if</code>-<code>else</code> chain can be reduced to two if-statements.<br />\nThis is because the case where the absolute value of <code>cur</code> and <code>prev</code> are the same is just the other two cases combined.<br />\nAs far as I know, you do need more variables, to make it possible.\nTherefor, this is just another choice, with its own drawbacks:</p>\n<pre><code>fun asteroidCollision(asteroids: IntArray): IntArray {\n val stack = asteroids.toMutableList()\n var index = stack.lastIndex\n while (index >= 1) {\n val curIndex = index\n val cur = stack[curIndex]\n val prevIndex = index-1\n val prev = stack[prevIndex]\n if (prev.isRight() && cur.isLeft()) {\n if (abs(prev) >= abs(cur)){\n stack.removeAt(curIndex)\n if (index-1==stack.lastIndex)\n index--\n }\n if (abs(cur) <= abs(prev)){\n stack.removeAt(prevIndex)\n index--\n }\n } else index--\n }\n return stack.toIntArray()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-14T09:31:29.630",
"Id": "245461",
"ParentId": "245200",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T19:01:07.943",
"Id": "245200",
"Score": "2",
"Tags": [
"algorithm",
"array",
"stack",
"kotlin"
],
"Title": "Kotlin Stack using an ArrayList to compare and remove elements"
}
|
245200
|
<p>Since i develop in Java, i got into the habit of not putting hardcoded text in my code.</p>
<p>For paths to files and folders I use the code below. I did it in a way that it was easy to set up and quick to understand, but i want to know if there are any solution more clean to do the same work ? A lib just for this ?</p>
<p>So if you have any suggestions, please let me know !</p>
<pre><code>/**
* Your directory respresented as an enum allow you to retrieve path of any directory easyly and
* cleanly to avoid too many hardcoded text.
*/
public enum Directory {
/**
*
* The following structure is the complete directory where you work, represented in the form of
* a tree structure. If you need some ressources which are not in your structure, you need to
* append to it the neccessary directories.
*
* An example of such a directory could be as follows :
*
* ROOT ("."), ./
* ASSETS (ROOT, "assets"), ├─ assets
* IMAGES (ASSETS, "img"), │ ├─ img
* SOUNDS (ASSETS, "snd"), → │ └─ snd
* SOURCE (ROOT, "src"), └─ src
* CLASS (SOURCE, "cls"); └─ cls
*
* Pretty easy with few tabs.
*
* ROOT (Environment.getExternalStorageState()) for android 4.4
*/
ROOT (App.context().get().getExternalFilesDir(null)),
EXAMPLE (ROOT, "ex"),
ASSETS (EXAMPLE, "assets"),
IMAGES (ASSETS, "img"),
ICON (IMAGES, "ico"),
/**
* For consistency make sure that `version` have only one child and will never
* in the future have more than one unique child named `v1`.
*/
VERSION_1 (IMAGES, "version/v1"),
SOUNDS (ASSETS, "snd"),
STYLE (ASSETS, "style"),
SOURCE (EXAMPLE, "src"),
CLASS (SOURCE, "class"),
BINARY (EXAMPLE, "bin");
/**
* The absolute path of this directory;
*/
private final String _DIR;
/**
* Create a new Directory.
*
* @param name The name of your root directory
*/
Directory (String name) {
_DIR = name.intern();
}
/**
* Create a new directory.
*
* @param parent The parent directory if its not your root directory;
* @param name The name of the directory
*/
Directory(Directory parent, String name) {
_DIR = parent.path() + name;
}
/**
* This method allow you to retrieve the absolute path to the given directory.
*
* @return the path to this directory with a '/' character at the end. Replace this delimiter
* if your file explorer use an diffrerent delimiter.
*/
public String path() {
return _DIR + '/';
}
/**
* Return a string representation of the absolute path to this directory
* @return the absolute path
*/
@Override
public String toString() {
return _DIR;
}
}
</code></pre>
<p>Ex :</p>
<pre><code>System.out.println(Directory.ICON); // print : /storage/ex/assets/img/ico
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T20:32:12.050",
"Id": "481492",
"Score": "2",
"body": "I really appreciate your code. But, this solution hardcodes as well all paths. How about putting all those paths in a configuration file. Hence, any change of any path will not impact your code base."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T21:45:12.607",
"Id": "481497",
"Score": "0",
"body": "Nice answer I know what you mean, and yes, that's right, all of the hard-coded text in one class instead of all over the code. The code you see is an example, I simplified by putting text in hard, however I actually use `App.context().get().getResources().getString(R.string.my_string)` the things here, is that i need to parse my string for get the parent node or the child. Its in that way i think my code is not perfect and where i need some help. Plus, i don't want the user to be able to modify these path, so config file is not really what i want.. i think ?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T19:05:54.670",
"Id": "245202",
"Score": "2",
"Tags": [
"java",
"android",
"file-system"
],
"Title": "No hardcoded path"
}
|
245202
|
<p>Hey I always used to create some pretty messy endpoints and I decided that it's about time to start writing cleaner code, I'll provide an example of how would I design an endpoint and I'll be thankful for any insights why is it good or bad practice to do it like this also I'd be more than happy if you provide your own tweaks with explanation why would you do it like that.<br>
<strong>Scenario</strong>: user post endpoint<br>
<strong>Pathname</strong>: /api/user<br>
<strong>Method</strong>: POST<br>
<strong>Controller</strong>:</p>
<pre><code>class UserPostEndpoint extends AbstractController
{
private UserPostHandlerInterface $handler;
private SerializerInterface $serializer;
function __construct(UserPostHandlerInterface $handler, SerializerInterface $serializer)
{
$this->handler = $handler;
$this->serializer = $serializer;
}
public function handleRequest(Request $request): Response
{
try {
$userPostRequestDTO = $this->serializer->unserialize($request->getContent(), UserPostRequestDTO::class);
$response = $this->handler->handle($userPostRequestDTO); // <- ApiSuccessResponse(statusCode = 201)
} catch(SerializationException $e) {
$response = new ApiErrorResponse('Invalid request content provided', 400);
} catch(ApiRequestContentValidationException $e) {
$response = new ApiErrorReponse($e->getPlainMessage(), 400);
} catch(\Exception $e) {
$response = new ApiErrorReponse('Internal server error', 500);
} finally {
return $response;
}
}
}
</code></pre>
<p>Handler would contain some basic things like: invoke createUser in UserFactory, persist the entity with repository.
<strong>ApiErrorReponse</strong>: message, statusCode<br>
<strong>ApiSuccessReponse</strong>: UserPostResponseDTO, statusCode(201)<br>
Would you <strong>add / change / remove</strong> something from the given example to make it more "correct"? <br>Thanks for the insights <br>
<strong>EDIT</strong><br>
After a few comments from @slepic I refactored the code into this</p>
<pre><code>class UserPostEndpoint extends AbstractController
{
private UserPostHandlerInterface $handler;
private DataTransformerInterface $dataTransformer;
function __construct(UserPostHandlerInterface $handler, DataTransformerInterface $dataTransformer)
{
$this->handler = $handler;
$this->dataTransformer = $dataTransformer;
}
public function handleRequest(Request $request): Response
{
try {
$userPostRequestDTO = $this->dataTransformer->toRequestDto($request->getContent(), $request->headers->get('Content-Type', 'application/json'));
$userPostResponseDTO = $this->handler->handle($userPostRequestDTO);
$response = new ApiSuccessResponse($userPostResponseDTO, Response::HTTP_CREATED);
} catch(SerializationException $e) {
$response = new ApiErrorResponse('Invalid request content provided', Response::HTTP_BAD_REQUEST);
} catch(ApiRequestContentValidationException $e) {
$response = new ApiErrorReponse($e->getPlainMessage(), Response::HTTP_BAD_REQUEST);
} catch(\Exception $e) {
$response = new ApiErrorReponse('Internal server error', Response::HTTP_INTERNAL_SERVER_ERROR);
} finally {
return $response;
}
}
}
</code></pre>
<p>I hope this is more appropriate</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T03:20:46.063",
"Id": "481509",
"Score": "0",
"body": "It Is a bit wierd that the controller dictates what error status codes should be returned, but status code for success is selected by handler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T07:29:37.593",
"Id": "481522",
"Score": "0",
"body": "@slepic after taking a second look thats true, should I move the try catch to the handler then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T07:59:45.653",
"Id": "481524",
"Score": "0",
"body": "No I think just like you have unserializer for request, you should have a serializer for response body, then, in the controller, build response object by composing 201 status code and the serialized body."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T08:14:03.520",
"Id": "481525",
"Score": "0",
"body": "The key point is that the handler should not be aware what format (JSON, etc.) is used for transport between client and server, neither what status code or headers are sent back to the client. In your implementation the handler Is responsible for providing the correct output format, yet the handler has no means to know what format the client requested. It Is the fact that you probably dont intend to support multiple formats that lead you to this design."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T08:18:21.407",
"Id": "481527",
"Score": "1",
"body": "In other words, http statuses and headers and bodies live in the http domain thus handled by controllers, your application dtos live in your business domain thus handled by your domain handlers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T13:39:12.207",
"Id": "481551",
"Score": "0",
"body": "@slepic I took your words into account and editted some parts of the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T14:50:48.497",
"Id": "481556",
"Score": "2",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-09T11:41:35.243",
"Id": "499419",
"Score": "0",
"body": "This might be more on-topic over at [SoftwareEngineering](https://SoftwareEngineering.StackExchange.com/), but before posting there please [**follow their tour**](https://SoftwareEngineering.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://SoftwareEngineering.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://SoftwareEngineering.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://SoftwareEngineering.StackExchange.com/help/dont-ask)."
}
] |
[
{
"body": "<p>How about:</p>\n<pre><code>class PostController extends AbstractController\n{\n public function store(PostStoreRequest $request): Response\n {\n $dataStruct = app(PostDataStruct::class)->fill($request->validated());\n \n return app(UserPostHandlerInterface::class)->createPost($dataStruct);\n }\n}\n</code></pre>\n<ul>\n<li><code>PostStoreRequest</code> validates data</li>\n<li><code>PostDataStruct</code> stores contents and has a method that fill all the data for you.</li>\n<li>Your code looks a bit like Laravel so I utilized Laravels app container. This way you will have an easier time mocking objects in phpunit.</li>\n<li>Within Kernel file forException Handlers, you can define how certain exceptions are handled. i.e. if you call <code>throw new SystemExceptionError('my message')</code> - in the Kernel file state that SystemExceptionError should have HTTP status 500.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-12T10:13:16.173",
"Id": "245359",
"ParentId": "245204",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T20:08:33.913",
"Id": "245204",
"Score": "2",
"Tags": [
"php",
"rest"
],
"Title": "What is the common API endpoint architecture using DTO?"
}
|
245204
|
<p>The easiest way to explain this problem is to show these two test cases:</p>
<pre><code>assert solution('ABC') == ['A', 'B', 'C', 'AB', 'AC', 'BC', 'ABC']
assert solution('ABCD') == ['A', 'B', 'C', 'D', 'AB', 'AC', 'AD', 'BC', 'BD', 'CD', 'ABC', 'ABD', 'ACD', 'BCD', 'ABCD']
</code></pre>
<p>my solution is below:</p>
<pre><code>def subsolution(lst, length):
return [lst + [x] for x in·
range(lst[-1]+1, length)]
def solution(symbols):
length = len(symbols)
result = [[[x] for x in range(length)]]
while True:
subres = []
for x in result[-1]:
subres.extend(subsolution(x, length))
if not subres:
break
result.append(subres)
result = [ item for sublist in result
for item in sublist
]
result = [
''.join(symbols[s] for s in el)
for el in result
]
return result
</code></pre>
|
[] |
[
{
"body": "<h1>Style</h1>\n<p>We all have our own 'what is the best' style. However even if you do something that others don't agree with, if you're consistent about it then that's all that matters.</p>\n<p><a href=\"https://i.stack.imgur.com/PjYlh.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/PjYlh.png\" alt=\"\" /></a></p>\n<p>From here you have some inconsistencies in your code.</p>\n<ul>\n<li><p>Indent style. You don't have a fixed style, and you've mixed two styles together to make something I think both sides can agree is not right.</p>\n<ul>\n<li><p>With opening delimiter:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>return [lst + [x] for x in·\n range(lst[-1]+1, length)]\n</code></pre>\n</blockquote>\n</li>\n<li><p>Hanging indent:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>result = [\n ''.join(symbols[s] for s in el)\n for el in result\n]\n</code></pre>\n</blockquote>\n</li>\n<li><p>Both:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>result = [ item for sublist in result\n for item in sublist\n]\n</code></pre>\n</blockquote>\n</li>\n</ul>\n</li>\n<li><p>You're not consistent in your newlines in comprehensions.</p>\n<ul>\n<li><p>Item and <code>for _ in</code> on first line:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>return [lst + [x] for x in·\n range(lst[-1]+1, length)]\n</code></pre>\n</blockquote>\n</li>\n<li><p>Item and entire <code>for _ in ...</code> on first line:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>result = [ item for sublist in result\n for item in sublist\n]\n</code></pre>\n</blockquote>\n</li>\n<li><p>Item on first line:</p>\n<blockquote>\n<pre class=\"lang-py prettyprint-override\"><code>result = [\n ''.join(symbols[s] for s in el)\n for el in result\n]\n</code></pre>\n</blockquote>\n</li>\n</ul>\n</li>\n</ul>\n<p>We can fix these by just having a consistent style.</p>\n<pre class=\"lang-py prettyprint-override\"><code>return [\n lst + [x]\n for x in range(lst[-1]+1, length)\n]\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>result = [\n item\n for sublist in result\n for item in sublist\n]\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>result = [\n ''.join(symbols[s] for s in el)\n for el in result\n]\n</code></pre>\n<h1>Improvements</h1>\n<ul>\n<li><p>Your last two comprehensions that build <em>two</em> lists are wasteful when you can just merge the comprehensions together. This will also improve readability.</p>\n<pre class=\"lang-py prettyprint-override\"><code>return [\n ''.join(symbols[s] for s in item)\n for sublist in result\n for item in sublist\n]\n</code></pre>\n</li>\n<li><p>Your code is not very readable. I can't tell that you're effectively calling <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"noreferrer\"><code>itertools.combinations</code></a> <code>len(symbols)</code> times.</p>\n<p>Whilst combinatorics are not very pleasant to read, your code doesn't show the most basic part clearly.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def solution(symbols):\n for i in range(1, 1 + len(symbols)):\n yield from itertools.combinations(symbols, i)\n</code></pre>\n</li>\n</ul>\n<h1>Overall</h1>\n<p>You should get a consistent style and your code has some improvements to be made.\nHowever your code is pretty good on the combinations front.\nThe <code>range</code> aspect is smart, maybe too smart, but if you used a docstring to explain the input and output then the implementation details can be guessed at fairly easily from your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T06:25:44.447",
"Id": "481518",
"Score": "0",
"body": "Thanks! About `itertools.combinations`: I didn't use because it was forbidden to use it. But I forget to mention it, so it's my bad."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T22:56:59.153",
"Id": "245208",
"ParentId": "245205",
"Score": "6"
}
},
{
"body": "<p><strong>My recursive solution:</strong></p>\n<p>Logic: You are taking a string.\nYou are appending three types of strings to the <code>ALL_VALUES</code> list.</p>\n<ol>\n<li>0th indexed character pair with all other characters for each string in the recursion stack.</li>\n<li>Each string that is in recursion stack.</li>\n<li>List of all characters individually.</li>\n</ol>\n<p>Now you are adding the string characters, all characters pair with 0th positioned character and rest all removing the leftmost character and doing it recursively.</p>\n<pre><code>ALL_VALUES = []\n\n\ndef find_all_subsets(string):\n if string:\n ALL_VALUES.extend(\n [string] + ([string[0] + character for character in string[1:]])\n )\n find_all_subsets(string[1:])\n\n\nfind_all_subsets(string)\nprint(set(ALL_VALUES + list(string)))\n</code></pre>\n<p><strong>Outputs:</strong></p>\n<pre><code>string = "ABCD" # Output {'A', 'B', 'CD', 'D', 'BD', 'C', 'BC', 'AD', 'AB', 'AC'}\n\nstring = "ABC" # Output = {'AC', 'C', 'AB', 'A', 'BC', 'B'}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-11T16:59:45.570",
"Id": "245328",
"ParentId": "245205",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T20:23:37.787",
"Id": "245205",
"Score": "1",
"Tags": [
"python",
"combinatorics"
],
"Title": "Combinatorics challenge solved it Python"
}
|
245205
|
<p>My attempt at creating a snake game, in pygame. I tried to make it as simple as possible, but i feel it could be better in terms of best practice, and efficiency, along the idea of avoiding redundant code.
It would be appreciated, if anyone can give me advice in that regard.</p>
<pre><code>import pygame
import time
import random
pygame.init()
pygame.font.init()
WINDOW = pygame.display.set_mode((500, 500))
pygame.display.set_caption('snake')
FOOD_COORS = []
TICK = 15
RUN = True
SNAKE_COMP = [[50, 50, 2], [40, 50, 2], [30, 50, 2], [20, 50, 2], [10, 50, 2]]
f = [random.randint(0, 50)*10, random.randint(0, 50)*10]
d = 2
CLOCK = pygame.time.Clock()
def hit():
time.sleep(3)
pygame.quit()
class snake():
def __init__(self, SNAKE_COMP):
self.x, self.y = SNAKE_COMP[0][0:2]
def draw(self, SNAKE_COMP):
self.SNAKE_COMP = SNAKE_COMP
for i in range(0, len(SNAKE_COMP)):
pygame.draw.rect(WINDOW, (255, 255, 255), (SNAKE_COMP[i][0], SNAKE_COMP[i][1], 10, 10))
def hit_check(self, SNAKE_COMP):
self.SNAKE_COMP = SNAKE_COMP
if SNAKE_COMP[0][0] >= 500 or SNAKE_COMP[0][0] < 0:
hit()
if SNAKE_COMP[0][1] >= 500 or SNAKE_COMP[0][1] < 0:
hit()
test_l = [[]]
for i in range(0, len(SNAKE_COMP)):
test_l.append(tuple(SNAKE_COMP[i][0:2]))
for i in range(0, len(test_l)):
if test_l.count(test_l[i]) > 1:
hit()
class food():
global FOOD_COORS
def draw(self):
x, y = self.x, self.y
pygame.draw.rect(WINDOW, (255, 0, 0), (x, y, 10, 10))
def spawn(self, SNAKE_COMP):
global FOOD_COORS
self.SNAKE_COMP = SNAKE_COMP
test_l = [[]]
for i in range(0, len(SNAKE_COMP)):
test_l.append(SNAKE_COMP[i][0:2])
g = True
while g:
x = random.randint(0, 49)*10
y = random.randint(0, 49)*10
if [x, y] not in test_l:
g = False
FOOD_COORS = [x, y]
self.x, self.y = x, y
snek = snake(SNAKE_COMP)
apple = food()
apple.spawn(SNAKE_COMP)
s = False
g = False
while RUN:
CLOCK.tick(TICK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
RUN = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and d != 3:
d = 1
elif keys[pygame.K_RIGHT] and d != 4:
d = 2
elif keys[pygame.K_DOWN] and d != 1:
d = 3
elif keys[pygame.K_LEFT] and d != 2:
d = 4
if g != True and SNAKE_COMP[0][0:2] != FOOD_COORS:
last = len(SNAKE_COMP) - 1
for i in range(1, len(SNAKE_COMP)):
SNAKE_COMP[len(SNAKE_COMP)-i][2] = SNAKE_COMP[len(SNAKE_COMP)-i-1][2]
SNAKE_COMP[0][2] = d
for i in range(0, len(SNAKE_COMP)):
if SNAKE_COMP[i][2] == 1:
SNAKE_COMP[i][1] -= 10
elif SNAKE_COMP[i][2] == 2:
SNAKE_COMP[i][0] += 10
elif SNAKE_COMP[i][2] == 3:
SNAKE_COMP[i][1] += 10
elif SNAKE_COMP[i][2] == 4:
SNAKE_COMP[i][0] -= 10
else:
k = SNAKE_COMP[0][2]
FOOD_COORS.append(k)
if k == 1:
FOOD_COORS[1] -= 10
elif k == 2:
FOOD_COORS[0] += 10
elif k == 3:
FOOD_COORS[1] += 10
elif k == 4:
FOOD_COORS[0] -= 10
SNAKE_COMP.insert(0, FOOD_COORS)
apple.spawn(SNAKE_COMP)
snek.hit_check(SNAKE_COMP)
apple.draw()
snek.draw(SNAKE_COMP)
pygame.display.update()
WINDOW.fill((0, 0, 0))
pygame.quit()
</code></pre>
|
[] |
[
{
"body": "<p>On the whole, the game works and has a solid UI that you've correctly kept basic and mostly out of play as you focus on the game engine logic. It looks like you've gone for a partially-OOP approach by putting focus on the two entities that are drawable and their necessary data but leaving the main game logic outside of a class. I think that's a reasonable fundamental design. I do have a variety of suggestions for tightening up this design and improving code style though.</p>\n<h3>Tight coupling</h3>\n<p>Although your classes are potentially useful abstractions, the snake's movement update is done outside of the <code>snake</code> class, breaking <a href=\"https://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)\" rel=\"nofollow noreferrer\">encapsulation</a>. A <code>snake.move</code> or <code>snake.change_direction</code> function is the correct delegation of responsibility for this rather than reaching into the class from main and messing with its internals.</p>\n<p>The state of code with classes and functions that rely on and mutate <a href=\"https://en.wikipedia.org/wiki/Global_variable\" rel=\"nofollow noreferrer\">global state</a> is difficult to predict. For example, I'd reasonably expect a <code>snake</code> or <code>food</code> class to be able to create multiple instances with separate positions. But in this design, instances are tightly coupled to a single global <code>FOOD_COOR</code> or <code>SNAKE_COMP</code> variable. Creating more than a single instance of either class breaks it.</p>\n<p>There are other more subtle violations of modularity, like calling global <code>hit</code> inside of <code>snake.hit_check</code>. This function should return true or false if a hit occurred and let the calling code invoke <code>hit</code> how, when and if they please rather than creating a dependency between the class and exterior code. <code>pygame</code> could be removed or at least injected into the object so the same snake logic could hook to any visual interface.</p>\n<h3>High cyclomatic complexity</h3>\n<p>The main <code>while</code> loop that runs the game has very high <a href=\"https://en.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a> with over 18 branches and 3 layers of nesting. These giant blocks of conditionals and loops make the code very hard to understand (and by extension, maintain and debug) and should be broken out into functions or otherwise refactored.</p>\n<h3>Abusing literals</h3>\n<p>The code abuses <a href=\"https://en.wikipedia.org/wiki/Hard_coding\" rel=\"nofollow noreferrer\">hard-coded</a> literal values throughout. If you want to change the size of the grid, for example, you'd need to walk the whole file hunting for all the <code>10</code>s that happen to be related to the grid size to make them a different number. This is tedious and error-prone even in a tiny program.</p>\n<p>Same applies to window size and a few other things. Storing these values as variables in <a href=\"https://en.wikipedia.org/wiki/Single_source_of_truth\" rel=\"nofollow noreferrer\">one place</a> and referencing them means everything just works when you need to change a value, helping to eliminate typo bugs and ease <a href=\"https://en.wikipedia.org/wiki/Code_refactoring\" rel=\"nofollow noreferrer\">refactoring</a>. If classes or functions need to know the window size, this information should be injected in a parameter to the initializer or appropriate method.</p>\n<p><code>d</code> (really <code>direction</code>) has 4 possible values: 1, 2, 3 and 4. The problem is that "1" has no semantic meaning here. It's not obvious whether a "1" entails up, down, left or sideways. The classical way to handle this is an <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enumeration</a>, but even <code>direction = "up"</code> would increase the expressiveness of the code and reduce bugs (did you type in 2 when you meant 1 somewhere?).</p>\n<h3>Magical boolean flags</h3>\n<p>Variables like</p>\n<pre><code>s = False\ng = False\n</code></pre>\n<p>are unclear. Pick descriptive names and avoid boolean flags in favor of functions that can return true/false to handle control flow. The reason functions are cleaner than flags is because they result in less state for the caller to keep track of and support modularity. Less state means the code is easier to understand. Modularity means it's easier to isolate problems if they occur and <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">handle refactors locally</a> without causing a domino effect throughout the code base.</p>\n<h3>Complex logic</h3>\n<p>Much of the logic can be simplified considerably. To pick one example, code that checks whether the head segment is colliding with the tail,</p>\n<pre><code>test_l = [[]]\nfor i in range(0, len(SNAKE_COMP)):\n test_l.append(tuple(SNAKE_COMP[i][0:2]))\nfor i in range(0, len(test_l)):\n if test_l.count(test_l[i]) > 1:\n hit()\n</code></pre>\n<p>could be something like</p>\n<pre><code>if any(SNAKE_COMP[0][:2] == x[:2] for x in SNAKE_COMP[1:]):\n hit()\n</code></pre>\n<p>Even here, it's unusual that <code>SNAKE_COMP</code> needs 3 elements in its coordinates. The slice is a <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">code smell</a> because it's non-obvious. If the third element is direction, it's not necessary. Only the head needs an explicit direction.</p>\n<h3>Style and naming</h3>\n<ul>\n<li><p>Classes should be <code>UpperCamelCase</code>. You don't need the <code>()</code> after the class name unless you're inheriting. Making the class <code>Snake</code> as it should be means you can call the instance <code>snake</code> instead of the awkward intentional typo <code>snek</code> to avoid the alias.</p>\n</li>\n<li><p>Use <code>ALL_CAPS</code> variable names sparingly, if at all, and only to designate program constants.</p>\n</li>\n<li><p>Never use single-letter variables unless the purpose is overwhelmingly obvious from context.</p>\n<pre><code>f = [random.randint(0, 50)*10, random.randint(0, 50)*10]\nd = 2\n</code></pre>\n<p>are not obvious. <code>f</code> is never used in the program which an editor with static analysis should warn you of and <code>d</code> should be called <code>direction</code>.</p>\n</li>\n<li><p>Alphabetize imports.</p>\n</li>\n<li><p>Use vertical whitespace more liberally, particularly around functions and blocks.</p>\n</li>\n<li><p>In addition to confusing single-letter boolean flags, names like <code>SNAKE_COMP</code> are unclear. What's <code>COMP</code>? Something like <code>snake_coordinates</code>, <code>snake_body</code> or <code>snake_tail</code> seems a bit clearer here. Even better in a class like <code>snake.tail</code>.</p>\n</li>\n</ul>\n<p>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> and your style will sparkle.</p>\n<h3>UX</h3>\n<p>After a collision, the game freezes for 3 seconds and dies. As a player, I might feel like the game crashed or is buggy. A message or visual indication of the collision would communicate the snake's death better. Even just exiting instantly feels like a smoother experience.</p>\n<h3>Efficiency</h3>\n<p>This is totally premature, but it's worth keeping in mind that nearly all of your snake and apple operations that are O(n) like <code>SNAKE_COMP.insert(0, FOOD_COORS)</code> can be made O(1) using a <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>deque</code></a> and <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set</code></a>. When you move the snake forward, you can rotate the deque. When you check for collision between the head and the body, you can use a set lookup.</p>\n<h3>Rewrite suggestion, round 1</h3>\n<p>This requires Python 3.8 because of the whisker assignments, but you can easily move those outside of the blocks.</p>\n<p>I'm using <a href=\"https://docs.python.org/3/library/functions.html#iter\" rel=\"nofollow noreferrer\"><code>__iter__</code></a> in both classes. Since I'm doing all of the drawing and pygame interaction in the main (the point is to keep UI and game logic separate), making the snake iterable is a nice way to get all of its body segments, but I cast to a tuple to avoid the caller mutating its position accidentally.</p>\n<p>On the other hand, I trust that the caller will abide by the vector input for the <code>turn</code> function since <a href=\"https://python-guide-chinese.readthedocs.io/zh_CN/latest/writing/style.html#we-are-all-consenting-adults\" rel=\"nofollow noreferrer\">we're all consenting adults</a>. If you don't trust the client to behave, you can validate this coordinate pair and raise an error.</p>\n<p>There's still lots of room for improvement: the main code is a bit bloated so this refactor is mostly an exercise in class organization and trying to keep everything <a href=\"https://en.wikipedia.org/wiki/Loose_coupling\" rel=\"nofollow noreferrer\">loosely coupled</a>. <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">Docstrings</a> are pretty cursory and could better explain the parameters and return values.</p>\n<p>I don't really know Pygame so I may have gaffed--I find the key handlers pretty awkward, but I notice you can slice out the arrow keys and make a nice, indexable list of flags that hopefully doesn't break anything.</p>\n<pre><code>import pygame\nfrom random import randrange\n\nclass Snake:\n def __init__(self, size, direction, body):\n self.size = size\n self.direction = direction\n self.body = list(map(tuple, body))\n\n def __iter__(self):\n return map(tuple, self.body)\n\n def in_bounds(self, width, height):\n """ Returns whether the snake's head is in the height/width bounds """\n x, y = self.body[0]\n return x >= 0 and y >= 0 and x < width and y < height\n\n def move(self):\n """ Moves the snake in the direction it's facing """\n self.body.insert(0, (self.body[0][0] + self.direction[0] * self.size,\n self.body[0][1] + self.direction[1] * self.size))\n\n def remove_tail(self):\n """ Destroys the snake's last tail segment """\n del self.body[-1]\n\n def touching_point(self, point):\n """ Returns whether point is somewhere in the snake's body """\n return point in self.body\n\n def touching_tail(self):\n """ Returns whether the snake's head point is in the snake's body """\n return self.body[0] in self.body[1:]\n \n def set_direction(self, x, y):\n """ Sets the snake's direction given a cardinal unit-vector facing \n in a non-opposite direction from the snake's current direction\n """\n if (-x, -y) != self.direction:\n self.direction = x, y\n\nclass Food:\n def __init__(self, x=0, y=0):\n self.x, self.y = x, y\n \n def __iter__(self):\n yield self.x, self.y\n\n def reposition(self, size, width, height, used_squares):\n """ Repositions the apple on the size grid within the bounds avoiding \n certain used squares. Infinitely loops if no squares are available.\n """\n while point := (randrange(0, width, size), randrange(0, height, size)):\n if point not in used_squares:\n self.x, self.y = point\n break\n\nif __name__ == "__main__":\n class Color:\n white = 255, 255, 255\n red = 255, 0, 0\n black = 0, 0, 0\n\n width = height = 500\n game_speed = 15\n cell_size = 10\n directions = (0, -1), (0, 1), (1, 0), (-1, 0)\n initial_body = (50, 50), (40, 50), (30, 50), (20, 50), (10, 50)\n initial_direction = (1, 0)\n pyg_arrow_key_loc = slice(273, 277)\n pygame.init()\n pygame.display.set_caption("snake")\n pyg_window = pygame.display.set_mode((width, height))\n pyg_clock = pygame.time.Clock()\n snake = Snake(cell_size, initial_direction, initial_body)\n apple = Food()\n apple.reposition(cell_size, width, height, snake)\n \n while not any(event.type == pygame.QUIT for event in pygame.event.get()):\n if any(arrows := pygame.key.get_pressed()[pyg_arrow_key_loc]):\n snake.set_direction(*directions[arrows.index(1)])\n\n snake.move()\n\n if snake.touching_point(*apple):\n apple.reposition(cell_size, width, height, snake)\n else:\n snake.remove_tail()\n\n if snake.touching_tail() or not snake.in_bounds(width, height):\n pygame.quit()\n \n pygame.draw.rect(pyg_window, Color.black, (0, 0, width, height))\n apple_rect = (apple.x, apple.y, cell_size, cell_size)\n pygame.draw.rect(pyg_window, Color.red, apple_rect)\n\n for x, y in snake:\n pygame.draw.rect(pyg_window, Color.white, (x, y, cell_size, cell_size))\n\n pyg_clock.tick(game_speed)\n pygame.display.update()\n</code></pre>\n<h3>Rewrite suggestion, round 2</h3>\n<p>I wasn't entirely happy with main in the above rewrite so I gave a shot at cleaning it up a bit. It's still not perfect and adds code but it'd be a likely next step if you wanted to scale up the app. Breaking <code>render</code> into entity-specific functions is a potential next step as the app grows.</p>\n<p>Notice that the <code>Snake</code> and <code>Food</code> classes don't need to be touched thanks to the earlier refactor and we can treat them as black boxes. After this refactor, the main function can treat <code>SnakeGame</code> as a black box as well and just specify its configuration. You can see how the abstractions build up: we can tuck these classes into another file like <code>snake.py</code> and use it as a library.</p>\n<pre><code>import pygame\nfrom snake import Food, Snake\n\nclass SnakeGame:\n class Color:\n white = 255, 255, 255\n red = 255, 0, 0\n black = 0, 0, 0\n\n def __init__(self, width, height, cell_size, \n initial_body, initial_direction, game_speed):\n pygame.init()\n pygame.display.set_caption("snake")\n self.pyg_window = pygame.display.set_mode((width, height))\n self.pyg_clock = pygame.time.Clock()\n self.snake = Snake(cell_size, initial_direction, initial_body)\n self.apple = Food()\n self.cell_size = cell_size\n self.width = width\n self.height = height\n self.game_speed = game_speed\n self.apple.reposition(cell_size, width, height, self.snake)\n\n def run(self): \n pyg_arrow_key_loc = slice(273, 277)\n directions = (0, -1), (0, 1), (1, 0), (-1, 0)\n \n while not any(event.type == pygame.QUIT for event in pygame.event.get()):\n if any(arrows := pygame.key.get_pressed()[pyg_arrow_key_loc]):\n self.snake.set_direction(*directions[arrows.index(1)])\n \n self.snake.move()\n \n if self.snake.touching_point(*self.apple):\n self.apple.reposition(self.cell_size, self.width, \n self.height, self.snake)\n else:\n self.snake.remove_tail()\n \n if (self.snake.touching_tail() or \n not self.snake.in_bounds(self.width, self.height)):\n pygame.quit()\n \n self.render()\n \n def render(self):\n pygame.draw.rect(self.pyg_window, SnakeGame.Color.black, \n (0, 0, self.width, self.height))\n apple_rect = (self.apple.x, self.apple.y, self.cell_size, self.cell_size)\n pygame.draw.rect(self.pyg_window, SnakeGame.Color.red, apple_rect)\n \n for x, y in self.snake:\n pygame.draw.rect(self.pyg_window, SnakeGame.Color.white, \n (x, y, self.cell_size, self.cell_size))\n \n self.pyg_clock.tick(self.game_speed)\n pygame.display.update()\n\nif __name__ == "__main__":\n SnakeGame(width=500, \n height=500, \n cell_size=10, \n initial_body=((50, 50), (40, 50), (30, 50), (20, 50), (10, 50)), \n initial_direction=(1, 0), \n game_speed=15).run()\n</code></pre>\n<h3>Suggested exercises</h3>\n<ul>\n<li>Add a score.</li>\n<li>Improve graphics/UI/messaging/text.</li>\n<li>Try making multiple apples.</li>\n<li>Make the snake periodically "poop", creating an obstacle that it cannot touch but fades away over time.</li>\n<li>Add walls.</li>\n<li>Add levels.</li>\n<li>Try adding a second snake that uses the <kbd>w</kbd><kbd>a</kbd><kbd>s</kbd><kbd>d</kbd> keys on the same keyboard.</li>\n<li>Use <a href=\"https://flask-socketio.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">Flask SocketIO</a> to make a real time network game.</li>\n<li>Try writing a <a href=\"https://towardsdatascience.com/slitherin-solving-the-classic-game-of-snake-with-ai-part-1-domain-specific-solvers-d1f5a5ccd635\" rel=\"nofollow noreferrer\">snake AI</a>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T01:24:39.247",
"Id": "245254",
"ParentId": "245209",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "245254",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T00:21:24.987",
"Id": "245209",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"pygame",
"snake-game"
],
"Title": "A Python Snake Game Using Pygame"
}
|
245209
|
<p>I have a text data file in <a href="https://www.spwla.org/" rel="nofollow noreferrer">SPWLA</a> format; I cannot find a specification for it. It contains physical measurements and/or rock descriptions from wellbore core samples. It's fairly gross. The example here is substantially simplified:</p>
<pre><code>text = """\
30 1
2001.10 0.00 2.11
40 1 2
-1002.0000 34.5678
30 1
2001.90 0.00 1
36 1 1
Sst.Lt-gry. Pyr.
40 1 2
18.72400 15.45700
30 1
2002.90 0.00 2
36 1 1
Sst.Lt-gry. W-cmt.
"""
</code></pre>
<p>This example contains data records for three depths in the wellbore:</p>
<ul>
<li>Record type 30 gives the depth of the following group of records.</li>
<li>Record type 36, if present, contains a string in a <a href="https://en.wikipedia.org/wiki/Domain-specific_language" rel="nofollow noreferrer">DSL</a>.</li>
<li>Record type 40, if present, contains the data whose fields are listed in another record type.</li>
<li>I don't think there can be more than one '30' record for a given depth, and in my solution I assume there cannot.</li>
</ul>
<p>There are several other record types, but I've left them out of this example.</p>
<p>I've written a parsing expression grammar (PEG), using Python <a href="https://pypi.org/project/parsimonious/" rel="nofollow noreferrer"><code>parsimonious</code></a>, to describe this format:</p>
<pre><code>from parsimonious import Grammar
grammar = Grammar(
r"""
file = data_blocks+
data_blocks = depth_block descr_block? data_block?
depth_block = "30" WS "1" WS depth WS NUMBER WS NUMBER WS
descr_block = "36" WS "1" WS "1" WS description WS
data_block = "40" WS "1" WS record_count WS DATA WS
record_count = NUMBER+
depth = NUMBER+
description = SENTENCE+
field_name = SENTENCE+
WS = ~r"\s*"
NUMBER = ~r"[-.0-9]+"
DATA = ~r"[- .0-9]+"
COMPANY = ~r"[-_A-Z]+"i
SENTENCE = ~r"[-., /ÅA-Z]"i
"""
)
</code></pre>
<p>And this parses successfully, producing an abstract syntax tree (AST):</p>
<pre><code>ast = grammar.parse(text)
</code></pre>
<p>According to the docs, the usual approach now is to subclass the <code>NodeVisitor</code> class in <code>parsimonious</code> to crawl the AST, returning whatever you need from each node's special method (for example, the <code>visit_description()</code> method determines what gets returned from the <code>description</code> nodes). Here's my node crawler:</p>
<pre><code>from parsimonious import NodeVisitor
class FileVisitor(NodeVisitor):
def visit_file(self, node, visited_children):
data = {}
for record in visited_children:
data.update(record)
return data
def visit_data_blocks(self, node, visited_children):
depth, descr, data = visited_children
descr = descr[0] if isinstance(descr, list) else ''
data = data[0] if isinstance(data, list) else []
return {depth: {'descr': descr, 'data': data}}
def visit_depth_block(self, node, visited_children):
_, _, _, _, depth, *_ = node.children
return float(depth.text)
def visit_descr_block(self, node, visited_children):
*_, descr, _ = visited_children
return descr
def visit_description(self, node, visited_children):
return node.text
def visit_data_block(self, node, visited_children):
*_, data, _ = visited_children
return data
def visit_DATA(self, node, visited_children):
return [float(x) for x in node.text.split()]
def generic_visit(self, node, visited_children):
return visited_children or node
</code></pre>
<p>I run it like so:</p>
<pre><code>fv = FileVisitor()
fv.visit(ast)
</code></pre>
<p>The result is this dictionary:</p>
<pre><code>{'data': {2001.1: {'descr': '', 'data': [-1002.0, 34.5678]},
2001.9: {'descr': 'Sst.Lt-gry. Pyr.', 'data': [18.724, 15.457]},
2002.9: {'descr': 'Sst.Lt-gry. W-cmt.', 'data': []}}}
</code></pre>
<p>Which is what I want, but my question is: is there a more efficient way to write this <code>NodeVisitor</code>? In particular:</p>
<ul>
<li>Can I avoid the <code>data = data[0] if isinstance(data, list) else []</code> business, which I seem to need to deal with the <code>data</code> (and <code>description</code>) node sometimes being empty?</li>
<li>Writing things like <code>_, _, _, _, depth, *_ = node.children</code> feels a bit fragile and hard to maintain, which obviates solving the entire problem this way. Am I missing something?</li>
</ul>
<p>I know I can do all this with string processing or regex, and I've done both. I'm interested in using a PEG-based method, because I'm drawn to the idea... but clearly I'm a little out of my depth! I guess I was hoping to be able to focus on maintaining the grammar, but writing that was relatively easy (assuming I've done it in a reasonable way!). The hard part was writing this tree crawler thing. So I'm wondering if I just swapped one kind of fragility (chained string methods or lengthy regexes) for another.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T04:56:24.683",
"Id": "481513",
"Score": "0",
"body": "There seems to be a mismatch between the grammar and the visitor methods posted above. There are methods that don't correspond with a rule name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T07:32:36.933",
"Id": "481523",
"Score": "0",
"body": "In `data[0] if isinstance(data, list) else []`, what exactly is `data` if not a list? I.e. What exact case are you trying to guard against? Is it just `None`, or some parsed garbage?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T10:29:05.727",
"Id": "481537",
"Score": "0",
"body": "@RootTwo Bah, you're right, good catch. I simplied everything (there are 3 other record types) and forgot to take those two methods out. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T10:35:18.933",
"Id": "481538",
"Score": "0",
"body": "@Graipher Thanks for reading... it's a `parsimonious.nodes.Node`, which has a very long repr containing essentially the entire data file's text (seems weird I know)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T14:28:45.797",
"Id": "481554",
"Score": "0",
"body": "I'm surprised `descr_block` works, given that your sentences seem to contain spaces. Is it an ambiguous rule? (Ending each line with EOL rather than WS would work to make it unambiguous, and then you could include WS in `description`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T19:28:45.750",
"Id": "481576",
"Score": "1",
"body": "@Pod Thank. I'm honestly not sure. I think I get away with it because the expressions are greedy. The thing is, if I start using EOL as a token, I need them all over the place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T22:17:44.343",
"Id": "481588",
"Score": "1",
"body": "@Pod The regex for `description` includes a space (but not '\\t' or '\\n'). Same for `DATA`. So they will both end at a '\\n'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T05:19:54.757",
"Id": "481889",
"Score": "0",
"body": "@kwinkunks Here is some VBA code to convert SPWLA files to excel spreadsheets. https://github.com/bolgebrygg/spwla."
}
] |
[
{
"body": "<p>I think you can get rid of the <code>isinstance(..., list)</code> checks by revising the grammar a bit. I renamed <code>data_blocks</code> to <code>chunk</code> because I kept mixing it up with <code>data_block</code>.</p>\n<p>A <code>chunk</code> is a <code>depth_block</code> followed by zero or more <code>other_blocks</code>. The <code>visit_chunk</code> function then knows the first child is a <code>depth_block</code> and the second child is a possibly empty list of <code>other_blocks</code>. No need to check for missing blocks.</p>\n<p>The <code>blocks</code> start with a regex that matches the numbers that start each block. In the corresponding visitor methods, <code>visited_children</code> unpacking all start with one leading <code>_,</code> to match the regex.</p>\n<p>I added whitespace (ws) to the end of each leaf-node in the grammer (number, description, the literals) to remove the WS clutter. The <code>nl</code> at the end of each block keeps the parser from extending a block to the next line.</p>\n<pre><code>from parsimonious import Grammar\n\ngrammar = Grammar(\n r"""\n file = chunk+\n chunk = depth_block other_block*\n \n other_block = descr_block / data_block\n \n depth_block = ~"30\\s+1\\s+" depth number number nl\n descr_block = ~"36\\s+1\\s+1\\s+" description+ nl\n data_block = ~"40\\s+1\\s+" count nl number+ nl\n\n count = number\n depth = number\n\n ws = ~r"[ \\t]+"\n nl = ~r"(\\n\\r?|\\r\\n?)" ws\n number = ~r"-?[.0-9]+" ws\n description = ~r"\\S+" ws\n """\n)\n</code></pre>\n<p>Starting from the bottom, the <code>description</code> visitor strips whitespace from the matched text. The <code>number</code> visitor strips surrounding whitespace and converts it to a float or int as appropriate.</p>\n<p>For a node having a single child, <code>NodeVisitor.lift_child</code> return the value of the child as the value of the node. So <code>visit_count</code> simply returns the value of it's child <code>number</code> node.</p>\n<p>The various <code>visit_*_block</code> methods use tuple unpacking to get the values of the important children nodes and returns an appropriate dict. <code>visit_chunk</code> assembles a dict from the component dicts returned from the <code>visit_*_block</code> methods. And <code>visit_file</code> returns a list of these chunk dicts.</p>\n<p>.</p>\n<pre><code>class Visitor(NodeVisitor):\n\n def visit_file = NodeVisitor.lift_child\n \n def visit_chunk(self, node, visited_children):\n chunk, others = visited_children\n for block in others:\n chunk.update(block)\n return chunk\n \n def visit_depth_block(self, node, visited_children):\n _, depth, _, _, _ = visited_children\n return {'depth':depth}\n \n visit_other_block = NodeVisitor.lift_child\n \n def visit_descr_block(self, node, visited_children):\n _, descriptions, _ = visited_children\n return {'description':descriptions}\n \n def visit_data_block(self, node, visited_children):\n _, count, data_list, _ = visited_children\n return {'count':count, 'data':data_list}\n \n visit_count = NodeVisitor.lift_child\n \n visit_depth = NodeVisitor.lift_child\n \n def visit_number(self, node, visited_children):\n text = node.text.strip()\n return float(text) if '.' in text else int(text)\n \n def visit_description(self, node, visited_children):\n return node.text.strip()\n</code></pre>\n<p>I can't install parsimonious on this computer, so this isn't tested.</p>\n<p>Looking at github, it doesn't look like parsimonious has been updated since 2018. I like using a PEG parser library called Tatsu. One nice feature is the grammer lets you name parts of a rule and then refer to them by name in a visitor method. For example, in the grammar, use:</p>\n<pre><code>data_block = ?"40\\s+1\\s+" count:number data:number+ nl\n</code></pre>\n<p>then the corresponding visitor would look like:</p>\n<pre><code>def data_block(self, ast):\n return {'count':ast.count, 'data':ast.data}\n</code></pre>\n<p>without needing the unpacking statements. I have a Tatsu-based solution if you would like me to post it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T17:18:59.760",
"Id": "481985",
"Score": "0",
"body": "Thank you for this contribution and the insight from your experience. I did wonder if Parsimonious had been abandoned, but it looked easier to wield than, say, `sly` or `pyparsing`. Anyway, I'm giving it a look now and I'll check out Tatsu as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T06:26:40.270",
"Id": "245265",
"ParentId": "245210",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T00:41:46.370",
"Id": "245210",
"Score": "4",
"Tags": [
"python",
"parsing",
"grammar"
],
"Title": "Is there a better way to parse this data file?"
}
|
245210
|
<p>this post is sort of a continuation of my answer on the following question: <a href="https://stackoverflow.com/q/62698250/7501501">Fast Algorithm to Factorize All Numbers Up to a Given Number</a>. As this post explains - We need to factorize all the numbers up to a large N.</p>
<p>At first I gave a python solution which was pretty slow (since - you know, python), than I decided to write it in C++. I am not that good with C++ and I would like to have a code review about that answer:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <math.h>
#include <unistd.h>
#include <list>
#include <vector>
#include <ctime>
#include <thread>
#include <iostream>
#include <atomic>
#ifndef MAX
#define MAX 200000000
#define TIME 10
#endif
std::atomic<bool> exit_thread_flag{false};
void timer(int *i_ptr) {
for (int i = 1; !exit_thread_flag; i++) {
sleep(TIME);
if (exit_thread_flag) {
break;
}
std::cout << "i = " << *i_ptr << std::endl;
std::cout << "Time elapsed since start: "
<< i * TIME
<< " Seconds" << std::endl;
}
}
int main(int argc, char const *argv[])
{
int i, upper_bound, j;
std::time_t start_time;
std::thread timer_thread;
std::vector< std::list< int > > factors;
std::cout << "Initiallizating" << std::endl;
start_time = std::time(nullptr);
timer_thread = std::thread(timer, &i);
factors.resize(MAX);
std::cout << "Initiallization took "
<< std::time(nullptr) - start_time
<< " Seconds" << std::endl;
std::cout << "Starting calculation" << std::endl;
start_time = std::time(nullptr);
upper_bound = sqrt(MAX) + 1;
for (i = 2; i < upper_bound; ++i)
{
if (factors[i].empty())
{
for (j = i * 2; j < MAX; j += i)
{
factors[j].push_back(i);
}
}
}
std::cout << "Calculation took "
<< std::time(nullptr) - start_time
<< " Seconds" << std::endl;
// Closing timer thread
exit_thread_flag = true;
std::cout << "Validating results" << std::endl;
for (i = 2; i < 20; ++i)
{
std::cout << i << ": ";
if (factors[i].empty()) {
std::cout << "Is prime";
} else {
for (int v : factors[i]) {
std::cout << v << ", ";
}
}
std::cout << std::endl;
}
timer_thread.join();
return 0;
}
</code></pre>
<p>I would especially like a review about my usage of threads (I am afraid it might slow down the code). The performance are reaching 6619 which is the 855th (out of 1662 primes up to 14140 ~ square root of 200000000) in 1.386111 hours, if you find any way to make it faster I will be amazing! A more semantic review is also very welcome (Like #include order?).</p>
<p>Just for fun and a point of reference if you are trying to run the code yourself:</p>
<p><a href="https://i.stack.imgur.com/rRDU6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rRDU6.png" alt="Progression Graph" /></a></p>
<p>Where X is time and Y is the prime reached (i). The orange tradeline is <code>y = 13 * 1.00124982852632 ^ x</code>. The graph is exponential since indeed the inner loop time is getting shorter.</p>
<p>The orange tradeline says I will reach 14107 (The highest prime before the square root) at x ≈ 5595.842803197861 seconds which is 1.554 hours!</p>
|
[] |
[
{
"body": "<p>The code does just a <em>tad more</em> then a standard sieve. Of course the inner loop of the sieve starts with <code>i*i</code> whereas your code starts with <code>i*2</code>; still we can expect that it should scale nicely with <span class=\"math-container\">\\$O(n \\log \\log n)\\$</span> time complexity. Considering that a sieve over 200000000 completes in a matter of seconds, the difference must come from the work the sieve does not.</p>\n<p>This <em>tad more</em> is that while sieve crosses out the compound numbers, you <code>push_back</code> them to the lists. And this is a performance killer.</p>\n<p>You push back every factor of every integer. The number of <code>push_back</code>s performed <a href=\"https://en.wikipedia.org/wiki/Divisor_function#Growth_rate\" rel=\"nofollow noreferrer\">grows approximately</a> as <span class=\"math-container\">\\$N\\log{N}\\$</span> (the Dirichlet estimate). I expect that the factors lists amasses about 4G entries; as each entry (having an <code>int</code> value and two pointers) is of 24 byte (on a 64-bit system), the total memory consumed is about 90 GB (how much exactly we don't know; you are at the mercy of the standard library implementors). This is by itself a very impressive number. What's worse, elements of these lists are scattered all over the place, and the code accesses them pretty much randomly, in a <em>very</em> cache-unfriendly manner. In other words, most of the time is spent thrashing the cache.</p>\n<p>To be honest, I don't know how to speed up your code. I have some ideas based on the entirely different approaches, by I don't expect an order of magnitude improvements. Factorizing is hard.</p>\n<hr />\n<p>I don't understand why do you want a timer thread. It is perfectly OK to query <code>std::chrono::system_clock::now();</code> before the processing, and at any moment you want to know how much time elapsed.</p>\n<hr />\n<p><code>Validating results</code> section is very sloppy. A visual inspection of a few primes is far from enough. You should take a small, yet representative (say, 10000 strong), set of numbers, compute their factors the hard way, and compare the results.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T00:59:37.380",
"Id": "481603",
"Score": "0",
"body": "Thanks for all of your points. I did not know about the Dirichlet estimate, these numbers are quite insane, 90GB - the numbers add up but how my computer did not crush? The program did got killed that might be the reason... I actually had a strong suspicion about the cache but I didn't want to bring it up since it is more of a SO question, do you think disabling it will be better? I do now know about this system_clock, system calls might slow down the process (maybe the context switch even more though). I will do a better \"Validating results\", thanks. Lastly should I consider C implementation?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T23:45:24.407",
"Id": "245250",
"ParentId": "245211",
"Score": "4"
}
},
{
"body": "<h1>Timing</h1>\n<p>The timer thread is unnecessary and an inaccurate way to measure time.</p>\n<blockquote>\n<p>I do now know about this system_clock, system calls might slow down the process (maybe the context switch even more though)</p>\n</blockquote>\n<p>Querying the time costs a bit of time, even if it does not involve an actual system call - which it really may not, there are lots of clever tricks for example <code>clock_gettime</code> uses vDSO on modern Linux and reads from a shared memory location and <code>QueryPerformanceCounter</code> reads the TSC on <a href=\"https://docs.microsoft.com/en-us/windows/win32/sysinfo/acquiring-high-resolution-time-stamps#qpc-support-in-windows-versions\" rel=\"noreferrer\">typical Windows systems</a>, there is no transition into and out of kernel mode. It's never a lot of time relative to what this program is doing, the overhead of getting the time is only an issue when timing very short spans of time. Even if getting the time costs a milisecond (which would be unacceptable and considered a bug in the implementation), it would still be OK for this program.</p>\n<h1>Performance</h1>\n<p>Storing the factors in explicit linked lists is a major performance problem, and unlike usual, using vectors wouldn't be great either. There is an alternative: store only one factor of a number. That still gives a complete factorization for any number, because if a number <code>N</code> has a factor <code>factors[N]</code>, then you can divide <code>N</code> by that factor and look up a factor of the new (smaller) number and so on, until 1 is reached.</p>\n<p>That way the inner loop of the sieve only does a bunch of stores into a vector, nothing heavy-weight like dynamically allocating nodes of a linked list, and the memory usage does not get out hand.</p>\n<p>As a convention, I'll use that the lowest factor of a prime is the prime itself. That is the mathematical definition, and it makes iterating over the implicit factor lists easy.</p>\n<h1>Other</h1>\n<p>Defining <code>MAX</code> by macro definition and putting local variable declarations at the top of the function are very C things to do. Even C has moved away from "all locals at the top". As general guidelines, I recommend using <code>const</code> variables instead of defines, and limiting local variables with the smallest possible scope. That does not repeatedly incur a cost for "making a variable" because that's not how that happens, any fixed space a function needs is allocated all at once at function entry. Besides, most local variables spend their entire lifetime in registers.</p>\n<p>Avoid <code>#include <unistd.h></code> if possible/reasonable, it does not exist on all platforms.</p>\n<p>Pick a brace style and stick to it. There were "same line"-braces and "next line"-braces. There are various opinions on which should be used, but at least they shouldn't be mixed.</p>\n<p>In total, the code might come out like this:</p>\n<pre><code>#include <iostream>\n#include <vector>\n#include <math.h>\n#include <chrono>\n\nint main() {\n const int MAX = 200000000;\n std::vector<int> factors;\n\n std::cout << "Initiallizating" << std::endl;\n auto start_time = std::chrono::steady_clock::now();\n factors.resize(MAX);\n std::cout << "Initiallization took "\n << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time).count()\n << " ms" << std::endl;\n\n std::cout << "Starting calculation" << std::endl;\n start_time = std::chrono::steady_clock::now();\n int upper_bound = sqrt(MAX) + 1;\n for (int i = 2; i < upper_bound; ++i) {\n if (factors[i] == 0) {\n for (int j = i; j < MAX; j += i) {\n factors[j] = i;\n }\n }\n }\n std::cout << "Calculation took "\n << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time).count()\n << " ms" << std::endl;\n\n std::cout << "Validating results" << std::endl;\n for (int i = 2; i < 20; ++i) {\n std::cout << i << ": ";\n if (factors[i] == i) {\n std::cout << "Is prime";\n }\n else {\n for (int N = i; N > 1; N /= factors[N]) {\n std::cout << factors[N] << ", ";\n }\n }\n std::cout << std::endl;\n }\n\n return 0;\n}\n</code></pre>\n<p>On my PC the sieving takes about 2.5 seconds now. Ideone is a bit slower but the program is fast enough to <a href=\"https://ideone.com/grBGBl\" rel=\"noreferrer\">run there</a> too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T12:06:27.903",
"Id": "481643",
"Score": "0",
"body": "Wow, 2.5 seconds! What is the time complexity for querying here? Before it was O(1) and now it is `O(log q)`? Thanks for the great answer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T12:14:18.730",
"Id": "481645",
"Score": "0",
"body": "@Yonlif the complexity for enumerating the factors of a number would the same as before (each step is still constant time, and the number of factors for a number hasn't changed). The complexity of \"getting a list of factors\" may have changed, depending on what you're willing to count as a list"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T12:15:28.507",
"Id": "481646",
"Score": "0",
"body": "Oh correct since the previous items was in a linked list and now getting the next item is still O(1)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T05:04:17.000",
"Id": "245262",
"ParentId": "245211",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "245262",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T00:52:44.760",
"Id": "245211",
"Score": "9",
"Tags": [
"c++",
"primes"
],
"Title": "Factorize All Numbers Up to a Given Number"
}
|
245211
|
<p>I have an array with 40000 numbers that are floats or ints. I need to perform some calculation.</p>
<p>To do this I have used nested for loop, but the code is really slow. Can I use something instead of nested the for loop? Is there any other way to reduce the execution time?<br />
When I changed to a list comprehension the execution time reduce slightly.
Why did the list comprehension take less time?</p>
<pre><code>import numpy as np
import time as t
pox1= np.random.randint(1000, size= 40000)
time = np.arange(40000)
y=np.zeros(len(pox1))
w=np.zeros(len(pox1))
start = t.time()
for num in range (len(time)-1):
z= [((pox1[i] - pox1[i-num]) ** 2) for i in range(num, len(pox1))]
k=np.mean(z)
y[num]=k
# for i in range(num, len(pox1)):
# z.append((pox1[i] - pox1[i-num]) ** 2)
endtime = (t.time()-start)
print(y,endtime)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-11T12:37:45.323",
"Id": "481736",
"Score": "0",
"body": "Whatever you do, don't change the code inside the question at this point now answer have arrived. You're too late for that. Next time, please take a look at the [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) before posting your next question."
}
] |
[
{
"body": "<h1>Python slow, C fast</h1>\n<p>By having the loops in Python you're basically cutting one of your legs off. It should come as no surprise that the one legged human will lose to the two legged human.</p>\n<p>The question we should be asking is how can we slice <code>pox1</code> to get what we want.</p>\n<ol>\n<li><p>We should split the for loop into two comprehensions so we can see how we'd do it in numpy.</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = [pox1[i] for i in range(num, len(pox1))]\nb = [pox1[i - num] for i in range(num, len(pox1))]\nz = (a - b) ** 2\n</code></pre>\n</li>\n<li><p><code>a</code> is very simple we just slice with the values of the range. But <code>b</code> is a bit harder, we can just move the <code>- num</code> into the range and we'll be able to do the same.</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = [pox1[i] for i in range(num, len(pox1))]\nb = [pox1[i] for i in range(0, len(pox1) - num)]\nz = (a - b) ** 2\n</code></pre>\n</li>\n<li><p>Convert it to slices</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = pox1[num : len(pox1)]\nb = pox1[0 : len(pox1) - num]\nz = (a - b) ** 2\n</code></pre>\n</li>\n<li><p>Use some slice sugar</p>\n<pre class=\"lang-py prettyprint-override\"><code>a = pox1[num :]\nb = pox1[: len(pox1) - num]\nz = (a - b) ** 2\n</code></pre>\n</li>\n<li><p>Put back in your code</p>\n<pre class=\"lang-py prettyprint-override\"><code>for num in range(len(time) - 1):\n y[num] = np.mean((pox1[num :] - pox1[: len(pox1) - num]) ** 2)\n</code></pre>\n</li>\n</ol>\n<p>I changed the size to 4000 and this cut it from 5.04s to 0.07s. To get 40000 changes with the updated code takes 3.30s.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\nimport time as t\n\nSIZE = 4000\npox1 = np.random.randint(1000, size=SIZE)\ntime = np.arange(SIZE)\n\ny=np.zeros(len(pox1))\nw=np.zeros(len(pox1))\n\nstart = t.time()\n\nfor num in range(len(time)-1):\n y[num] = np.mean((pox1[num :] - pox1[:len(pox1) - num]) ** 2)\n\nendtime = t.time() - start\nprint(y, endtime)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T09:57:33.060",
"Id": "481535",
"Score": "0",
"body": "Thank you sir for your very nice and easy explanation. As a non programmer your explanation is quite clear to."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T09:26:56.193",
"Id": "245218",
"ParentId": "245214",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "245218",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T08:50:56.910",
"Id": "245214",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy"
],
"Title": "Getting the square of the difference between many points in a NumPy array"
}
|
245214
|
<p>I have a system with 2 different processes. Process 1 starts process 2 and sets up an <code>AnonymousPipe</code> between the 2. Process 1 needs to run some code and needs to interact with process 2 to get info and commit changes. Process 2 runs on Python with references to C# code (since I'm more familiar with C#) so process 2 has a while(true) loop to listen to process 1.</p>
<p>Process 2 has 3 classes that are "services" to underlying code. A simplified example:</p>
<pre><code>// Runs under Process 2 (Python)
public class LibraryManager
{
public string GetCategory(string something) // Step 3.1
{
return something;
}
}
// Runs under Process 2 (Python)
public class Agent
{
public void Run()
{
while (true)
{
// pipe is the anonymouspipe wrapped in an easy to handle class
var function = pipe.Read<Command>(); // Step 2 - waits here for a write, halts code but this is ok for me
switch (function)
{
case Command.LibraryManager_Category:
pipe.Write(LibraryManager.GetCategory("something"); // Step 3
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
// Runs under Process 1 (C#)
public class LibraryManagerService
{
public string GetCategory()
{
CodesysEngine.Pipe.Write(Command.LibraryManager_Category); // Step 1
return CodesysEngine.Pipe.Read<string>(); // Step 4 - this halts the code until the Agent does his write, this is ok for me
}
}
</code></pre>
<p>I'm doing this communication now via an <code>enum</code> <code>Command</code>. This works. If I need to send data to Process 2 I can just write 2 things and bases on the <code>Command</code> change the type I read. (I've done some coding under the hood to be able to do this.)</p>
<p>What I'm not 100% satisfied with is the <code>Command</code> I use to tell the <code>Agent</code> which part of code to execute. This example only has 1 method but I see this growing to over 100 which will make it not very readable as it will be a <code>switch</code> with over 100 <code>case</code>es. I was thinking of splitting the <code>enum</code> per service and have a "master" <code>enum</code> with the 3 services as a divider. (First send which service, then send which method, then send any arguments if needed.)</p>
<p>Is there a more standardized way of doing what I want to achieve cause I have the feeling this can get pretty fast too big to handle?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T09:10:11.197",
"Id": "245216",
"Score": "1",
"Tags": [
"c#",
"ipc"
],
"Title": "IPC with over 100 different methods - viable way to maintain readability"
}
|
245216
|
<p>The "game of 24" as I called it in the title is a maths game in which you are given four numbers and have to combine them in an expression using only the four basic arithmetic operations <code>+</code>, <code>-</code>, <code>×</code> and <code>÷</code> (and possibly using parenthesis) to achieve the final result of <code>24</code>. You <em>must</em> use <em>each</em> digit exactly <em>once</em>.</p>
<p>For example, if the numbers were <code>1 2 3 4</code> the answer could be <code>1×2×3×4</code> or <code>(1+2+3)×4</code>.</p>
<p>I set to write a solver for this game in APL (which eventually led to <a href="https://mathspp.com/blog/24-game" rel="nofollow noreferrer">this blog post</a>) which I wanted to be general enough to handle any amount of input numbers and any target number (so not necessarily only <code>24</code> as target number). The recursive algorithm I used is fairly simple and has a brute-force nature: pick two numbers from the available <code>N</code> numbers in all the different ways I can do that and then combine them with all the available operations, applying the same function recursively to the several sets of <code>N-1</code> numbers.</p>
<p>I am not only interested in knowing if I can get to a target number but I also want to know <em>how</em> to get there, so while I do all these manipulations, I also keep track of how to get to the available numbers by writing prefix expressions with the numbers used. E.g. if at some point I have the numbers <code>1 2 3 4</code>, I will have a matching string representation of <code>'1' '2' '3' '4'</code>. If then I use addition to merge <code>1</code> and <code>2</code>, the new set of numbers is <code>3 3 4</code> and the matching representation changes to <code>'+ 1 2' '3' '4'</code>.</p>
<p>This is the simple namespace I created:</p>
<p>(<strong>edit</strong>: <a href="https://mathspp.com/blog/24-game" rel="nofollow noreferrer">as time went by the code evolved a little</a>)</p>
<pre><code>:Namespace GameOf24
⍝ Generalized solver for the "game of 24".
Solve←{
⍝ Dyadic function to find ways of building ⍺ with the numbers in ⍵
(reprs values)←Combine⊂⍵
mask←⍺=∊values
(mask/reprs) (mask/values)
}
Combine←{
⍝ Recursive dyadic function combining the numbers ⍵ which have been obtained by the expressions ⍺
⎕DIV←1
⍺←⍕¨¨⍵ ⍝ default string representations of input numbers
1=l←≢⊃⍵: ⍺ ⍵ ⍝ if no more numbers to combine, return
U ← { ⍝ unpack pairs of nested results
⊃{(wl wr)←⍵ ⋄ (al ar)←⍺ ⋄ (al,wl)(ar,wr)}/⍵
}
C ← { ⍝ Combine two numbers of ⍵ with the dyadic function in ⍺
(r v) ← ⍵
(li ri) ← ↓⍉idx⌿⍨sub← ≠v[idx]
newv ← v[li] (⍎⍺) v[ri]
oldv ← v[sub⌿unused]
values ← ↓newv,oldv
reprs ← ↓r[sub⌿unused],⍨↓(↑sub/⊂⍺),(↑r[li]),' ',↑r[ri]
reprs values
}
idx ← (~0=(1+l)|⍳l*2) ⌿ ↑,⍳l l
unused ← idx ~⍨⍤1 1 ⍳l
(a w) ← U, '+-×÷' ∘.C ↓⍉↑⍺ ⍵
u←≠w
a ∇⍥(u∘/) w
}
:EndNamespace
</code></pre>
<p>The <code>Solve</code> function is just a wrapper around the main algorithm I described, filtering for the target value in all the different values I can build with the input numbers. Use it like <code>24 GameOf24.Solve 1 2 3 4</code>.</p>
<p>Other than all the feedback you can give me, I have particular questions I would like to see addressed:</p>
<ul>
<li><p>originally I was using a fair share of each <code>¨</code> and used <code>U</code> twice, so I created a dfn for <code>U</code>, which now I only use once. Is it worth keeping it as a separate dfn? Or maybe there is a smarter way of unpacking the results of <code>'+-×÷' ∘.C ↓⍉↑⍺ ⍵</code> to <code>(a w)</code> which doesn't require the use of <code>U</code>;</p>
</li>
<li><p>I don't think it is very elegant to have a string <code>'+-×÷'</code> with the arithmetic operations I am allowed to use and then later on fixing them with <code>⍎⍺</code> but I can't think of a better way of doing this;</p>
</li>
<li><p>is the shape of the data adequate? A vector of vectors for the numbers available and a separate vector of "strings" seems suitable;</p>
</li>
<li><p>should <code>C</code> be adjusted and defined outside of <code>Combine</code>? Currently it's inside <code>Combine</code> because it uses variables defined inside <code>Combine</code> and I think it would be too cumbersome to define those auxiliary variables each time <code>C</code> is called;</p>
</li>
<li><p>the string representations keep getting extra whitespace that I don't know where it comes from; e.g. <code>100 GameOf24.Solve 1 2 3 4 7</code> gives <code>×+3 7 ×+1 4 2 </code> as string representation of the result.</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:12:18.800",
"Id": "530387",
"Score": "0",
"body": "I can still not understand how the expression `÷-÷3 ×5 6 2 4` evals, it looks like Polish notation, but not exactly the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:15:39.493",
"Id": "530392",
"Score": "0",
"body": "Am I not using regular prefix notation? `÷-÷3×5 6 2 4` = `÷-÷3(×5 6) 2 4` = `÷-÷3 30 2 4` = `÷-(÷3 30) 2 4` = `÷-0.1 2 4` etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:48:09.150",
"Id": "530403",
"Score": "0",
"body": "Ah, I see now. The extra white space makes me a little confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T15:33:59.593",
"Id": "530418",
"Score": "0",
"body": "APL seems to be even more write only than Perl :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T16:30:43.417",
"Id": "530421",
"Score": "0",
"body": "@Kubahasn'tforgottenMonica APL is unlike other traditional languages, yes. In general, it's hard to look at APL and guess what it's doing if you know nothing about APL, yes. APL is write-only? Not really :) when you learn it, you'll learn how to read it. Just like with English, Russian, or Chinese."
}
] |
[
{
"body": "<p><code>{(wl wr)←⍵ ⋄ (al ar)←⍺ ⋄ (al,wl)(ar,wr)}</code> can be <code>((⊣/⍤⊣,⍥⊃⊣/⍤⊢),⍥⊂⊢/⍤⊣,⍥⊃⊢/⍤⊢)</code>, a crazy looking train indeed.</p>\n<p>Might be a good idea to add <code>⎕IO←0</code> at the beginning of the namespace script.</p>\n<p><code>U, '+-×÷' ∘.C ↓⍉↑⍺ ⍵</code> the <code>,</code> is not needed.</p>\n<blockquote>\n<p>the string representations keep getting extra whitespace that I don't know where it comes from</p>\n</blockquote>\n<p>It is due to the padding of <code>↑</code> in this line:</p>\n<pre><code>reprs←↓r[sub⌿unused],⍨↓(↑sub/⊂⍺),(↑r[li]),' ',↑r[ri]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:12:23.597",
"Id": "530388",
"Score": "0",
"body": "Thanks for the suggestions!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-12T12:07:26.433",
"Id": "268903",
"ParentId": "245217",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T09:14:42.020",
"Id": "245217",
"Score": "3",
"Tags": [
"recursion",
"mathematics",
"apl"
],
"Title": "Solving the game of 24 recursively in APL"
}
|
245217
|
<p>I'm coming from languages like Java and Python and I'm completely new to C++. Therefore, my knowledge is somewhat limited.</p>
<p>My goal is to implement a listener in C++ myself and I came up with a solution using function pointers and lambdas.<br />
The design is different from other questions that I have seen on this site so I hope it's not a duplicate.</p>
<p>My question: Is my implementation optimal or is it good from a C++ point of view? If there are any optimizations or any better ways please let me know. (Below code is just an example of my design)</p>
<pre><code>class IntegerListener {
public :
void (*number_changed)(int old_number, int new_number);
void (*number_increased)(int increased_value);
//deleting default constructor to make users to define number_changed and number_increased
IntegerListener() = delete;
IntegerListener(void (*&&number_changed)(int, int), void (*&&number_increased)(int)) {
this->number_changed = number_changed;
this->number_increased = number_increased;
}
};
class Integer {
private:
int number;
std::vector<IntegerListener *> integer_listeners;
public:
explicit Integer(int num) : number(num) {}
void set_number(int new_number) {
for (IntegerListener *&integer_listener:integer_listeners) {
(*integer_listener).number_changed(number, new_number);
}
if (new_number > number) {
for (IntegerListener *&integer_listener:integer_listeners) {
(*integer_listener).number_increased(new_number - number);
}
}
number = new_number;
}
void add_number_changed_listener(IntegerListener &&integer_listener) {
integer_listeners.push_back(&integer_listener);
}
};
</code></pre>
<p>and in order to add some listener my idea is something like below:</p>
<pre><code>void test() {
Integer integer(1);
// from a java background it represents the java way the best, in my opinion.
integer.add_number_changed_listener(IntegerListener(
[](int oldNum, int newNum) {
std::cout << "changed(from 1listener): (" << oldNum << ") -> (" << newNum << ")" << std::endl;
},
[](int increasedValue) {
std::cout << "increased by(from 1listener): (" << increasedValue << ")" << std::endl;
}));
integer.add_number_changed_listener(IntegerListener(
[](int oldNum, int newNum) {
std::cout << "changed(from 2listener): (" << oldNum << ") -> (" << newNum << ")" << std::endl;
},
[](int increasedValue) {
std::cout << "increased by(from 2listener): (" << increasedValue << ")" << std::endl;
}));
std::cout << "first call: \n";
integer.set_number(2);
std::cout << "second call: \n";
integer.set_number(1);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T12:01:47.817",
"Id": "481541",
"Score": "2",
"body": "Welcome to Code Review were we review working code from a project you have written and provide tips and suggestions on how the code can be improved. The code must be [concrete and not hypothetical](https://codereview.stackexchange.com/help/how-to-ask). Statements like `(below code is just an example of my design)` and/or `and in order to add some listener my idea is something like below:` can make the question off-topic and it could be closed for a `lack of context`. Is this code working in a project?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T12:49:59.533",
"Id": "481548",
"Score": "2",
"body": "Just at a glance I can see the code has some critical bugs in it: `add_number_changed_listener()` takes the address of a temporary… which then vanishes. But… because this is undefined behaviour, it might *appear* to work. (With UB, *ANYTHING* could happen.) So I'll assume that since there’s test code (good job, by the way!), it was actually tested and seemed to work, and thus it counts as extant, non-hypothetical code (and that the “just an example” comment is superfluous, because it’s clearly not an “example”, it’s actual (seemingly) working code (that could even be useful!))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T14:27:34.960",
"Id": "481553",
"Score": "0",
"body": "@indi tnx for ur reply. this actually is an example and i'm going to use this structure for something more complex and it's complexity wasn't necessary here because this example completely shows what i have in my mind. and for first part I actually didn't know that the lifetime of rvalue is till the end of fullexpresion, I thought it was the stack it lives in(i thought so since the test case actually worked!). I'll change that for sure. and another question-> other than that would you consider what i've done a good practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T19:03:52.030",
"Id": "481573",
"Score": "0",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T22:16:02.760",
"Id": "481587",
"Score": "0",
"body": "@Mast literally the 5th line is saying \"Application of best practices and design pattern usage\" are in the scope of this site. and this question a a design pattern considering the best practices! please don't down vote it so fast for no reason. I was actually told to post it here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T01:45:04.643",
"Id": "481607",
"Score": "0",
"body": "I don’t see how basically complete, (apparently) working code—with tests!—is “pseudocode”, “stub code”, “hypothetical”, or “obfuscated”. I think all the confusion here stems from a poor choice of words. OP called this “an example of my design”. What they *meant* is that it is a *proof of concept*. A proof of concept is not “hypothetical”; it’s literally the opposite of that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T04:39:39.853",
"Id": "481620",
"Score": "0",
"body": "@indi There was a strong emphasis on 'example' both in the question and the comments, making me doubt Code Review would be of any help to the actual code. After rereading, you may well be right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-10T04:43:32.023",
"Id": "481621",
"Score": "2",
"body": "However, keep in mind we don't close without reason. 5 people (or a moderator) have to agree it's an ill fit before it's closed and this will be people with experience on the site. I was hardly the first to raise my concerns."
}
] |
[
{
"body": "<p>There’s actually quite a bit you can do to simplify the listener class, while at the same time making it easier and more flexible to use!</p>\n<p>Let’s start with deleting the default constructor: you actually don’t need to do this. Classes get an automatically-generated default constructor <em>only if there are no other constructors defined</em>. But in your class, there <em>is</em> another constructor defined! So the default constructor is already deleted.</p>\n<p>See for yourself! Try this:</p>\n<pre><code>// No constructors are defined, so the class gets a default constructor.\nclass foo {};\n\n// A constructor is defined, so the default constructor is suppressed.\nclass bar\n{\npublic:\n explicit bar(int) {}\n};\n\n// This will compile:\nauto f = foo{};\n\n// This will not:\n//auto b1 = bar{};\n\n// But of course, this will compile:\nauto b2 = bar{42};\n</code></pre>\n<p>So right away, you can drop the line deleting the default constructor.</p>\n<p>Now, this is <em>not</em> wrong:</p>\n<pre><code>void (*number_changed)(int old_number, int new_number);\n\nvoid (*number_increased)(int increased_value);\n</code></pre>\n<p>That is indeed the correct way to have two data members that are function pointers.</p>\n<p><em>However</em>…</p>\n<p>There is actually a better way:</p>\n<pre><code>std::function<void (int, int)> number_changed;\nstd::function<void (int)> number_increased;\n</code></pre>\n<p>The reason this is better is because <code>std::function</code> is a <em>LOT</em> more powerful than a function pointer. A function pointer only works for regular, free functions, class static functions, and lambdas with no captures.</p>\n<p>But <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a> works with <em>literally anything</em> that even remotely <em>looks</em> like a function. It works for all the same things a function pointer works for. But it also works for member functions, lambdas with captures (closures), general function objects, bound-argument functions, … and so on and so forth. Like, literally everything works.</p>\n<p>For example:</p>\n<pre><code>class my_int_listener\n{\npublic:\n void number_changed(int, int) { /* whatever you want */ }\n void number_increased(int) { /* whatever you want */ }\n\n // This class could have data members, a constructor... whatever\n // you want, and you can use all that stuff in your callbacks.\n};\n\n// Constructed however you want, wherever you want - global var, on the\n// heap, whatever - just so long as it outlives integer.\nauto mil = my_int_listener{};\n\nauto integer = Integer{1};\n\nusing namespace std::placeholders;\ninteger.add_number_changed_listener(\n {\n std::bind(&my_int_listener::number_changed, &mil, _1),\n std::bind(&my_int_listener::number_increased, &mil, _1)\n }\n);\n</code></pre>\n<p>The other benefit of <code>std::function</code> is the syntax is <em>soooo</em> much nicer. Function pointers are ghastly. Even when I’m forced to use them, I always use typedefs to hide the ugliness:</p>\n<pre><code>class IntegerListener {\npublic :\n using number_changed_function = void (*)(int, int);\n using number_increased_function = void (*)(int);\n\n number_changed_function number_changed = nullptr;\n number_increased_function number_increased = nullptr;\n\n IntegerListener(number_changed_function&& number_changed, number_increased_function&& number_increased) {\n this->number_changed = number_changed;\n this->number_increased = number_increased;\n }\n};\n</code></pre>\n<p>That just looks a lot more like natural C++. And of course, with <code>std::function</code>:</p>\n<pre><code>class IntegerListener {\npublic :\n std::function<void (int, int)> number_changed = nullptr;\n std::function<void (int)> number_increased = nullptr;\n\n IntegerListener(std::function<void (int, int)>&& number_changed, std::function<void (int, int)>&& number_increased) {\n this->number_changed = number_changed;\n this->number_increased = number_increased;\n }\n};\n</code></pre>\n<p>Although you could use typedefs there too, which is probably a good idea for avoiding needless repetition.</p>\n<p>The one downside of using <code>std::function</code> over raw function pointers is that <code>std::function</code> objects are larger—sometimes quite a bit larger, in order to do the type erasure necessary to do all its tricks. But unless you want to accept the rather severe restrictions that raw function pointers come with, there’s no other option. (Well, there <em>are</em> other options, but they would require a redesign: you could, for example, you could use a polymorphic base class for your listeners, and use dynamic dispatch.)</p>\n<p>Now let’s focus on that constructor:</p>\n<pre><code>IntegerListener(void (*&&number_changed)(int, int), void (*&&number_increased)(int)) {\n this->number_changed = number_changed;\n this->number_increased = number_increased;\n}\n</code></pre>\n<p>I’m not sure why you’d want to use rvalue-references for your constructor parameters here. Did you try something and it would’t compile without them? I can’t see what purpose rvalue-referenes here serve, even theoretically.</p>\n<p>The other thing is: when you’re initializing data members, you almost always want to use data member initializers, rather than initializing them in the constructor’s body.</p>\n<p>This is probably more what you want:</p>\n<pre><code>IntegerListener(void (*number_changed)(int, int), void (*number_increased)(int)) :\n number_changed{number_changed},\n number_increased{number_increased}\n{}\n</code></pre>\n<p>Or even more correctly:</p>\n<pre><code>IntegerListener(void (*number_changed)(int, int), void (*number_increased)(int)) :\n number_changed{std::move(number_changed)},\n number_increased{std::move(number_increased)}\n{}\n</code></pre>\n<p>The moves are because there’s no need to <em>copy</em> the arguments from the function parameters to the data members (assuming you don’t want to use the function parameters again). Moving is more logically correct, and can be <em>much</em> faster (though it doesn’t matter here).</p>\n<p>Finally, I can’t imagine any reason why this constructor couldn’t be <code>noexcept</code>. If all it’s doing is just taking the parameters and moving them into the data members, then so long as the moves are <code>noexcept</code> (which, moves should <em>always</em> be <code>noexcept</code> wherever possible, and they are both for raw function pointers and <code>std::function</code>), there’s no chance of failure.</p>\n<p>So putting it altogether, if I were writing your listener class, I might do:</p>\n<pre><code>class IntegerListener\n{\npublic:\n using number_changed_type = std::function<void (int, int)>;\n using number_increased_type = std::function<void (int)>;\n\n number_changed_type number_changed = nullptr;\n number_increased_type number_increased = nullptr;\n\n IntegerListener(\n number_changed_type number_changed,\n number_increased_type number_increased) noexcept :\n number_changed{std::move(number_changed)},\n number_increased{std::move(number_increased)}\n {}\n};\n</code></pre>\n<p>Now on to the dispatcher….</p>\n<pre><code>std::vector<IntegerListener *> integer_listeners;\n</code></pre>\n<p>I don’t see any reason why you’d want to store <em>pointers</em> to the listeners, rather than just storing the listeners directly. You’re not doing dynamic dispatch (<code>IntegerListener</code> doesn’t have a virtual destructor), and there is no functional difference between storing the objects directly in the vector or storing them remotely. Using pointers for this just means poor performance due to the extra indirection and cache busting, and the need to manage memory, with no benefits.</p>\n<p>In fact, as I pointed out in my other comment, what you’re doing is actually just storing the address of temporary objects, which immediately die, leaving you with dangling pointers. If you actually wanted to store pointers, you would have to either manually allocate those pointers (or use global or static objects, I guess)—which means you also have to manually manage that memory with custom copy constructors and a destructor—or (and, really, this is the only option in modern C++… do <em>NOT</em> try manually allocating and managing memory), use smart pointers.</p>\n<p>But, as I said, there’s no benefit to using pointers <em>at all</em>, so there’s nothing to be gained from using smart pointers. Just store the objects in the vector directly. It’ll be faster, easier to code, and you won’t end up with critical bugs involving dangling pointers like the one you have (or leaks or double-frees or any of the other crap that comes with manual memory management… seriously <em>do not do manual memory management in C++</em>).</p>\n<pre><code>void set_number(int new_number) {\n for (IntegerListener *&integer_listener:integer_listeners) {\n (*integer_listener).number_changed(number, new_number);\n }\n if (new_number > number) {\n for (IntegerListener *&integer_listener:integer_listeners) {\n (*integer_listener).number_increased(new_number - number);\n }\n }\n number = new_number;\n}\n</code></pre>\n<p>If you’re going to store pointers in your vectors, there’s really no reason to iterate through them by reference. In fact, you’re just paying for a double indirection which you don’t even use.</p>\n<p><em>But!</em> If you’re going to store the actual listeners in your vectors, then, yes, you should take them by reference… but you should really take them by <code>const</code> reference, because you’re not going to be modifying them.</p>\n<p>I generally recommend to use the universal form of range-<code>for</code>. This:</p>\n<pre><code>for (auto&& item : range)\n</code></pre>\n<p><em>always</em> works, for <em>everything</em>, and <em>never</em> does the wrong thing. It should be the default thing you write whenever you write a range-<code>for</code>.</p>\n<p>(And no, it is <em>NOT</em> the same as doing <code>for (IntegerListener&& item : range)</code>. That usually <em>won’t</em> work… and it won’t work for your case. It’s <code>auto&&</code> or it’s a craps shoot. <em>Only</em> <code>auto&&</code> <em>always</em> works.)</p>\n<p><em>However</em>… if you want to be more explicit about what your code is actually doing, you could do:</p>\n<pre><code>for (auto& item : range) // to signal you will be modifying the items\n// or\nfor (auto const& item : range) // if you'll just be reading them\n</code></pre>\n<p>These don’t <em>always</em> work, but they <em>almost</em> always work, and if you really mean what they say—that you’re either modifying the items or you’re definitely not and you’re just inspecting them—then they <em>pretty much</em> always work.</p>\n<p>So I’d probably write:</p>\n<pre><code>for (auto const& integer_listener : integer_listeners)\n integer_listener.number_changed(number, new_number);\n</code></pre>\n<p>unless I was feeling lazy, in which case I’d use the <code>auto&&</code> form.</p>\n<pre><code>void add_number_changed_listener(IntegerListener &&integer_listener) {\n integer_listeners.push_back(&integer_listener);\n}\n</code></pre>\n<p>This is really the only broken function in the code. Everything else is correct, though maybe not the most efficient, and maybe not following C++ best practices or styles.</p>\n<p>But this function has two problems. First, it takes the argument by rvalue reference. I can’t imagine why you’d want to do that. It doesn’t really make any sense. What you’re saying with that is that you <em>only</em> want to take <em>temporary-constructed</em> integer listeners. In other words, you’re saying:</p>\n<pre><code>// this is fine:\ninteger.add_number_changed_listener(IntegerListener{f1, f2});\n\n// but this is absolutely wrong, and should not compile:\nauto il = IntegerListener{f1, f2};\ninteger.add_number_changed_listener(il);\n</code></pre>\n<p>But why? What’s wrong with making an integer listener and passing it to <em>two</em> integers? Maybe I have two integers that I want to keep track of changes to. Why am I banned from using the same listener for both?</p>\n<p>The second problem with this function is that you only take the address of the listener. Even if you weren’t <em>requiring</em> temporary-constructed listeners, that’s an accident waiting to happen, because even if the listener isn’t temporary—which means it’s very likely to die almost immediately—it still might not live long enough to still be active when the dispatcher wants to signal an event.</p>\n<p>You have two options here:</p>\n<ul>\n<li><em>either</em> you <em>mandate</em> that users keep listener objects around for as long as needed, and make it their problem to keep track of that (which would be a terrible, bug-prone design); <em>or</em></li>\n<li>you simply keep the listener object with the dispatcher, so it <em>has</em> to stick around as long as the dispatch object exists.</li>\n</ul>\n<p>In other words, don’t muck around with pointers and the address-of operator ('&'). Just do the natural thing:</p>\n<pre><code>void add_number_changed_listener(IntegerListener integer_listener) {\n integer_listeners.push_back(integer_listener);\n}\n</code></pre>\n<p>And even better, and more technically correct: you don’t really want a <em>copy</em> of the listener stored in the vector… you want the actual listener object. So you want to move what you were given into the array:</p>\n<pre><code>void add_number_changed_listener(IntegerListener integer_listener) {\n integer_listeners.push_back(std::move(integer_listener));\n}\n</code></pre>\n<p>Now as a user of the class, <em>I</em> have control. <em>I</em> get to decide if I want to give you a temporary-constructed listener, or if I want to copy a listener to multiple integers. And no matter what I choose, everything just works.</p>\n<p>That’s it for the line-by-line review! Overall, the only “problem” with it that would make me reject it from a code base I was responsible for is that the vector <code>integer_listeners</code> holds pointers rather than actual objects, and those pointers are almost certainly going to be dangling because <code>add_number_changed_listener()</code> only takes temporaries. If you only made two changes:</p>\n<ol>\n<li>change <code>integer_listeners</code> to be a <code>std::vector<IntegerListener></code> (not <code>std::vector<IntegerListener*></code>); and</li>\n<li>change <code>add_number_changed_listener()</code> to store (by copying or—better—moving) the passed listener, not just its address</li>\n</ol>\n<p>then I would consider the code acceptable. (Though, of course, there are a number of other improvements you could make, like using <code>std::function</code> rather than raw function pointers`.)</p>\n<p>To answer your concerns:</p>\n<ol>\n<li>The design is pretty optimal, yes. There are a few minor touch-ups here and there that make it even more efficient, but the basic design is sound. And, actually, it’s a pretty good design, in my opinion.</li>\n<li>Is the design good C++? Yes, I think so. Even without the changes I suggested (other than fixing those critical bugs), I’d say it fits well with good C++ philosophy. There are other ways of doing it, of course, and every design has its pros and cons. But this design is, I think, quite good. I’d use it.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T22:30:28.573",
"Id": "481590",
"Score": "0",
"body": "THANK YOU SO MUCH FOR YOU TIME. i just learned 20 years in 10 minutes. i have to go and research many things that you have mentioned and see why they are the way you are saying they are like I didn't understand the auto&& part. Just thank you :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T18:48:49.410",
"Id": "245239",
"ParentId": "245219",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "245239",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T09:40:52.680",
"Id": "245219",
"Score": "2",
"Tags": [
"c++",
"beginner"
],
"Title": "Java-like listeners in C++"
}
|
245219
|
<p>I have a pandas dataframe (called <code>base_mortality</code>) with 1 column and n rows, which is of the following form:</p>
<pre><code> age | death_prob
---------------------------
60 | 0.005925
61 | 0.006656
62 | 0.007474
63 | 0.008387
64 | 0.009405
65 | 0.010539
66 | 0.0118
67 | 0.013201
68 | 0.014756
69 | 0.016477
</code></pre>
<p><code>age</code> is the index and <code>death_prob</code> is the probability that a person who is a given age will die in the next year. I want to use these death probabilities to project the expected annuity payment that would be paid to an annuitant over the next t years.</p>
<p>Suppose I have 3 annuitants, whose names and ages are contained in a dictionary:</p>
<pre><code>policy_holders = {'John' : 65, 'Mike': 67, 'Alan': 71}
</code></pre>
<p>Then I would want to construct a new dataframe whose index is time (rather than age) which has 3 columns (one for each annuitant) and t rows (one for each time step). Each column should specify the probability of death for each policy holder at that time step. For example:</p>
<pre><code> John Mike Alan
0 0.010539 0.013201 0.020486
1 0.011800 0.014756 0.022807
2 0.013201 0.016477 0.025365
3 0.014756 0.018382 0.028179
4 0.016477 0.020486 0.031269
.. ... ... ...
96 1.000000 1.000000 1.000000
97 1.000000 1.000000 1.000000
98 1.000000 1.000000 1.000000
99 1.000000 1.000000 1.000000
100 1.000000 1.000000 1.000000
</code></pre>
<p>At present, my code for doing this is as follows:</p>
<pre><code>import pandas as pd
base_mortality = pd.read_csv('/Users/joshchapman/PycharmProjects/VectorisedAnnuityModel/venv/assumptions/base_mortality.csv', index_col=['x'])
policy_holders = {'John' : 65, 'Mike': 67, 'Alan': 71}
out = pd.DataFrame(index=range(0,101))
for name, age in policy_holders.items():
out[name] = base_mortality.loc[age:].reset_index()['age']
out = out.fillna(1)
print(out)
</code></pre>
<p>However, my aim is to remove this loop and achieve this using vector operations (i.e. pandas and/or numpy functions). Any suggestions on how I might improve my code to work in this way would be great!</p>
|
[] |
[
{
"body": "<p>Enter <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.cut.html\" rel=\"nofollow noreferrer\"><code>pandas.cut</code></a>. It returns the bin in which each event lies. You can even pass the labels directly. This way you can reduce it to a Python loop over the people:</p>\n<pre><code>import pandas as pd\nimport numpy as np\n\nage_bins = range(59, 70) # one more than the probabilities\ndeath_prob = [0.005925, 0.006656, 0.007474, 0.008387, 0.009405, 0.010539, 0.0118,\n 0.013201, 0.014756, 0.016477]\n\npolicy_holders = {'John' : 65, 'Mike': 67, 'Alan': 71}\n\nvalues = {name: pd.cut(range(age, age + 101), age_bins, labels=death_prob)\n for name, age in policy_holders.items()}\n\nout = pd.DataFrame(values, dtype=np.float64).fillna(1)\nprint(out)\n\n# John Mike Alan\n# 0 0.010539 0.013201 1.0\n# 1 0.011800 0.014756 1.0\n# 2 0.013201 0.016477 1.0\n# 3 0.014756 1.000000 1.0\n# 4 0.016477 1.000000 1.0\n# .. ... ... ...\n# 96 1.000000 1.000000 1.0\n# 97 1.000000 1.000000 1.0\n# 98 1.000000 1.000000 1.0\n# 99 1.000000 1.000000 1.0\n# 100 1.000000 1.000000 1.0\n# \n# [101 rows x 3 columns]\n</code></pre>\n<p>Note that the hin edges need to be one larger than the labels, because technically, this is interpreted as <code>(59, 60], (60, 61], ...</code>, i.e. including the right edge.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T10:18:16.827",
"Id": "481927",
"Score": "0",
"body": "Thanks for your help on this one! Quick question though: what if the probabilities are not unique? I've tried replacing the last probability with the second to last and this gives the error `Categorical categories must be unique` from `pd.cut`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T10:27:27.700",
"Id": "481929",
"Score": "0",
"body": "@JRChapman In that case you will have to pass `labels=False` (or `None`, not quite sure atm) and use the resulting indices to index into `pd.Series(death_prob)`. See also the first revision of my answer for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T13:30:41.907",
"Id": "481947",
"Score": "0",
"body": "@JRChapman: It is `False`, and here is the direct link to that revision: https://codereview.stackexchange.com/revisions/245225/1"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T12:51:13.047",
"Id": "245225",
"ParentId": "245223",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "245225",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T12:10:53.063",
"Id": "245223",
"Score": "2",
"Tags": [
"python",
"numpy",
"pandas"
],
"Title": "Construct a numpy array by repeating a 1 dimensional array sliced at different indices"
}
|
245223
|
<p>Basic idea (foo and foa are filenames):</p>
<p><a href="https://i.stack.imgur.com/STy5F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/STy5F.png" alt="enter image description here" /></a></p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
namespace FileIndexer
{
class FileIndexTrie
{
private class CachablePath
{
public string filename;
public int cachedPath;
//stolen from: https://stackoverflow.com/a/263416/13687491
public override int GetHashCode()
{
int hash = 13;
hash = (hash * 7) + filename.GetHashCode();
hash = (hash * 7) + cachedPath.GetHashCode();
return hash;
}
public override bool Equals(Object obj)
{
if (obj == null || !(obj is CachablePath))
return false;
else
return filename.Equals(((CachablePath)obj).filename) && cachedPath == ((CachablePath)obj).cachedPath;
}
};
private Dictionary<char, FileIndexTrie> nodes;
private HashSet<CachablePath> nodeFiles;
private static Dictionary<int, string> pathCache = new Dictionary<int, string>();
public FileIndexTrie()
{
this.nodes = new Dictionary<char, FileIndexTrie>();
this.nodeFiles = null;
}
public bool insert(string word, string filePath)
{
if (word == null || filePath == null)
return false;
try
{
insert(word, filePath, this);
}
catch (Exception ex)
{
if (ex is ArgumentException || ex is PathTooLongException)
Console.WriteLine("Trie: Invalid path \"" + filePath + "\", insert() failed for word:\"" + word + "\"");
return false;
}
return true;
}
private void insert(string word, string filePath, FileIndexTrie currentNode)
{
if (word.Length >= 1)
{
if (!currentNode.nodes.ContainsKey(word[0]))
currentNode.nodes[word[0]] = new FileIndexTrie();
insert(word.Substring(1), filePath, currentNode.nodes[word[0]]);
}
else if (word.Length == 0)
{
string path = Path.GetDirectoryName(filePath);
CachablePath currentPathFilename = new CachablePath();
if (currentNode.nodeFiles == null)
currentNode.nodeFiles = new HashSet<CachablePath>();
if (!pathCache.ContainsKey(path.GetHashCode()))
pathCache[path.GetHashCode()] = path;
currentPathFilename.cachedPath = path.GetHashCode();
currentPathFilename.filename = Path.GetFileName(filePath);
currentNode.nodeFiles.Add(currentPathFilename);
}
}
public List<string> getFilepaths(string word)
{
if (word == null)
return new List<string>();
return getFilepaths(word, this);
}
private List<string> getFilepaths(string word, FileIndexTrie currentNode)
{
if (word.Length >= 1)
{
if (!currentNode.nodes.ContainsKey(word[0]))
return new List<string>();
return getFilepaths(word.Substring(1), currentNode.nodes[word[0]]);
}
else if (word.Length == 0 && currentNode.nodeFiles != null)
{
List<string> ret = new List<string>();
foreach (CachablePath cp in currentNode.nodeFiles)
ret.Add(pathCache[cp.cachedPath] + "\\" + cp.filename);
return ret;
}
return new List<string>();
}
public List<string> getFilepathsStartsWith(string word)
{
List<string> ret = new List<string>();
if (word == null)
return ret;
getFilepathsStartsWith(word, this, ret);
return ret;
}
private void getFilepathsStartsWith(string word, FileIndexTrie currentNode, List<string> foundFilePaths)
{
if (word.Length > 1)
{
if (!currentNode.nodes.ContainsKey(word[0]))
return;
getFilepathsStartsWith(word.Substring(1), currentNode.nodes[word[0]], foundFilePaths);
}
else if (word.Length == 1)
{
getAllChildrenPaths(currentNode.nodes[word[0]], foundFilePaths);
}
}
private void getAllChildrenPaths(FileIndexTrie currentNode, List<string> foundFilePaths)
{
if (currentNode.nodeFiles != null)
foreach (CachablePath cp in currentNode.nodeFiles)
foundFilePaths.Add(pathCache[cp.cachedPath] + "\\" + cp.filename);
foreach (KeyValuePair<char, FileIndexTrie> node in currentNode.nodes)
getAllChildrenPaths(node.Value, foundFilePaths);
}
}
}
</code></pre>
<p>I tried to create a trie to index and search for files. Every node has a <code>Dictionary<char, FileIndexTrie> nodes</code> which contains all the children, the key is the char which will follow next to the current one (in the string). It also contains a <code>HashSet<CachablePath> nodeFiles</code> which holds all the files with file path associated to the current node. I created a "cache" <code>Dictionary<int, string> pathCache</code> since I expect alot of paths that will repeat.</p>
<p>Brief Usage example:</p>
<pre><code> static void Main(string[] args)
{
FileIndexTrie root = new FileIndexTrie();
root.insert("foo", @"C:\example\foo");
root.insert("foa", @"C:\example\foa");
root.insert("foa", @"C:\example\foa");
root.insert("foa", @"C:\example\foa2");
root.insert("foa2", @"C:\example\foa2");
root.insert("foa3", @"C:\example2\foa3");
root.insert("doa", @"C:\example3\doa moa");
root.insert("mao", @"C:\example3\doa moa");
root.insert("", @"C:\example\foa");
root.insert("", @"");
List<string> test = root.getFilepaths("fo");
List<string> test1 = root.getFilepaths("foa");
List<string> test2 = root.getFilepathsStartsWith("fo");
List<string> test3 = root.getFilepathsStartsWith("d");
List<string> test4 = root.getFilepathsStartsWith("f");
}
</code></pre>
<p><code>.insert</code> will index the path in the trie. <code>.getFilepaths</code> will look for a exact match and <code>.getFilepathsStartsWith</code> will look for a partial match of the string start.</p>
<p><strong>Concerns:</strong></p>
<ol>
<li>the model class <code>CachablePath</code> within the <code>FileIndexTrie</code> class. I would seperate it but it feels like this cannot be used outside of this class</li>
<li>Does <code>string.GetHashCode()</code> provide a usable hashcode for this use ?</li>
<li><code>private List<string> getFilepaths(string word, FileIndexTrie currentNode)</code> method seems messy, I lost track how it works, seems like returning the List everywhere could look better</li>
<li>performance of <code>foreach (KeyValuePair<char, FileIndexTrie> node in currentNode.nodes)</code></li>
</ol>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T13:08:08.843",
"Id": "245226",
"Score": "2",
"Tags": [
"c#",
"file",
"hash-map",
"search",
"trie"
],
"Title": "Trie to index files and search for them"
}
|
245226
|
<p>I am slowly creating a flow field pathfinding solution for Unity3D. I'm trying to follow <a href="http://www.gameaipro.com/GameAIPro/GameAIPro_Chapter23_Crowd_Pathfinding_and_Steering_Using_Flow_Field_Tiles.pdf" rel="nofollow noreferrer">Elijah Emerson's description</a>, which appears in the book 'Game AI Pro' (volume 1). In <a href="https://codereview.stackexchange.com/questions/244997/coordinates-struct-for-flow-field-pathfinding-am-i-doing-this-right">this question</a> I ask about the Coordinates object which I use here. I have subsequently cached some variables.</p>
<p>In my tests, the stop watch has recorded times for each part of the flow field generation, for example:</p>
<pre><code>FlowField calculations complete 1.0664ms
path request complete 0.1309ms
reset complete 0.014ms
goal allocation complete 0.1427ms
integration fields complete 0.4417ms
flow fields complete 0.3318ms
</code></pre>
<p>Integration and flow passes are the slowest parts, and I wonder is there anything I can do to speed them up some more?</p>
<p>I've followed some more advice from the aforementioned book, such as saving node neighbours on initialisation, instead of trying to find them at run time. That has helped. I also used <a href="https://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx" rel="nofollow noreferrer">James McCaffrey's priority queue</a> with an internal binary heap. Getting rid of lists, and list comparisons (flagging a boolean property instead works wonders), and replacing them with priority queues seems the biggest gain by far.</p>
<p>I realise it may be trying to squeeze blood from a stone at this point (having dropped calculation time from 100ms to 1.1ms), but I'm eager for any ideas which can help.</p>
<p><strong>Integration Pass:</strong></p>
<pre><code>public void IntegrationPass(PriorityQueue<Coordinates> openList)
{
while (openList.Count > 0)
{
Coordinates theseCoordinates = openList.Dequeue();
// Update Integration value.
//foreach (Coordinates neighbour in FindNeighbours(theseCoordinates, true, true))
foreach (Coordinates neighbour in IntegrationPassNeighbours[theseCoordinates.sectorX, theseCoordinates.sectorY])
{
if (neighbour.Flag)
{
continue;
}
byte cost = neighbour.Cost.Value;
int oldIntegration = neighbour.Integration.Value + cost;
int newIntegration = theseCoordinates.Integration.Value + cost;
if (neighbour.IsWalkable && newIntegration < oldIntegration)
{
neighbour.Integration.Value = newIntegration;
neighbour.SetFlag(true);
openList.Enqueue(neighbour, newIntegration);
}
}
}
}
</code></pre>
<p><strong>Flow Pass:</strong></p>
<pre><code>public void FlowPass()
{
foreach (Coordinates node in CoordinatesField)
{
if (node.IsBlocked)
{
continue;
}
int bestValue = ushort.MaxValue;
Coordinates bestNode = Coordinates.zero;
//foreach (Coordinates neighbour in FindNeighbours(node, false, false))
foreach (Coordinates neighbour in FlowPassNeighbours[node.sectorX, node.sectorY])
{
int neighbourValue = neighbour.Integration.Value;
if (neighbourValue < bestValue)
{
bestValue = neighbourValue;
bestNode = neighbour;
}
}
if (!bestNode.Equals(Coordinates.zero))
{
int comparisonX = bestNode.worldX - node.worldX;
int comparisonY = bestNode.worldY - node.worldY;
// North
if (comparisonX == 1 && comparisonY == 0)
{
node.Flow.Value = 1;
}
// North East
else if (comparisonX == 1 && comparisonY == -1)
{
node.Flow.Value = 2;
}
// East
else if (comparisonX == 0 && comparisonY == -1)
{
node.Flow.Value = 3;
}
// South East
else if (comparisonX == -1 && comparisonY == -1)
{
node.Flow.Value = 4;
}
// South
else if (comparisonX == -1 && comparisonY == 0)
{
node.Flow.Value = 5;
}
// South West
else if (comparisonX == -1 && comparisonY == 1)
{
node.Flow.Value = 6;
}
// West
else if (comparisonX == 0 && comparisonY == 1)
{
node.Flow.Value = 7;
}
// North West
else if (comparisonX == 1 && comparisonY == 1)
{
node.Flow.Value = 8;
}
}
}
}
</code></pre>
<p>For clarity, here is the lookup referenced by Flow.Value:</p>
<pre><code>public static Vector3[] DirectionLookUp =
{
Vector3.zero,
new Vector3(1, 0, 0),
new Vector3(1, 0, -1),
new Vector3(0, 0, -1),
new Vector3(-1, 0, -1),
new Vector3(-1, 0, 0),
new Vector3(-1, 0, 1),
new Vector3(0, 0, 1),
new Vector3(1, 0, 1)
};
</code></pre>
|
[] |
[
{
"body": "<p>In FlowPass you have a long sequence of if .. {} .. else if {} statements.</p>\n<p>I suggest trying a lookup table to compute the value, say</p>\n<pre><code> node.Flow.Value = Lookup [ (comparisonX+1)*3 + (comparisonY+1) ]\n</code></pre>\n<p>where Lookup is initialised as</p>\n<pre><code>int [] Lookup = new int[] { 3, ... }\n</code></pre>\n<p>It may even be possible to compute this with a simple arithmetic expression, although I cannot immediately see an expression that works. From the code supplied I am not clear how Flow.Value is used, it may be possible to choose a different encoding which is simpler and faster to calculate.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T16:42:33.350",
"Id": "481563",
"Score": "0",
"body": "This is a good point. It's funny because Flow.Value is used to reference a lookup table of Vector3 directions (N, NE, E, etc)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T16:46:22.937",
"Id": "481564",
"Score": "0",
"body": "I have added the table to the question. I have also changed the value range from 0-7 to 1-8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T16:50:44.103",
"Id": "481565",
"Score": "0",
"body": "once you have an answer DO NOT alter your code. That tends to invalidate the answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T16:53:26.627",
"Id": "481567",
"Score": "0",
"body": "It looks like a 2D array lookup would make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T17:07:32.127",
"Id": "481569",
"Score": "0",
"body": "@ThomasWard It didn't invalidate George's answer (it provided the context he asked for), your edit however did break the solution. Vector3.zero was added to the lookup, so the default flow direction wasn't north, which required the numbers to be shifted up by one. Flow.Value of 0 is goal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T17:19:40.363",
"Id": "481571",
"Score": "3",
"body": "@inappropriateCode Ordinarily I'd agree with Thomas here, but it seems George simply was too fast with the answer and should've left a comment instead of an answer if the question was unclear. For now, we'll leave the edit as-is unless a moderator decides otherwise. Please keep in mind for next time we do take answer invalidation seriously, even if it only looks like one."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T15:50:16.277",
"Id": "245231",
"ParentId": "245227",
"Score": "1"
}
},
{
"body": "<p>Since I don't know the pipeline of C# source code to executable (and I don't have enough experience to make an educated guess) you'll have to (micro)benchmark all the suggestions yourself. Potentially the code changes I'm pushing for are made obsolete by compiler, but hopefully these are improvements that give the compiler more room to do its thing.</p>\n<p>I'm also only able to offer half an answer, I don't know the algorithim so I can't suggest any major improvements. I reckon you'll have more success improving the algorithms and data structures involved as the code looks pretty clean.</p>\n<hr />\n<p><strong>Integration Pass</strong></p>\n<p>The neighbour loop skips any neighbours with a Flag set, does some work, and then checks another boolean associated with the neighbour. You could do both these checks at the start, and avoid unnecessary work if the second check fails.</p>\n<pre><code>foreach (Coordinates neighbour in IntegrationPassNeighbours[theseCoordinates.sectorX, theseCoordinates.sectorY])\n{\n if (neighbour.Flag || !neighbour.IsWalkable)\n {\n continue;\n }\n\n byte cost = neighbour.Cost.Value;\n int oldIntegration = neighbour.Integration.Value + cost;\n int newIntegration = theseCoordinates.Integration.Value + cost;\n\n if (newIntegration < oldIntegration)\n {\n neighbour.Integration.Value = newIntegration;\n neighbour.SetFlag(true);\n openList.Enqueue(neighbour, newIntegration);\n }\n}\n</code></pre>\n<p>The cost calculation does slightly more work than it needs to, and the result is not needed unless a condition passes. Looking at the code (below <code>byte cost = ...</code>) without names or types looks a little bit like this</p>\n<pre><code>D = A + C;\nE = B + C;\nif (E < D)\n{\n // Use E\n}\n</code></pre>\n<p>(Assuming no overflow) we don't need to compare D and E if we compare A and B. In other words, lets delay the computation of D and E until inside the block, and see what happens</p>\n<pre><code>if (B + C < A + C) // Replacing E and D with their definitions\n{\n D = A + C\n E = B + C\n // Use E\n}\n</code></pre>\n<p>Now it should be more obvious that 1) we can drop the + C from both sides of the condition and 2) we don't need D.</p>\n<pre><code>if (B < A)\n{\n E = B + C\n // Use\n}\n</code></pre>\n<p>Or back to code</p>\n<pre><code>foreach (Coordinates neighbour in IntegrationPassNeighbours[theseCoordinates.sectorX, theseCoordinates.sectorY])\n{\n if (neighbour.Flag || !neighbour.IsWalkable)\n {\n continue;\n }\n\n int neighbourIntegration = neighbour.Integration.Value;\n int theseIntegration = theseCoordinates.Integration.Value;\n if (theseIntegration < neighbourIntegration)\n {\n byte cost = neighbour.Cost.Value;\n int newIntegration = theseIntegration + cost;\n neighbour.Integration.Value = newIntegration;\n neighbour.SetFlag(true);\n openList.Enqueue(neighbour, newIntegration);\n }\n}\n</code></pre>\n<hr />\n<p><strong>Flow Pass</strong></p>\n<pre><code>foreach (Coordinates node in CoordinatesField)\n{\n if (node.IsBlocked)\n {\n continue;\n }\n ...\n}\n</code></pre>\n<p>If this is an unpredictable condition at the start of the loop, it might be a source of performance pain. Can you somehow remove this check? If the number of nodes which are clear (not labelled as blocked) is tiny, and this condition is met most of the time, you might be better off maintaining a separate data structure just for those nodes. It would be at a small memory cost, but it might alleviate pain for other tools like the JIT or branch predictor. If most nodes are clear, it might be worth doing the computation anyway, and doing the check later or somehow ignoring the result.</p>\n<p>If it is not unpredictable, can you take advantage of the pattern, and still remove the condition?</p>\n<p>If I have the general algorithm down, you find the smallest neighbour in a neighbourhood around the current node, and point in the direction of it. I'm sure there are a million ways to optimise this pattern, such as running the function in parallel over all the neighbourhoods at once, or doing some magic with a sliding window, but I don't know how easy they would be to implement. Perhaps you might be able to express each node is a pixel in an image, and use some highly optimised routine for computing gradients using convolutions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T22:55:31.920",
"Id": "245248",
"ParentId": "245227",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "245248",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-09T13:56:19.807",
"Id": "245227",
"Score": "4",
"Tags": [
"c#",
"pathfinding",
"unity3d"
],
"Title": "Speed Up Flow Field Algorithm?"
}
|
245227
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.