body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<h2>Context and initial idea</h2>
<p>I'm trying to teach myself the <a href="https://www.martinfowler.com/bliki/CQRS.html" rel="noreferrer">CQRS</a> and <a href="https://martinfowler.com/eaaDev/EventSourcing.html" rel="noreferrer">Event Sourcing</a> patterns by developing a simple ASP.NET Core application, loosely following <a href="https://github.com/gregoryyoung/m-r" rel="noreferrer">Greg Young's example CQRS implementation on GitHub</a>.</p>
<p>Once a command has been handled and the resulting events have been persisted to the database, I want to have any event handlers process the event on a background thread so that the thread that initiated the command can return without having to wait for the event handlers.</p>
<p>I've been taught that using <code>Task.Run()</code> for fire-and-forget-like background work like this is a bad idea for a multitude of reasons. I also want to be able to use scoped services from <code>IServiceProvider</code> (the default ASP.NET Core DI container) without having to worry about the services being disposed before the background work completes.</p>
<p><a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2#queued-background-tasks" rel="noreferrer">The ASP.NET Core documentation suggests a queue-based approach for background work</a> which is based on the <code>IHostedService</code> abstraction and will run in the background for the entire duration of the web host and will even try to shut down any executing background work gracefully when the host stops. With some modifications, we could even have this service manage the service scopes of any enqueued background work (using <code>IServiceProvider.CreateScope()</code> and passing the scoped service provider to a <code>Func<IServiceProvider, CancellationToken, Task></code> delegate) to be able to utilize the DI container to its full potential. Sounds great!</p>
<p>There is just one problem with this approach: it process the background work items in sequence, one at a time. If at all possible, <strong>I want to execute the background work in parallel</strong>.</p>
<h2>Implementation</h2>
<p>The implementation I've arrived at involves two parts: the interface <code>IBackgroundTaskExecutor</code>, which defines a simple <code>Execute()</code> method taking a delegate that defines the background work, and the class <code>BackgroundTaskExecutingService</code> which implements both the aforementioned interface and <code>IHostedService</code> and runs as a <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2" rel="noreferrer">hosted background service</a> alongside the web host.</p>
<p><code>BackgroundTaskExecutingService</code> has the following responsibilities:</p>
<ul>
<li>Process any incoming background work in parallel.</li>
<li>Log and handle any unhandled exceptions that are thrown by the background work.</li>
<li>Keep references to the executing <code>Task</code> instances until they complete.</li>
<li>Gracefully (attempt to) shut down all currently executing tasks when the web host stops.</li>
</ul>
<p>(While not required by the contract that the ASP.NET Core web host specifies, the service can also be restarted after it has been stopped.)</p>
<p>All consumers have to do to dispatch background work is to retrieve a reference to the <code>IBackgroundTaskExecutor</code> service from the DI container and pass the background work they wish to process to <code>Execute()</code>.</p>
<p>The implementation is designed as a reusable library and includes an <code>IServiceCollection</code> extension method for registering the implementation and any necessary dependencies.</p>
<h2>Code</h2>
<p><em>IBackgroundTaskExecutor.cs</em></p>
<pre><code>using BackgroundTaskFactory = System.Func<
System.IServiceProvider,
System.Threading.CancellationToken,
System.Threading.Tasks.Task>;
namespace BackgroundTasks
{
public interface IBackgroundTaskExecutor
{
void Execute(BackgroundTaskFactory backgroundTaskFactory);
}
}
</code></pre>
<p><em>BackgroundTaskExecutingService.cs</em></p>
<pre><code>using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using BackgroundTaskFactory = System.Func<
System.IServiceProvider,
System.Threading.CancellationToken,
System.Threading.Tasks.Task>;
namespace BackgroundTasks
{
public sealed class BackgroundTaskExecutingService : IBackgroundTaskExecutor, IHostedService, IDisposable
{
private readonly IServiceProvider _services;
private readonly ILogger _logger;
private State _state;
private ConcurrentDictionary<Task, byte> _executingTasks; // used as ConcurrentHashSet<Task>
private CancellationTokenSource _stoppingCts;
public BackgroundTaskExecutingService(
IServiceProvider services,
ILogger<BackgroundTaskExecutingService> logger)
{
if (services == null) throw new ArgumentNullException(nameof(services));
if (logger == null) throw new ArgumentNullException(nameof(logger));
_services = services;
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
if (_state == State.Started) return Task.CompletedTask;
_executingTasks = new ConcurrentDictionary<Task, byte>();
_stoppingCts = new CancellationTokenSource();
_state = State.Started;
_logger.LogInformation("The background task executing service has started.");
return Task.CompletedTask;
}
private void AssertStarted()
{
if (_state != State.Started)
{
throw new InvalidOperationException("The background task executing service is not started.");
}
}
public void Execute(BackgroundTaskFactory backgroundTaskFactory)
{
if (backgroundTaskFactory == null) throw new ArgumentNullException(nameof(backgroundTaskFactory));
AssertStarted();
_ = ExecuteAsync(backgroundTaskFactory);
}
private async Task ExecuteAsync(BackgroundTaskFactory backgroundTaskFactory)
{
var task = ExecuteAndHandleExceptionAsync(backgroundTaskFactory);
_executingTasks.TryAdd(task, default);
await task;
_executingTasks.TryRemove(task, out _);
}
private async Task ExecuteAndHandleExceptionAsync(BackgroundTaskFactory backgroundTaskFactory)
{
try
{
using (var scope = _services.CreateScope())
{
await backgroundTaskFactory(scope.ServiceProvider, _stoppingCts.Token);
}
}
catch (OperationCanceledException e) when (_stoppingCts.IsCancellationRequested)
{
_logger.LogInformation(e, "A background task was canceled.");
}
catch (Exception e)
{
_logger.LogError(e, "A background task threw an unhandled exception.");
}
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_state == State.Stopped) return;
try
{
_logger.LogInformation("The background task executing service is stopping.");
_stoppingCts.Cancel();
}
finally
{
// wait for any executing tasks to complete or the graceful shutdown process to be canceled
await Task.WhenAny(
Task.WhenAll(_executingTasks.Keys),
Task.Delay(Timeout.Infinite, cancellationToken));
_state = State.Stopped;
_logger.LogInformation("The background task executing service has stopped.");
}
}
public void Dispose()
{
_stoppingCts?.Cancel();
}
private enum State
{
Stopped,
Started
}
}
}
</code></pre>
<p><em>BackgroundTasksServiceCollectionExtensions.cs</em></p>
<pre><code>using System;
using BackgroundTasks;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
namespace Microsoft.Extensions.DependencyInjection
{
public static class BackgroundTasksServiceCollectionExtensions
{
public static IServiceCollection AddBackgroundTasks(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
services.AddLogging();
services.TryAddSingleton<BackgroundTaskExecutingService>();
services.TryAddSingleton<IBackgroundTaskExecutor>(
serviceProvider => serviceProvider.GetService<BackgroundTaskExecutingService>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHostedService, BackgroundTaskExecutingService>(
serviceProvider => serviceProvider.GetService<BackgroundTaskExecutingService>()));
return services;
}
}
}
</code></pre>
<h2>Example usage</h2>
<p>This is an example of how the <code>IBackgroundTaskExecutor</code> is used within my web application to dispatch event messages to event handlers on a background thread:</p>
<pre><code>private readonly IBackgroundTaskExecutor _backgroundTaskExecutor;
public void Dispatch<TEvent>(EventMetadata<TEvent> eventMetadata) where TEvent : Event
{
_backgroundTaskExecutor.Execute((services, cancellationToken) =>
{
var eventHandlers = services.GetServices<IEventHandler<TEvent>>();
return Task.WhenAll(eventHandlers.Select(eventHandler => eventHandler.HandleAsync(
eventMetadata,
cancellationToken)));
});
}
</code></pre>
<h2>Questions and concerns</h2>
<ul>
<li>Are there any immediate problems with this design? Am I being horribly naïve to use this as a solution to my problem?</li>
<li>This is for a relatively small application (a personal blog), but should I be concerned about things like thread starvation?</li>
<li>I'm not using <code>ConfigureAwait(false)</code> anywhere because it's not necessary for ASP.NET Core. Assuming I want to put this out as a reusable library targeting .NET Standard 2.0 (where it might be used by frameworks that have a <code>SynchronizationContext</code>)--on what lines would I need to use <code>ConfigureAwait(false)</code>?</li>
<li>Is there anything else that sticks out or looks bad?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T10:26:56.537",
"Id": "418959",
"Score": "0",
"body": "Implementing Background Tasks in Web Applications is hard. Maybe you can check out [Hangfire](https://www.hangfire.io/), a library for preforming Background Processing in Web Applications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T11:07:20.307",
"Id": "419061",
"Score": "0",
"body": "@VolkmarRigo I considered using Hangfire, and if I needed support for retryable and/or scheduled tasks I probably would, but for now the problem seems simple enough that I want to try and solve it without tacking on an additional dependency."
}
] | [
{
"body": "<p>just come across this and I'm sure by now you've figured a lot of things out, but thought I'd add my 2 cents worth.</p>\n\n<p>I wouldn't be worried about thread starvation, I would though be worried! I've played with Greg Young's m-r example a few times, from memory it processes events in-process which is a nice way to get things started. Ideally though if you don't want to do that the \"best\" way to go is to put the events on some kind of queue be it RabbitMQ, AWS SQS, Azure Service Bus or event MSMQ (but don't use MSMQ, ever!!!). Once your events are on a queue you can write another application/process that can read them and process at will.</p>\n\n<p><strong>Queue Benefits:</strong></p>\n\n<ul>\n<li>Resilience: This will make your system more resilient, if there's a crash during processing of an event it will just be put back on the queue and processed another time. Days even if you have a bug that needs fixing before you want the rest of the events to be processed (I've actually done this in the past, although I can definitely say it's not fun)</li>\n<li>Scale: You can also scale with more cunning and precision. You can scale your event processing independently of your website and if you so wish you could have one process for each type of event and so you could scale per event type at the extreme end.</li>\n</ul>\n\n<p><strong>IHostedService</strong></p>\n\n<p>I'm working with IHostedService at the moment, I've written a console app that just runs one IHostedService (and reads events off a queue funnily enough). The problem that lead me to this page is that the hosted service runs in a background thread out of my control and I'm currently getting an exception thrown that no try/catch is picking up (I was taught to let exceptions bubble up and this exception is not now I'm having to put try/catch everywhere to find where the problem is). This exception is currently taking down the entire application, from what I've read this is a thing with IHostedServices. You don't want a background process to take down your website!</p>\n\n<p><strong>Single Responsibility</strong></p>\n\n<p>Not only is this the <strong>S</strong> in SOLID, but it's also a guiding principle in the microservices/distritubed systems world. Each system/service should do one thing and do it well.</p>\n\n<p><strong>Hosting</strong></p>\n\n<p>Last but not least where it's going to be hosted from is always going to be a factor IMO. I work a lot with Azure and now Kubernetes so while I build things that can be hosted anywhere there's always a lean towards leveraging the abilities of that hosting environment. For instance you could host in an Azure Web App, these have the concept of Web Jobs that are separate to the website, but run in the same App Service Plan. You could have your site write to an Azure Storage Queue and then a web job read the events from this (just an example)</p>\n\n<p><strong>ConfigureAwait</strong>\nIn my opinion don't write your own framework, there are plenty of things out there that have had many eyes on them. If you're asking these sorts of questions use someone else's framework to start with and then once you've got familiar with it make the decision then about making your own. That's my opinion though. From what I've read on MS documention in the past, yes you should use <code>ConfigureAwait(false)</code> when creating a package.</p>\n\n<p>Hope some of this helps. This is just from my experience and I'm sure other people will say other things :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T08:31:51.927",
"Id": "440630",
"Score": "2",
"body": "I might be wrong, but in .NET Core I don't think _ConfigureAwait(false)_ is needed since there is no synchronization context anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T09:00:02.357",
"Id": "440632",
"Score": "0",
"body": "I can't confirm or deny this, I've not used it for a long time now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T08:22:24.210",
"Id": "226672",
"ParentId": "216524",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T12:32:15.997",
"Id": "216524",
"Score": "7",
"Tags": [
"c#",
"concurrency",
"library",
"async-await",
"asp.net-core"
],
"Title": "Safely executing background tasks in parallel in ASP.NET Core"
} | 216524 |
<p><strong>I hope this is the right way of doing things</strong>: I've previously posted a request for a code review and gotten feedback. Now I have new improved code that I would like a code review on again. Old: <a href="https://codereview.stackexchange.com/questions/216444/c-linked-list-iterator-implementation">C++ linked list iterator implementation</a></p>
<hr>
<p><strong>Known issues:</strong></p>
<ul>
<li>Sentinel node contains a value</li>
<li>I haven't yet learned how to implement rule of five.</li>
<li>I don't understand the point of <code>const_iterator</code></li>
</ul>
<p><hr>
<strong>Node.h</strong></p>
<pre><code>#pragma once
namespace Util
{
template<typename T>
class Node
{
public:
template<typename T> friend class Iterator;
template<typename T> friend class List;
private:
Node(T);
~Node();
void push_back(Node*);
void unlink();
T value;
Node<T>* next;
Node<T>* prev;
};
template<typename T>
Node<T>::Node(T t) : value(t), next(this), prev(this)
{
// ...
}
template<typename T>
Node<T>::~Node()
{
unlink();
}
template<typename T>
void Node<T>::push_back(Node* n)
{
n->next = this;
n->prev = prev;
prev->next = n;
prev = n;
}
template<typename T>
void Node<T>::unlink()
{
next->prev = prev;
prev->next = next;
next = this;
prev = this;
}
}
</code></pre>
<p><hr>
<strong>Iterator.h</strong></p>
<pre><code>#pragma once
#include "Node.h"
namespace Util
{
template<typename T>
class Iterator
{
public:
template<typename T> friend class List;
T& operator*() const;
Iterator& operator++();
Iterator& operator--();
Iterator& operator++(int);
Iterator& operator--(int);
bool operator==(const Iterator& rhs) const;
bool operator!=(const Iterator& rhs) const;
private:
Iterator(Node<T>* n);
Node<T>* node;
};
template<typename T>
Iterator<T>::Iterator(Node<T>* n) : node(n)
{
// ...
}
template<typename T>
T& Iterator<T>::operator*() const
{
return node->value;
}
template<typename T>
Iterator<T>& Iterator<T>::operator++()
{
node = node->next;
return *this;
}
template<typename T>
Iterator<T>& Iterator<T>::operator--()
{
node = node->prev;
return *this;
}
template<typename T>
Iterator<T>& Iterator<T>::operator++(int)
{
Iterator<T> it(*this);
operator++();
return it;
}
template<typename T>
Iterator<T>& Iterator<T>::operator--(int)
{
Iterator<T> it(*this);
operator--();
return it;
}
template<typename T>
bool Iterator<T>::operator==(const Iterator& rhs) const
{
return node == rhs.node;
}
template<typename T>
bool Iterator<T>::operator!=(const Iterator& rhs) const
{
return node != rhs.node;
}
}
</code></pre>
<p><hr>
<strong>List.h</strong></p>
<pre><code>#pragma once
#include "Iterator.h"
namespace Util
{
template<typename T>
class List
{
public:
typedef Iterator<T> Iterator;
typedef Node<T> Node;
List();
~List();
List(const List&) = delete;
List(List&&) = delete;
List& operator=(const List&) = delete;
List& operator=(List&&) = delete;
// Capacity
bool empty() const;
int size() const;
// Modifiers
void push_back(const T&);
void push_front(const T&);
void pop_back();
void pop_front();
void clear();
Iterator insert(Iterator it, const T&);
Iterator erase(Iterator it);
// Element access
T& front() const;
T& back() const;
Iterator begin() const;
Iterator end() const;
private:
Node* head;
int list_size;
};
template<typename T>
List<T>::List() : head(new Node(0)), list_size(0)
{
// ...
}
template<typename T>
List<T>::~List()
{
while (!empty())
{
pop_back();
}
delete head;
}
template<typename T>
bool List<T>::empty() const
{
return head->next == head;
}
template<typename T>
int List<T>::size() const
{
return list_size;
}
template<typename T>
void List<T>::push_back(const T& t)
{
head->push_back(new Node(t));
++list_size;
}
template<typename T>
void List<T>::push_front(const T& t)
{
head->next->push_back(new Node(t));
++list_size;
}
template<typename T>
void List<T>::pop_back()
{
delete head->prev;
--list_size;
}
template<typename T>
void List<T>::pop_front()
{
delete head->next;
--list_size;
}
template<typename T>
void List<T>::clear()
{
Iterator it = begin();
while (!empty())
{
it = erase(it);
}
}
template<typename T>
typename List<T>::Iterator List<T>::insert(Iterator it, const T& t)
{
it.node->push_back(new Node(t));
++list_size;
--it;
return Iterator(it);
}
template<typename T>
typename List<T>::Iterator List<T>::erase(Iterator it)
{
Node* n = it.node->next;
delete it.node;
--list_size;
return Iterator(n);
}
template<typename T>
T& List<T>::front() const
{
return head->next->value;
}
template<typename T>
T& List<T>::back() const
{
return head->prev->value;
}
template<typename T>
typename List<T>::Iterator List<T>::begin() const
{
return Iterator(head->next);
}
template<typename T>
typename List<T>::Iterator List<T>::end() const
{
return Iterator(head);
}
}
</code></pre>
<p><hr>
<strong>Possible bug</strong>:
I've manually compared most of the methods of <code>std::list</code> and my list, and it seems coherent. Except for:</p>
<pre><code>for (auto it = list.begin(); it != list.end(); ++it)
{
it = list.erase(it);
}
</code></pre>
<p>The <code>std::list</code> deletes the all the elements and then errors because you cannot increment past <code>it.end()</code>. But my list deletes every other element in a weird way, and I think loops around several times.</p>
| [] | [
{
"body": "<ol>\n<li><p>Is there any use to only including one of the headers? No.<br>\nAre they all part of an intrinsic whole? Yes.<br>\nSo, why try to artificially separate them? Doing so just creates extra complexity.</p></li>\n<li><p>You are right that having the root store a spurious element is a serious error, especially as you might not even be able to construct it. Fortunately, that's easily remedied:<br>\nIntroduce an additional type only storing the links, have <code>Node</code> inherit from it, and only store that for manipulating the hierarchy.</p>\n\n<pre><code>struct Links {\n Links* next = nullptr;\n Links* prev = nullptr;\n};\n</code></pre>\n\n<p>For bonus points, make <code>List::List()</code> <code>noexcept</code> by making the root part of the <code>List</code>. </p></li>\n<li><p><code>Node</code> tries to do far too much. It is an implementation-detail of the list, and any desperate struggle to OO-ify, encapsulate, and make it its own separate abstraction just adds needless complexity. Yes, it needs the links (<code>prev</code> and <code>next</code>), and has to store the payload (<code>value</code>), but the only useful addition aside from that is a ctor forwarding all arguments to the <code>value</code>-member, to insulate the list from changes in the members order and prepare for implementing <code>emplace</code>-functions.</p>\n\n<p>All the logic belongs in the list directly.</p>\n\n<pre><code>template <class T>\nstruct Node : Links {\n template <class... X, decltype(new T(std::declval<X>(x)...))>\n Node(X&&... x) : value(std::forward<X>(x)...) {}\n\n T value;\n};\n</code></pre></li>\n<li><p>Reference-types and pointer-types are the exception, not the rule. All other user-defined types are expected to provide transitive-const. Which explains why you couldn't find much use to <code>const_iterator</code>.</p>\n\n<p>When re-doing all involved parts, consider using <code>Node<std::remove_const_t<T>></code> for the node-type of <code>List<T></code> and <code>Iterator<T></code>. Doing so allows more re-use and composition.</p>\n\n<p>Also keep in mind that any iterator should be trivially convertible to the corresponding constant iterator. And that (nearly) all iterators are so light-weight passing by reference is a pessimisation.</p></li>\n<li><p>If you add support for swapping (<code>friend void swap(List& a, List& b) noexcept</code>) and construction from arbitrary iterator-ranges (<code>template <class InputIt> List(InputIt first, InputIt last)</code>), the rest will easily fall into place.</p></li>\n<li><p>Consider whether defining a function in-class won't simplify things.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T19:28:56.007",
"Id": "216537",
"ParentId": "216528",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>The bug in</p>\n\n<pre><code>for (auto it = list.begin(); it != list.end(); ++it)\n{\n it = list.erase(it);\n}\n</code></pre>\n\n<p>is due to <code>++it</code>. You don't need to manually advance the iterator, <code>erase</code> does it for you automatically.</p></li>\n<li><p>The <code>const_iterator</code> promises that the pointed value would not be modified through it, which better expresses the intentions, and allows the compiler to optimize code more aggressively.</p></li>\n<li><p><code>head</code> is a misnomer. Call it <code>sentinel</code>, which it actually is.</p></li>\n<li><p>I am not sure that the circular list with a sentinel node is a good design. It doesn't buy you anything; memory wise it is worse than standard head and tail pointers; it somewhat complicates the code; it imposes a requirement on <code>T</code> to be constructible from <code>0.</code></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T19:31:12.193",
"Id": "216538",
"ParentId": "216528",
"Score": "3"
}
},
{
"body": "<p>I see a number of things that may help you improve your code.</p>\n\n<h2>Don't shadow template types</h2>\n\n<p>The code includes these lines:</p>\n\n<pre><code>namespace Util\n{\n template<typename T>\n class Node\n {\n public:\n template<typename T> friend class Iterator;\n template<typename T> friend class List;\n</code></pre>\n\n<p>There are a few problems here, but one is that the inner declarations shadow the outer one. </p>\n\n<p>Another problem is that the way this code is sructured, the <code>Node</code> class needs to refer to the <code>List</code> and <code>Iterator</code> classes. However, those classes are not defined within the <code>Node.h</code> file and so they need forward declarations. To address both these issues, one could place a forward declaration within the <code>Util</code> namespace:</p>\n\n<pre><code>template<typename T>\nclass List;\n</code></pre>\n\n<p>Then within the class, the <code>friend</code> line would look like this:</p>\n\n<pre><code>friend class List<T>;\n</code></pre>\n\n<p>Better, however, would be the next suggestion:</p>\n\n<h2>Reconsider the packaging</h2>\n\n<p>I would think there is very little use of <code>Node</code> outside the context of a <code>List</code>. For that reason, I'd suggest that it should be a private class within <code>List</code> and therefore, the <code>Node.h</code> file would go away. Similar logic applies to <code>Iterator.h</code> </p>\n\n<h2>Document or eliminate template limitations</h2>\n\n<p>If we try to build a <code>List<std::string></code> it will fail with the current code because of this line:</p>\n\n<pre><code>List<T>::List() : head(new Node<T>(0)), list_size(0)\n</code></pre>\n\n<p>The problem is that that passing a <code>0</code> to the <code>Node</code> constructor only works if the templated type <code>T</code> can be constructed that way and <code>std::string</code> cannot. If instead, a default <code>Node</code> constructor were written, we could write this:</p>\n\n<pre><code>List<T>::List() : head(new Node<T>), list_size(0) {}\n</code></pre>\n\n<p>There is more, but it's all I have time for at the moment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T09:08:27.813",
"Id": "216577",
"ParentId": "216528",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216537",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T14:03:31.430",
"Id": "216528",
"Score": "4",
"Tags": [
"c++",
"beginner",
"linked-list",
"homework",
"iterator"
],
"Title": "Linked list implementation C++"
} | 216528 |
<p>I'm creating a versatile component with styled-components that essentially just maps style attributes. I feel my type declarations seem inefficient in getting access to props.</p>
<p>Is it appropriate to use the props interface for each of these styles the way I'm doing it? Thoughts?</p>
<pre><code>import styled, { css } from 'styled-components';
import { darken } from 'polished';
import { elevation as boxShadow, color } from '../../StyleBase';
import { mapStyle } from '../../StyleBase';
export interface BoxProps {
fill?: boolean;
background?: string;
padding?:
| number
| [number, number]
| [number, number, number]
| [number, number, number, number];
margin?:
| number
| [number, number]
| [number, number, number]
| [number, number, number, number];
radius?: number;
elevation?: number;
border?: boolean;
}
const padding = ({ padding }: BoxProps) => mapStyle('padding', padding);
const margin = ({ margin }: BoxProps) => mapStyle('margin', margin);
const radius = ({ radius }: BoxProps) => mapStyle('border-radius', radius);
const background = ({ background }: BoxProps) =>
mapStyle('background', background);
const elevation = ({ elevation }: BoxProps) =>
elevation && mapStyle('box-shadow', boxShadow[elevation]);
const fill = ({ fill }: BoxProps) =>
fill &&
css`
flex: 1 1 0%;
`;
const border = ({ border }: BoxProps) =>
border &&
css`
border: 1px solid ${darken(0.07, color.GRAY_LIGHT)};
`;
export const Box = styled.div`
${fill}
${padding}
${margin}
${radius}
${background}
${elevation}
${border}
`;
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T16:07:19.727",
"Id": "216530",
"Score": "1",
"Tags": [
"css",
"react.js",
"typescript"
],
"Title": "Versatile React component that maps style attributes"
} | 216530 |
<p>I made a palindrome checker that's supposed to be designed to be simple and easy to read. Please let me know what you think. I believe the time complexity is <span class="math-container">\$\mathcal{O}(n)\$</span> but I'm not too sure about that:</p>
<p>Challenge: You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.</p>
<pre><code>function reverseString(str)
{
str = str.replace(/[^\w\s]|_/g, "").toLowerCase().split(" ").join("");
var array = [];
for(var i = str.length ; i >=0; i--)
{
array.push(str[i])
}
return(array.join(""));
}
reverseString("My age is 0, 0 si ega ym.");
function palindrome(str) {
str = str.replace(/[^\w\s]|_/g, "").toLowerCase().split(" ").join("");
if(str === reverseString(str))
{
return true;
}
else
{
return false;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T18:38:52.180",
"Id": "418904",
"Score": "0",
"body": "Are you sure this is working as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T18:42:00.947",
"Id": "418905",
"Score": "0",
"body": "The test `reverseString(\"My age is 0, 0 si ega ym.\");` should at least be something like `console.log(palindrome(reverseString(\"My age is 0, 0 si ega ym.\")));`, and does your challenge ignore spaces? Because if they don't, your example string should return false while it doesn't. Please clarify the exact challenge."
}
] | [
{
"body": "<h3>Time complexity</h3>\n\n<p>Your time complexity is linear but you can save a few traversals over the string and lower the constant factor as you improve readability. Checking whether a string is a palindrome can be done in one pass with two pointers at each end of the string (plus some conditionals for your special characters), but this gains speed at the expense of readability; I'd encourage a round of clean-up before going for optimizations.</p>\n\n<h3>Repeated code</h3>\n\n<p>Repeated code harms maintainability and readability. Notice that the line</p>\n\n<pre><code>str.replace(/[^\\w\\s]|_/g, \"\").toLowerCase().split(\" \").join(\"\");\n</code></pre>\n\n<p>appears in two places in the code. If you decide to change one to accept a different regex but forget to change the other one, you've introduced a potentially subtle bug into your program. Move this to its own function to avoid duplication.</p>\n\n<h3>Use accurate function names and use builtins</h3>\n\n<p><code>reverseString</code> is a confusing function: it does more than reversing a string as advertised: it also strips whitespace and punctuation, which would be very surprising if I called this function as a user of your library without knowing its internals. All functions should operate as black boxes that perform the task they claim to, nothing more or less.</p>\n\n<p>The array prototype already has a <code>reverse()</code> function, so there's no need to write this out by hand.</p>\n\n<h3>Avoid unnecessary verbosity</h3>\n\n<p>The code:</p>\n\n<pre><code> if(str === reverseString(str))\n {\n return true; \n }\n else\n {\n return false;\n }\n</code></pre>\n\n<p>is clearer written as <code>return str === reverseString(str);</code>, which says \"return the logical result of comparing <code>str</code> and its reversal\".</p>\n\n<h3>Improve the regex to match your specification</h3>\n\n<p>Including spaces in your regex substitution to <code>\"\"</code> is easier than <code>.split(\" \").join(\"\")</code>. If you wish to remove all non-alphanumeric characters, a regex like <code>/[^a-z\\d]/gi</code> reflects your written specification accurately (or use <code>\\W</code> if you don't mind including underscores).</p>\n\n<h3>Style remarks</h3>\n\n<ul>\n<li>JS uses K&R braces instead of Allman by convention.</li>\n<li>Add a blank line above <code>for</code> and <code>if</code> blocks to ease vertical congestion.</li>\n<li>Add a space around keywords and operators like <code>for(</code> and <code>>=0</code>, which are clearer as <code>for (</code> and <code>>= 0</code>.</li>\n<li>No need for parentheses around a <code>return</code> value.</li>\n<li><code>array.push(str[i])</code> is missing a semicolon.</li>\n<li>CodeReview's snippet autoformatter will automatically do most of this for you.</li>\n</ul>\n\n<h3>Rewrite 1</h3>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const palindrome = str => {\n str = str.replace(/[^a-z\\d]/gi, \"\").toLowerCase();\n return str === str.split(\"\").reverse().join(\"\");\n};\n\nconsole.log(palindrome(\"My age is 0, 0 si ega ym.\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h3>Rewrite 2: uglier, but faster</h3>\n\n<p><a href=\"https://jsperf.com/pppalindrome\" rel=\"noreferrer\">Benchmark</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const palindrome = str => {\n str = str.replace(/[^a-z\\d]/gi, \"\").toLowerCase();\n let left = 0;\n let right = str.length;\n\n while (left < right) {\n if (str[left++] !== str[--right]) {\n return false;\n }\n }\n\n return true;\n};\n\n[\n \"\",\n \"a\",\n \"aba\",\n \"racecar\",\n \"racecar \",\n \" racecar\",\n \" race car\",\n \" r r a c e c a rr \",\n \".a .. r . ... . .{9f08e988-1e35-4dc6-a24a-5c7e03bce5ba}$ $!ace ca r3 a\",\n].forEach(test => console.log(palindrome(test)));\n\nconsole.log();\n[\n \"ab\",\n \"abc\",\n \"racecars\",\n \"racescar\",\n \" ra scecar\",\n \" r sace car\",\n \"a r r a c e c a rr \",\n \" r r a c e c a rr a\",\n \".a .. r . ... . .$$$ $!aces ca r a\",\n].forEach(test => console.log(palindrome(test)));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:20:48.007",
"Id": "418918",
"Score": "0",
"body": "Good points, just to make sure is the time complexity O(n) because the reverse function traverses through each element of the array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:30:54.403",
"Id": "418921",
"Score": "0",
"body": "Your code makes ~11 trips over the `n`-sized input, which is why I mention the high constant factor. If you do the replacement and lowercasing one time, you can get away with about 6 trips through the input. I count any array function, loop or `===` as one trip over the input. This is a pretty minor concern relative to the other points, though, and addressing the style points accidentally improves your performance along the way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T00:04:51.587",
"Id": "418931",
"Score": "0",
"body": "This is pretty much exactly what I was thinking as I read it. It's weird just how much more compressed everything gets.... Anyways, wouldn't it be better to add a `.split()` to the first line so the last could be simply `return str === str.reverse();`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T00:06:26.240",
"Id": "418932",
"Score": "1",
"body": "Small optimization for your rewrite, lowercase the string first and [avoid the additional cost of a case-insensitive regex](https://stackoverflow.com/a/32021/3397444). There are larger optimizations that could also be done, but that make the code more complicated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T00:17:54.537",
"Id": "418934",
"Score": "1",
"body": "@Feathercrown `==`/`===` doesn't work on arrays, unfortunately, but good thought."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T00:29:08.627",
"Id": "418936",
"Score": "0",
"body": "@cbojar On the flip side, doing the sub first reduces the number of characters needed to lowercase. I'm not sure how the regex engine works, but I imagine on this one, it should be a one-pass job since there are no quantifiers (I may be mistaken). Either way, like you say, a more performance-conscious implementation would likely avoid all of these functions (I'm sure this can be done in one pass with two pointers), but I think the OP's code needs work before the micro-performance tweaks are worth looking at."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T05:14:37.587",
"Id": "418946",
"Score": "2",
"body": "Of course, the goal is to get an \"easy to read\" palindrome checker. Frankly, I doubt that the improvements to the efficiency of the method, impressive though they are, outweigh the looming disaster that would be maintaining or reading them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T17:36:45.047",
"Id": "418988",
"Score": "0",
"body": "@Feathercrown I agree"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:22:41.553",
"Id": "216539",
"ParentId": "216534",
"Score": "12"
}
},
{
"body": "<p>Too much code. </p>\n\n<ul>\n<li>You can return a boolean</li>\n</ul>\n\n<p>Note that the positions of <code>{</code> and <code>}</code></p>\n\n<pre><code> if(str === reverseString(str)) {\n return true; \n } else {\n return false;\n }\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code> return str === reverseString(str);\n</code></pre>\n\n<ul>\n<li><p>You can remove whites spaces and commas etc with regExp <code>/\\W/g</code></p></li>\n<li><p>Array has a reverse function which you can use rather than do it manually.</p></li>\n<li><p>You should reverse the string in the function.</p></li>\n<li><p>Strings are iterate-able so you can convert a string to an array with <code>[...str]</code></p></li>\n</ul>\n\n<p>Example</p>\n\n<pre><code>function isPalindrome(str) {\n str = str.replace(/\\W/g,\"\").toLowerCase();\n return str === [...str].reverse().join(\"\");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:31:01.417",
"Id": "418922",
"Score": "0",
"body": "Ah I see, btw I tried to code from scratch as much as possible to get better at problem solving/ programming. Although you are right that there are many JS methods that would make it easier to implement a solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:34:10.777",
"Id": "216540",
"ParentId": "216534",
"Score": "5"
}
},
{
"body": "<p>The line to scrub punctuation and spaces could be simplified from:</p>\n\n<pre><code>str = str.replace(/[^\\w\\s]|_/g, \"\").toLowerCase().split(\" \").join(\"\");\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>str = str.replace(/[^\\w]|_/g, \"\").toLowerCase();\n</code></pre>\n\n<p>Essentially, your original regex marks spaces as legal characters, which you're then going and later scrubbing out with <code>.split(\" \").join(\"\")</code>. By excluding the <code>\\s</code> in your regex, you cause the regex to match spaces in the string, which would then be replaced along with the punctuation in the <code>str.replace</code> method. See this <a href=\"https://regex101.com/r/mjy969/4\" rel=\"nofollow noreferrer\">regex101</a>.</p>\n\n<p>I'd also ask you to consider what it means to be a palindrome. Words like <code>racecar</code>. The way you're currently doing it is by reversing the string, and then checking equality. I suggest it could be half (worst case) or O(1) (best case) the complexity if you'd think about how you could check the front and the back of the string at the same time. I won't give you the code how to do this, but I'll outline the algorithm. Consider the word <code>Urithiru</code>, a faster way to check palindrome-ness would to be doing something like this:</p>\n\n<p>Take the first and last letters, compare them, if true, then grab the next in sequence (next from the start; next from reverse). Essentially the program would evaluate it in these steps:</p>\n\n<ol>\n<li><code>u</code> == <code>u</code>: true</li>\n<li><code>r</code> == <code>r</code>: true</li>\n<li><code>i</code> == <code>i</code>: true</li>\n<li><code>t</code> == <code>h</code>: false</li>\n</ol>\n\n<p>Words like <code>Urithiru</code> and palindromes have the worst complexity cases for the algorithm because every letter must be checked to prove it's a palidrome. However, if you checked a work like <code>supercalifragilisticexpialidocious</code>, it'd only take two iterations, and then most words in the English language (the ones that don't start and end with the same letters), would be an O(1) result. For instance, <code>English</code> would fail after the first comparison.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T22:14:14.230",
"Id": "216550",
"ParentId": "216534",
"Score": "2"
}
},
{
"body": "<p>I would suggest separating out the code to remove punctuation and convert to lowercase into a separate function (<code>normalizeString</code>), and make the <code>reverseString</code> and <code>isPalindrome</code> functions \"purer\". (This follows the Single Responsibility Principle.)</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function reverseString(str) {\n var array = [];\n\n for(var i = str.length - 1; i >= 0; --i) {\n array.push(str[i]);\n }\n\n return(array.join(\"\"));\n}\n\nfunction isPalindrome(str) {\n let left = 0;\n let right = str.length;\n\n while (left < right) {\n if (str[left++] !== str[--right]) {\n return false;\n }\n }\n\n return true;\n};\n\nfunction normalizeString(str) {\n return str.replace(/[^\\w\\s]|_/g, \"\").toLowerCase().split(\" \").join(\"\");\n}\n\n// reverseString(normalizeString(...));\n// isPalindrome(normalizeString(...));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T17:30:40.163",
"Id": "418986",
"Score": "0",
"body": "Ok, but I'm a little confused on why you used the while loop on your palindrome function, when you can use the reverseString or array.reverse() to compare both strings? It's actually why I created that function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T17:31:48.447",
"Id": "418987",
"Score": "0",
"body": "@DreamVision2017 For efficiency: this `isPalindrome` implementation can stop as soon as it finds a pair of characters that don't match."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T15:30:42.820",
"Id": "216586",
"ParentId": "216534",
"Score": "2"
}
},
{
"body": "<p>The main contribution of this answer is to use <code>toLowerCase()</code> before the regex, so the regex does less work. Note that I don't know if that would benefit performance at all - profile it if you are curious.</p>\n\n<pre><code>// private implementation - separated for ease of testing\nconst _isPalindrome = x => x===[...x].reverse().join('');\nconst _alphanum = x => x.toLowerCase().replace(/[^a-z\\s]/g, '');\n\n// public interface - combined for ease of use\nconst isPalindrome = x => _isPalindrome(_alphanum(x));\n</code></pre>\n\n<p>This may be unpopular, but I prefer terse/abstract argument names <code>x</code> and <code>y</code> over longer, more specific names. It's similar to using <code>i</code> as a loop variable - it makes it easier to see the structure of the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T17:16:33.967",
"Id": "216592",
"ParentId": "216534",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216539",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T18:26:03.900",
"Id": "216534",
"Score": "11",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"array",
"palindrome"
],
"Title": "Easy to read palindrome checker"
} | 216534 |
<p>I want this method to be completely understandable just from looking at the code and comments only. </p>
<pre><code>def add_error(error_dict, key, err):
"""Given an error message, or a list of error messages, this method
adds it/them to a dictionary of errors.
Doctests:
>>> add_error({}, 'key1', 'error1')
{'key1': ['error1']}
>>> add_error({'key1': ['error1']}, 'key1', 'error2')
{'key1': ['error1', 'error2']}
>>> add_error({'key1': ['error1', 'error2']}, 'key2', 'error1')
{'key1': ['error1', 'error2'], 'key2': ['error1']}
>>> add_error({}, 'key1', ['error1', 'error2'])
{'key1': ['error1', 'error2']}
>>> add_error({}, 'key1', [])
{}
>>> add_error({'key1': ['error1']}, 'key2', ['error1', 'error2'])
{'key1': ['error1'], 'key2': ['error1', 'error2']}
>>> add_error({}, 'key1', 23) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: The error(s) must be a string, or a list of strings.
>>> add_error({}, 'key1', [23]) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: The error(s) must be a string, or a list of strings.
>>> add_error({}, 'key1', ['error1', 23]) # doctest: \
+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: The error(s) must be a string, or a list of strings.
"""
if not isinstance(err, list):
err = [err]
if not key in error_dict and len(err) > 0:
error_dict[key] = []
for e in err:
if not isinstance(e, string_types):
raise TypeError(
'The error(s) must be a string, or a list of strings.'
)
error_dict[key].append(e)
return error_dict
</code></pre>
<p>Hopefully, the code along with the comment does the job well, but I would still appreciate review(s) of this method. One thing I always keep on wondering is whether this is too many doc-tests for such a simple method. Thanks.</p>
| [] | [
{
"body": "<h2>Consider narrowing accepted types</h2>\n\n<p>This might not be possible based on the context of your code, but if it is: arguments sharing one of many different types hinders and complicates testability and maintainability. There are many different solutions to this that will help this situation; one is accepting variadic arguments - i.e.</p>\n\n<pre><code>def add_error(error_dict, key, *errs):\n</code></pre>\n\n<p>This is still easily invocable without needing to wrap a single error in a list.</p>\n\n<h2>Use <code>x not in</code> instead of <code>not x in</code></h2>\n\n<p>i.e.</p>\n\n<pre><code>if key not in error_dict\n</code></pre>\n\n<h2>Lose your loop</h2>\n\n<p>and also lose your empty-list assignment, instead doing</p>\n\n<pre><code>error_dict.setdefault(key, []).extend(err)\n</code></pre>\n\n<p>If you use the variadic suggestion above, your entire function becomes that one line.</p>\n\n<h2>Immutable or not?</h2>\n\n<p>Currently you do two things - alter a dictionary and return it - when you should only pick one. Either make a copy of the dict and return an altered version, or modify the dict and don't return anything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:36:43.993",
"Id": "216541",
"ParentId": "216535",
"Score": "8"
}
},
{
"body": "<p>congratulations on writing a fairly clear, readable function! (And welcome!)</p>\n\n<p><strong>What types do you take?</strong></p>\n\n<p>You explicitly check for an instance of type <code>list</code>. I think you should invert your check, and look for a string type instead. The reason is that it would enable you to accept iterables other than <code>list</code> as your errors.</p>\n\n<p>For example, you would be able to do something like:</p>\n\n<pre><code>add_error(edict, 'key', (str(e) for e in ...))\n</code></pre>\n\n<p>That last parameter is not a <code>list</code>, but it <em>is</em> something you might want to do. Also, <code>*args</code> is not a list but a tuple - you might want to splat a tuple rather than converting it to a list first.</p>\n\n<p><strong>What types do you take?</strong></p>\n\n<p>Your <code>key</code> parameter is always tested as a string. But dicts can have other key-types than string, and you neither test those, nor do you appear to have coded any kind of rejection on that basis. I suggest you add some tests that demonstrate your intent: is it okay to use non-strings as keys, or not?</p>\n\n<p><strong>What constraints exist on the errors?</strong></p>\n\n<p>I don't see any indication of what happens when duplicate errors are added. Is this intended to be allowed, or not?</p>\n\n<p><strong>What constraints exist on the keys?</strong></p>\n\n<p>Is it okay to use <code>None</code> as a key? How about <code>''</code> (empty string)? Tests, please.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T22:07:25.080",
"Id": "216548",
"ParentId": "216535",
"Score": "5"
}
},
{
"body": "<h2>Type Hints</h2>\n\n<p>Based on your doctests, you must be using Python 3.6 or later (due to reliance on dictionary key order).</p>\n\n<p>Since Python 3.5+ includes support for type hints, you could declare you function as:</p>\n\n<pre><code>def add_error(error_dict: dict, key: str, err: list) -> dict:\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>from typing import List, Dict\n\ndef add_error(error_dict: Dict[str, List[str]], key: str,\n err: List[str]) -> Dict[str]:\n</code></pre>\n\n<p>Of course, modify the type hints if you take the argument changes suggested in other answers. In particular, as is, the type of <code>err</code> is actually a variant type. I’d prefer a variable list of strings, <code>*err: str</code>.</p>\n\n<h2>Detect Errors before Modifying</h2>\n\n<p>If an error is not a string, you will raise an exception. But first, if the key does not exist in the dictionary, you add an empty list for that key. </p>\n\n<p>If the error list contains strings before a non-string, you add those strings to the key’s list, then raise an exception part way through. </p>\n\n<p>Consider moving the checks up to the start of the function, before any changes have been made. </p>\n\n<pre><code>if any(not isinstance(e, string_types) for e in err):\n raise TypeError(\"The error(s) must be a string, or list of strings\")\n</code></pre>\n\n<h2>Duck Typing</h2>\n\n<p>Why must the errors be a string? Any object can be converted to a string...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T22:55:40.873",
"Id": "216553",
"ParentId": "216535",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "216541",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T18:49:54.897",
"Id": "216535",
"Score": "8",
"Tags": [
"python",
"python-3.x"
],
"Title": "Method for adding error messages to a dictionary given a key"
} | 216535 |
<p>My code recovers all sent messages (ending with "\r\n") in function <code>read_message</code>. I would like to improve this code, make it more efficient? If it's possible, I am open to all reviews!</p>
<p><strong>Code</strong></p>
<pre><code>static char *read_message(char *data)
{
static char *buffer = NULL;
char *message = NULL;
char *ptr;
size_t size;
if (buffer)
{
size = strlen(buffer) + strlen(data) + 1;
if (!(buffer = realloc(buffer, size)))
return (NULL);
strcat(buffer, data);
}
else {
if (!(buffer = strdup(data)))
return (NULL);
}
if ((ptr = strstr(buffer, "\r\n")))
{
size = ((unsigned int)ptr - (unsigned int)buffer) + 1;
if (!(message = (char*)malloc(sizeof(char) * size)))
return (NULL);
strncpy(message, buffer, size);
ptr += 2;
if (!(ptr = strdup(ptr)))
return (NULL);
free(buffer);
buffer = ptr;
}
return (message);
}
static t_message *parse_message(char *buffer)
{
int id;
id = atoi(buffer);
printf("L'id du message est %d\n", id);
return (NULL);
}
static void handle_message(void)
{
printf("OK\n");
}
void listen_client(t_args *args)
{
ssize_t count;
char buffer[BUFF_SIZE + 1] = { 0 };
char *msg_str;
t_message *msg;
while ((count = recv(args->client->s, buffer, BUFF_SIZE, 0)))
{
buffer[count] = '\0';
if (!(msg_str = read_message(buffer)))
continue ;
if (!(msg = parse_message(msg_str)))
continue ;
handle_message();
}
printf("Fin de connexion\n");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T22:05:05.393",
"Id": "418926",
"Score": "1",
"body": "Please show the definition of `t_message`, as well as showing all relevant `#include`s."
}
] | [
{
"body": "<p><strong>Portability</strong> </p>\n\n<p>First this program could be made more portable. There are 2 portability issues here</p>\n\n<p>If it was ported to a system that did not define end of line as \"\\r\\n\" this program might not work. This problem could be solved by including the proper header files or using</p>\n\n<pre><code>#define EndOfLine \"\\r\\n\"\n</code></pre>\n\n<p>and using </p>\n\n<pre><code> ptr = strstr(buffer, EndOfLine)\n</code></pre>\n\n<p>The second portability issue is the use of <code>strdup()</code>. It is not implemented on all systems. This <a href=\"https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c\">Stackoverflow question discusses the use of strdup</a>.</p>\n\n<p><strong>Consistency in Coding Style</strong> </p>\n\n<p>There is one place in the code where the indentation is inconsistent:</p>\n\n<pre><code> if (buffer)\n {\n size = strlen(buffer) + strlen(data) + 1;\n if (!(buffer = realloc(buffer, size)))\n return (NULL);\n strcat(buffer, data);\n }\n else {\n if (!(buffer = strdup(data)))\n return (NULL);\n }\n</code></pre>\n\n<p>The use of braces \"{\" and \"}\" should be consistent through the entire program.\nEverywhere except in this code the brace starts on a new line. </p>\n\n<p>It would be very nice if the headers were included for compilation and\ntesting. Without the headers or the calling functions it is difficult to\ncompile or test this code.</p>\n\n<p><strong>Complexity</strong> </p>\n\n<p>It might be better if the function <code>read_message(char *data)</code> was separated\ninto multiple functions to reduce the complexity. All of the functions might\nbe more readable if there was some virtical spacing between blocks of code.</p>\n\n<p><strong>Possible Bug</strong> </p>\n\n<p>The function <code>parse_message(char *buffer)</code> always returns NULL, in your\ntesting did the function <code>handle_message()</code> always get called?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T22:08:39.767",
"Id": "216549",
"ParentId": "216536",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T19:13:30.453",
"Id": "216536",
"Score": "1",
"Tags": [
"c",
"client"
],
"Title": "Read message protocol socket c"
} | 216536 |
<p>I could have any value in milliseconds like:</p>
<blockquote>
<p>1040370</p>
</blockquote>
<p>I must alert a specific converted time format : <code>_m_s</code> (ie:<code>17m20s</code>)</p>
<p>Here is how I do it: </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function ms(a){
var m = a/1000/60,
s = Math.floor(('0.'+(''+m).split('.')[1])*60);
m = (''+m).split('.')[0];
alert(m+'m'+s+'s');
}
ms(1040370);</code></pre>
</div>
</div>
</p>
<p>What do you think?
Is it satisfactory or is there a better way to accomplish the same?</p>
| [] | [
{
"body": "<p>Seems overly complicated. Let the builtin math and parsing functions do the work for you. And name time values something like <code>t</code>.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ms = t => alert( `${parseInt( t/1000 / 60 )}m${parseInt( t/1000 % 60 )}s` )\nms(1040370);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:17:18.853",
"Id": "216546",
"ParentId": "216542",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216546",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:40:55.423",
"Id": "216542",
"Score": "2",
"Tags": [
"javascript",
"datetime",
"formatting"
],
"Title": "Get _m_s time format from milliseconds value"
} | 216542 |
<p>As many of you know <code>goto</code> is usually signs of code smell. However I thought this could be an appropriate case, and would like confirmation or criticism.</p>
<p>Unnecessary section such as the called functions were removed. Every non-standard function returns an <code>int</code> as status, <code>0</code> is "OK"; except <code>linkedlist_open()</code> which returns a pointer which could be <code>NULL</code> if the system runs out of memory.</p>
<p><code>packagetarget_close()</code> does implement the necessary <code>NULL</code> checks. </p>
<pre class="lang-c prettyprint-override"><code>packagetarget *packagetarget_open()
{
packagetarget *target = (packagetarget*) malloc(sizeof(packagetarget));
if (!target) return NULL;
if (packagetarget_setname(target, ""))
goto disposer;
if (packagetarget_setsys(target, PACKAGETARGET_SYS))
goto disposer;
if (packagetarget_setarch(target, PACKAGETARGET_ARCH))
goto disposer;
if (packagetarget_setmin(target, PACKAGETARGET_MIN))
goto disposer;
if (packagetarget_setver(target, PACKAGETARGET_VER))
goto disposer;
if (packagetarget_setmax(target, PACKAGETARGET_MAX))
goto disposer;
linkedlist *comp = linkedlist_open();
if (!comp) goto disposer;
target->comp = comp;
return target;
disposer:
packagetarget_close(target);
return NULL;
}
</code></pre>
<p>Each setter function follows a simple pattern. Since each setter is identical, I will only put the code for <code>packagetarget_setname</code>.</p>
<pre class="lang-c prettyprint-override"><code>int packagetarget_setname(packagetarget *target, char *name)
{
if (!target) return 1;
if (!name) return 2;
target->name = realloc(target->name, strlen(name) * sizeof(char));
if (!target->name) return 3;
strcpy(target->name, name);
return 0;
}
</code></pre>
<p>Here is the <code>packagetarget_close</code> function:</p>
<pre class="lang-c prettyprint-override"><code>void packagetarget_close(packagetarget *target)
{
if (!target) return;
if (target->name) free(target->name);
if (target->sys) free(target->sys);
if (target->arch) free(target->arch);
if (target->min) free(target->min);
if (target->ver) free(target->ver);
if (target->min) free(target->min);
if (target->comp) linkedlist_close(target->comp);
free(target);
return;
}
</code></pre>
<p><code>linkedlist_open</code> is a similar function to the <code>packagetarget_open</code>.</p>
<pre><code>linkedlist *linkedlist_open()
{
linkedlist *list = (linkedlist*) malloc(sizeof(linkedlist));
if (!list) return NULL;
list->head = NULL;
list->length = 0;
list->remhook = NULL;
return list;
}
</code></pre>
<p>The one thing most of these functions is they may fail when the system runs out of memory. So I have implemented checks for each step.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:09:08.283",
"Id": "418914",
"Score": "0",
"body": "\"However I thought this could be an appropriate case, and would like confirmation or criticism.\" Yet you've stripped the code out of all it's context so we can't determine whether you're right or not. The code you've provided looks like it should've been used in a wrapper, not with `goto` constructs. Please provide more code and an explanation of what it's supposed to do so we can see how this snippet is being used. Stack Overflow likes minimal examples, Code Review does absolutely not. Please take a look at our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:11:50.273",
"Id": "418915",
"Score": "0",
"body": "Not all of the functions are written, yet. This function is a constructor for a struct named `packagetarget`. The idea is to allocate the struct in memory, and then call the setter methods for each field, which may fail. EDIT: If any step fails, the destructor function is called, once; and the function returns a null pointer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:15:58.533",
"Id": "418916",
"Score": "0",
"body": "If not all the functions are written, are you sure it works the way it should? And how can you be sure this is the right way to do it if you haven't completed the rest? It sounds like you're simply too early in the process got get this meaningfully reviewed and your question answered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T21:27:30.000",
"Id": "418920",
"Score": "0",
"body": "I have updated the question to include more code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T22:12:04.917",
"Id": "418927",
"Score": "1",
"body": "What is a constructor in C? I know what a constructor is in C++. Did you mean C++?"
}
] | [
{
"body": "<h2>packagetarget_close()</h2>\n\n<p>First of all, you have a <strong>copy-and-paste error</strong> in <code>packagetarget_close()</code>, where you attempt to free <code>target->min</code> twice, but not <code>target->max</code>.</p>\n\n<p>Next, note that most of the <code>if</code> statements are superfluous. As per the <a href=\"https://en.cppreference.com/w/c/memory/free\" rel=\"nofollow noreferrer\">standard behaviour for <code>free()</code></a>,</p>\n\n<blockquote>\n <p>If <code>ptr</code> is a null pointer, the function does nothing.</p>\n</blockquote>\n\n<h1>packagetarget_open()</h1>\n\n<p>You have <strong>undefined behaviour</strong> due to the way your error-handling works. The chunk of memory returned by <code>malloc()</code> contains arbitrary junk. If <code>packagetarget *target = (packagetarget*) malloc(sizeof(packagetarget))</code> succeeds, but one of the setters fails, then you would call <code>packagetarget_close()</code>, which would then interpret that arbitrary junk as pointers to memory to be freed. A good way to fix that is to zero the memory before calling any of the setters. You can either use <code>calloc()</code> instead of <code>malloc()</code>, or <code>memset()</code>, or a <a href=\"https://stackoverflow.com/q/11152160/1157100\">struct initializer</a>.</p>\n\n<h2>Avoiding malloc()</h2>\n\n<p>In C, I prefer the init-cleanup idiom over new-destroy (which you call open-close). In the init-cleanup idiom, the caller is responsible for providing the chunk of memory to be initialized, which gives the caller the option of providing either stack-based or heap-based memory.</p>\n\n<h2>Avoiding goto</h2>\n\n<p>While indiscriminate use of <code>goto</code> leads to spaghetti code, there are <a href=\"https://lkml.org/lkml/2003/1/12/151\" rel=\"nofollow noreferrer\">some circumstances where <code>goto</code> is justifiable, if used in a readily recognizable pattern</a>.</p>\n\n<p>I think that your use of <code>goto</code> isn't horrible, but personally I would prefer to write the <code>if</code> statements as a chain of <code>&&</code> expressions.</p>\n\n<h2>Suggested solution</h2>\n\n<pre><code>#include <stdlib.h>\n#include <string.h>\n\ntypedef struct packagetarget {\n char *name;\n char *sys;\n char *arch;\n char *min;\n char *ver;\n char *max;\n linkedlist comp;\n} packagetarget;\n\nint packagetarget_setname(packagetarget *target, const char *name) {\n if (!target) return 1;\n if (!name) return 2;\n target->name = realloc(target->name, strlen(name) * sizeof(char));\n if (!target->name) return 3;\n strcpy(target->name, name);\n return 0;\n}\n\nint packagetarget_setsys(packagetarget *target, const char *sys) {\n …\n}\n\nint packagetarget_setarch(packagetarget *target, const char *arch) {\n …\n}\n\nint packagetarget_setmin(packagetarget *target, const char *min) {\n …\n}\n\nint packagetarget_setver(packagetarget *target, const char *ver) {\n …\n}\n\nint packagetarget_setmax(packagetarget *target, const char *max) {\n …\n}\n\npackagetarget *packagetarget_cleanup(packagetarget *target) {\n if (target) {\n free(target->name);\n free(target->sys);\n free(target->arch);\n free(target->min);\n free(target->ver);\n free(target->max);\n linkedlist_cleanup(&target->comp);\n }\n return target;\n}\n\npackagetarget *packagetarget_init(packagetarget *target) {\n static const packagetarget empty = {};\n if (target) {\n *target = empty;\n if (!(0 == packagetarget_setname(target, \"\") &&\n 0 == packagetarget_setsys(target, PACKAGETARGET_SYS) &&\n 0 == packagetarget_setarch(target, PACKAGETARGET_ARCH) &&\n 0 == packagetarget_setmin(target, PACKAGETARGET_MIN) &&\n 0 == packagetarget_setver(target, PACKAGETARGET_VER) &&\n 0 == packagetarget_setmax(target, PACKAGETARGET_MAX) &&\n linkedlist_init(&target->comp))) {\n packagetarget_cleanup(target);\n return NULL;\n }\n }\n return target;\n}\n\nint main() {\n packagetarget t;\n if (packagetarget_init(&t)) {\n …\n }\n packagetarget_cleanup(&t);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T04:34:20.600",
"Id": "418944",
"Score": "0",
"body": "I did find the undefined behavior in `packagetarget_close()` myself too, but it was very late so I couldn't edit the question to fix it. Since I am very early in the project I may switch over idioms like you suggested because it made more sense. I used the open/close idioms because the only c api I am familiar with was Lua, which has the same structure. Also, marked as answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T04:17:39.850",
"Id": "216568",
"ParentId": "216545",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216568",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T20:57:18.490",
"Id": "216545",
"Score": "2",
"Tags": [
"c",
"error-handling",
"memory-management",
"constructor"
],
"Title": "Constructor for a packagetarget struct"
} | 216545 |
<p>I have a C# app that receives the following commands, via tcp sockets.</p>
<pre><code>{
key = "foo",
value = 1.6557,
}
</code></pre>
<p>I'm currently using this method to get the key-value pairs and store them to a classes auto properties.</p>
<pre><code>private Regex _keyRegex = new Regex("\"(.)*\"");
private Regex _valueRegex = new Regex(@"\d*\.{1}\d*");
private MyClass CrappyFunction(string nomnom)
{
// Gets a match for the key
var key = _keyRegex.Match(nomnom);
// Gets a match for the value
var value = _valueRegex.Match(nomnom);
// Tests if got matches for both. If not, returns null.
if (!key.Success || !value.Success) return null;
// Found both values, so it creates a new MyClass and returns it
// Also removes the " chars from the key
return new MyClass(
key.ToString().Replace("\"", string.Empty),
value.ToString());
}
</code></pre>
<p>Even though it works, I have a really bad feeling looking at this particular piece of code. It's ugly, in the sense that I'm using two regex objects to achieve my goal.
Any suggestions will be appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T23:08:40.780",
"Id": "418930",
"Score": "0",
"body": "Is json comming in over the sockets, because there are libraries to parse that."
}
] | [
{
"body": "<p>If you don't want to use a JSON library, you can combine the 2 regex expressions into one and use named groups <code>(?<name>expression)</code>.</p>\n\n<pre><code>private static Regex _regex =\n new Regex(@\"\"\"(?<key>.*)\"\".*?(?<value>\\d*\\.\\d*)\", RegexOptions.Compiled);\n</code></pre>\n\n<p>The you get the result with</p>\n\n<pre><code>var match = _regex.Match(\"{ key = \\\"foo\\\", value = 1.6557, }\");\nstring key = match.Groups[\"key\"].Value;\nstring value = match.Groups[\"value\"].Value;\n</code></pre>\n\n<p>Note that in a verbatim string, double quotes must be escaped by doubling them. The named group <code>key</code> does not include the double quotes, so you get the key directly.</p>\n\n<p>So I basically have the regex</p>\n\n<pre><code>key_expression.*?value_expression\n</code></pre>\n\n<p>Both expressions are separated by <code>.*?</code>. The quotation mark tells the <code>*</code> to be lazy, i.e. to take as few characters as possible. If you don't, it will swallow the digits before the decimal point.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T23:24:26.897",
"Id": "216555",
"ParentId": "216551",
"Score": "0"
}
},
{
"body": "<p>May not be the fastest but using 'LINQ' and 'split' it is easy to extract out the values. </p>\n\n<pre><code>var keyValue = \n data\n .Split(',')\n .Select(\n part => part.Split('='))\n .Take(2)\n .Select(\n parts => parts[1].Trim())\n .ToArray();\n\nvar key = keyValue[0].Replace(\"\\\"\", string.Empty);\nvar value = keyValue[1];\n</code></pre>\n\n<p>First split is on the ','<br/> \nThe results of that is split on '='. <br/>\nTake(2), ignores the 3rd part of the first split.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T23:30:26.507",
"Id": "216556",
"ParentId": "216551",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": "216555",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T22:29:30.580",
"Id": "216551",
"Score": "-2",
"Tags": [
"c#",
"regex"
],
"Title": "c# Fastest way to get values from string"
} | 216551 |
<p>In my final project for my Python course, I am required to create a calculator program. I really need someone to look over my code and tell me if I have met all the requirements for this project.</p>
<p>Here are the requirements:</p>
<blockquote>
<p>For the final project, you are to write a calculator program in Python
with the following characteristics:</p>
<ul>
<li>It must be at least 50 lines of code excluding comments</li>
<li>It must have the following functions:+,-,*,/, SQRT, and work with decimal numbers.</li>
<li>It must be all text, no high resolution graphics</li>
<li>It must automatically copy the result to the operating system clipboard</li>
<li>It must work as a functional calculator (calculations can be entered over and over)</li>
</ul>
<p>Please submit the source code only (.py), no object code (I will
compile on receipt)</p>
<p>NOTE:</p>
<ol>
<li><p>This assignment is graded on a pass/fail basis; there is no partial credit or resubmissions. Be sure you understand ALL of the
requirements.</p></li>
<li><p>Solutions that require the user install any software will NOT be accepted (in case you are not sure, this means NO Pyperclip.)</p></li>
</ol>
<p>WARNING: All submissions will be checked for plagiarism using
SafeAssign or other plagiarism checker.</p>
</blockquote>
<p>I completed the project, but because this is a pass/fail project I want to be 200% sure I have met every requirement. I am also open to any other feedback that would sharpen my Python skills.</p>
<p>Menu</p>
<pre><code>def main():
#Menu
print("=======================")
print("Welcome to Calculator")
print("By: Tyler Harris")
print("=======================")
print("Menu: ")
print("[1] Calculator")
print("[2] Instructions")
print("[3] Exit")
print("=======================")
choice = input("Please select an option: ")
if choice == '1':
calculator()
elif choice == '2':
instructions()
main()
elif choice == '3':
print("Thank you for using Calculator.")
else:
print("Not an option, try again:")
main()
</code></pre>
<p>Calculator</p>
<pre><code>def calculator():
result=0 #Resets calulator.
try:
while True:
print("Last Result: "+str(result))
#Number 1 input.
if result == 0:
num1= int(input("First Number: "))
if result != 0:
num1=result
#Operator input.
#Checks for input of special operators 'c', 'sqrt', and 'esc'.
operator=input("Opertaor: ").lower()
if operator == "c":
print("Calculator cleared")
calculator()
if operator=="sqrt":
result=(sqrt(num1))
print("Result: "+str(result))
continue
if operator=="esc":
main()
if operator.isdigit(): #Throw error if operator is a number.
raise Exception()
#Number 2 input.
num2= int(input("Second Number: "))
#Operator calls.
if operator=="+":
result=(add(num1,num2))
elif operator=="-":
result=(sub(num1,num2))
elif operator=="*":
result=(mult(num1,num2))
elif operator=="/":
result=(div(num1,num2))
#Copy result to System's clipboard and display the result.
copy2clip(str(result))
print("=======================")
print("Result: "+str(result))
print("copied to clipboard")
print("=======================")
#Catch any errors and reset calculator
except Exception:
print("=======================")
print("Error Please try again.")
calculator()
else:
calculator()
</code></pre>
<p>Operators</p>
<pre><code>def add(num1,num2):
return num1 + num2
def sub(num1,num2):
return num1 - num2
def mult(num1,num2):
return num1 * num2
def div(num1,num2):
return num1 / num2
def sqrt(num1):
return (num1**(1/2.0))
</code></pre>
<p>Instructions</p>
<pre><code>def instructions():
print("=======================")
print(format('Calculator','^25s'))
print("=======================")
print("Available operators")
print("+: Addition")
print("-: Subtraction")
print("*: Multiplication")
print("/: Division")
print("sqrt: Square Root")
print("c: Clear Calculator")
print("esc: Exit Calculator")
print("=======================")
def copy2clip(txt):
cmd='echo '+txt.strip()+'|clip'
return subprocess.check_call(cmd, shell=True)
if __name__=='__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T08:32:59.360",
"Id": "418954",
"Score": "1",
"body": "I would suggest you don't use `raise Exception`, instead provide a bit more info i.e. `raise ValueError('Operator must be a digit')`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T17:13:11.320",
"Id": "418984",
"Score": "0",
"body": "I'm afraid I don't have time for a full review, but one thing I did pick up on and wants checking is the requirement to \"work with decimal numbers.\" It may be worth clarifying whether it's fine to use floating point numbers, or whether you're specifically expected to use the decimal library: https://docs.python.org/3.7/library/decimal.html"
}
] | [
{
"body": "<p>You are using function calls as if they were goto labels. That is a huge sin: it makes your program spaghetti code. If you want a loop, then write a loop. For example, <code>main()</code> should look like:</p>\n\n<pre><code>def main():\n while True:\n #Menu\n print(\"=======================\")\n print(\"Welcome to Calculator\")\n print(\"By: Tyler Harris\")\n print(\"=======================\")\n print(\"Menu: \")\n print(\"[1] Calculator\")\n print(\"[2] Instructions\")\n print(\"[3] Exit\")\n print(\"=======================\")\n choice = input(\"Please select an option: \")\n if choice == '1':\n calculator()\n elif choice == '2':\n instructions()\n elif choice == '3':\n print(\"Thank you for using Calculator.\")\n break\n else:\n print(\"Not an option, try again:\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T01:00:29.937",
"Id": "216558",
"ParentId": "216557",
"Score": "10"
}
},
{
"body": "<pre><code> elif choice == '2':\n instructions()\n main()\n</code></pre>\n\n<p>Ummm, that's probably not exactly what you want.\nPython lacks a <code>goto</code> statement, so the usual idiom would be to wrap the whole thing in some sort of <code>while</code> loop, perhaps <code>while True</code>.\nConsider an input sequence of \"2 2 2 2 2\", or \"z z z z z\".\nYou'll wind up pushing <code>main</code> onto the call stack again, and again, and again....</p>\n\n<p>Your locals never go out of scope,\nso their <a href=\"https://docs.python.org/3/tutorial/stdlib2.html#weak-references\" rel=\"nofollow noreferrer\">ref</a> <a href=\"https://docs.python.org/3/extending/newtypes.html#finalization-and-de-allocation\" rel=\"nofollow noreferrer\">count</a> never decrements and they won't be deallocated and tidied up.</p>\n\n<p>tl;dr: leaking stack frames is Bad, don't do it.</p>\n\n<pre><code> print(\"Last Result: \"+str(result))\n</code></pre>\n\n<p>Usual idiom would be <code>print('Last Result:', result)</code>, but no harm done.</p>\n\n<pre><code> num1 = int(input(\"First Number: \"))\n</code></pre>\n\n<p>The requirements seemed pretty clear about \"...must work with <strong>decimal</strong> numbers.\"\nYou chose to invoke <code>int()</code> rather than <code>float()</code>.</p>\n\n<pre><code> if result != 0: \n num1 = result\n</code></pre>\n\n<p>I can't imagine how that corresponds to The Right Thing.\nIf you want a sentinel, <code>None</code> would be much better than <code>0</code>,\njust consider a sequence like <code>2 + 1 = - 3 =</code> (which yields zero).\nPerhaps there's a reason for assigning the accumulator to <code>num1</code>, but I'm not seeing it.\nIt appears you have discarded the user input.</p>\n\n<pre><code> operator = input(\"Opertaor: \").lower()\n</code></pre>\n\n<p>Typo.</p>\n\n<pre><code> calculator()\n</code></pre>\n\n<p>Same criticism as above. Python lacks <code>goto</code>, and you're leaking stack frames here.</p>\n\n<pre><code> if operator == \"sqrt\":\n result = (sqrt(num1))\n print(\"Result: \"+str(result))\n continue\n</code></pre>\n\n<p>It is apparent that I'm not understanding why you are using the <code>result</code> accumulator versus the <code>num1</code> user input.\nOn most calculators, repeated clicking of the √ key would yield repeated assignment of <code>result = sqrt(result)</code>.\nI'm a little concerned about <code>num1</code> versus <code>result</code> confusion.</p>\n\n<pre><code> if operator==\"esc\":\n main()\n</code></pre>\n\n<p>Same remark about leaking stack frames.\nA <code>return</code> statement would be usual, here.</p>\n\n<pre><code> if operator.isdigit(): \n</code></pre>\n\n<p>This seems a bit restrictive.\nBetter to unconditionally raise an \"unrecognized operator\" error.</p>\n\n<pre><code> num2 = int(input(\"Second Number: \"))\n</code></pre>\n\n<p>Same criticism as above, the \"decimal\" instructions are pretty clear about calling <code>float()</code>.</p>\n\n<pre><code> result = (add(num1,num2))\n</code></pre>\n\n<p>All four of these assignments seem pretty weird,\nas for a typical calculator we'd be accumulating <code>result = add(result, num2)</code>.\nThis is a consequence of the <code>num1</code> assignment above.\nAlso, please discard the <code>(</code>extraneous parentheses<code>)</code>.</p>\n\n<pre><code>def sqrt(num1):\n return (num1**(1/2.0))\n</code></pre>\n\n<p>This works fine, but do consider the usual idiom of simply calling <code>math.sqrt()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T12:17:06.237",
"Id": "418963",
"Score": "1",
"body": "Just to elaborate on the first point of why it is bad to keep calling main() - basically each time you call a method, you are 'entering' that method. But you never exit the method - you just keep going deeper into the wormhole with each main() call. As JH is saying, each time you call a method you are putting more data onto the stack, but since the methods never are allowed to exit, the data is never freed, which eventually means you run out of space and the application will stop working."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T01:01:10.647",
"Id": "216559",
"ParentId": "216557",
"Score": "8"
}
},
{
"body": "<p>I made some changes. Is there anything else I have missed that could be considered bad practice?</p>\n\n<p>Main</p>\n\n<pre><code>def main():\n#Operators are +,-,*,/\n#Special operator are c and esc\ncalculator()\n</code></pre>\n\n<p>Calculator</p>\n\n<pre><code>def calculator():\nnum1 = 0 #Resets calulator.\nclear = True #Checks if calculator is cleared\nwhile True:\n try:\n print(\"Last result: \",num1)\n\n #Number 1 input.\n if clear == True:\n num1= float(input(\"First Number: \")) \n\n #Operator input.\n #Checks for input of special operators 'c', 'sqrt', and 'esc'.\n operator=input(\"Operator: \").lower()\n if bool(re.search('^(?=.*[0-9]$)', operator)) == True: #Check if operator contains a number\n raise ValueError(\" Operator must be +,-,*,/,sqrt, or c\") #Throw error if operator is a number.\n elif operator == \"c\":\n num1 = 0\n clear = True\n print(\"Calculator cleared\")\n elif operator==\"sqrt\":\n num1=(sqrt(num1))\n print(\"result: \",num1)\n continue\n elif operator==\"esc\":\n sys.exit(0)\n\n #Number 2 input. \n if operator == \"c\":\n pass\n else:\n num2= float(input(\"Second Number: \"))\n\n #Operator calls.\n if operator==\"+\":\n num1= add(num1,num2)\n clear = False\n elif operator==\"-\":\n num1= sub(num1,num2)\n clear = False\n elif operator==\"*\":\n num1= mult(num1,num2)\n clear = False\n elif operator==\"/\":\n num1= div(num1,num2)\n clear = False\n\n #Copy num1 to System's clipboard and display the num1. \n copy2clip(str(num1)) \n print(\"=======================\")\n print(\"result: \",num1)\n print(\"copied to clipboard\")\n print(\"=======================\")\n\n #Catch any errors and reset calculator \n except ValueError as error:\n print(\"=======================\")\n print(\"Error: \",repr(error))\n pass\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:30:15.600",
"Id": "427866",
"Score": "1",
"body": "Welcome to Code Review! While OPs are [encouraged to answer their own questions](https://codereview.stackexchange.com/help/self-answer) bear in mind that [\"_Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\"](https://codereview.stackexchange.com/help/how-to-answer)... You can post a [new question](https://codereview.stackexchange.com/questions/ask) and mention the question/post above, to link the posts."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-29T18:04:00.400",
"Id": "221291",
"ParentId": "216557",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-30T23:31:42.430",
"Id": "216557",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"homework",
"calculator"
],
"Title": "Calculator final project in Python"
} | 216557 |
<p>I made a project in Python 3.7.1 that includes classes to create Yu-Gi-Oh cards. This isn't the entire game; it is just the cards itself. I will create the entire game later. I want feedback on how to improve my code.</p>
<pre><code>class Deck(object):
def __init__(self, main_deck):
self.main_deck = main_deck
def add_normal_cards(self, card_to_add, all_cards):
"""
Add monsters, spells and traps to the deck.
"""
if len(self.main_deck) > 60:
return "You have to many cards in your deck (60)."
else:
card_counter = 0
# Check to see how many copies of a card there are in your deck. Maximum 3 of the same card. Limited cards
# will be added eventually.
for card in self.main_deck:
if card == card_to_add:
card_counter += 1
if card_counter == 3:
return "You have to many copies of that card in your deck (3)."
else:
if card_to_add not in all_cards:
return "That card hasn't been added to the game yet (" + card_to_add + ")."
else:
self.main_deck.append(card_to_add)
def add_extra_cards(self, card_to_add, all_cards):
"""
Add monsters, spells and traps to the deck.
"""
if len(self.main_deck) > 15:
return "You have to many cards in your extra deck (15)."
else:
card_counter = 0
# Check to see how many copies of a card there are in your deck. Maximum 3 of the same card. Limited cards
# will be added eventually.
for card in self.main_deck:
if card == card_to_add:
card_counter += 1
if card_counter == 3:
return "You have to many copies of that card in your deck (3)."
else:
if card_to_add not in all_cards:
return "That card hasn't been added to the game yet (" + card_to_add + ")."
else:
self.main_deck.append(card_to_add)
class Monster(object):
def __init__(self, name, effects, attributes, monster_type, atk, _def, description):
self.name = name
self.effects = effects
self.attributes = attributes
self.type = monster_type
self.atk = atk
self._def = _def
self.description = description
def effect(self):
"""
Activate the effect of this monster.
"""
for effect in self.effects:
eval(effect)
class Spell(object):
def __init__(self, name, effects):
self.name = name
self.effects = effects
def activate(self):
"""
Activate the effect of this spell.
"""
for effect in self.effects:
eval(effect)
class Trap(object):
def __init__(self, name, effects):
self.name = name
self.effects = effects
def activate(self):
"""
Activate the effect of this spell.
"""
for effect in self.effects:
eval(effect)
class LinkMonster(object):
def __init__(self, name, effects, attributes, monster_type, atk, link_rating, description, recipe, links):
self.name = name
self.effects = effects
self.attributes = attributes
self.type = monster_type
self.atk = atk
self.link_rating = link_rating
self.description = description
self.recipe = recipe
self.links = links
def activate(self):
"""
Activate the effect of this monster.
"""
for effect in self.effects:
eval(effect)
class SynchroMonster(object):
def __init__(self, name, effects, attributes, monster_type, atk, _def, description, recipe):
self.name = name
self.effects = effects
self.attributes = attributes
self.type = monster_type
self.atk = atk
self._def = _def
self.description = description
self.recipe = recipe
def activate(self):
"""
Activate the effect of this monster.
"""
for effect in self.effects:
eval(effect)
class XyzMonster(object):
def __init__(self, name, effects, attributes, monster_type, atk, _def, description, recipe):
self.name = name
self.effects = effects
self.attributes = attributes
self.type = monster_type
self.atk = atk
self._def = _def
self.description = description
self.recipe = recipe
self.materials = recipe
def activate(self):
"""
Activate the effect of this monster.
"""
for effect in self.effects:
eval(effect)
class FusionMonster(object):
def __init__(self, name, effects, attributes, monster_type, atk, _def, description, recipe):
self.name = name
self.effects = effects
self.attributes = attributes
self.type = monster_type
self.atk = atk
self._def = _def
self.description = description
self.recipe = recipe
def activate(self):
"""
Activate the effect of this monster.
"""
for effect in self.effects:
eval(effect)
class PendulumMonster(object):
def __init__(self, name, effects, pendulum_effects, pendulum_scale, attributes, monster_type, atk, _def,
description, recipe):
self.name = name
self.effects = effects
self.pendulum_effects = pendulum_effects
self.pendulum_scale = pendulum_scale
self.attributes = attributes
self.type = monster_type
self.atk = atk
self._def = _def
self.description = description
self.recipe = recipe
self.materials = recipe
def activate(self):
"""
Activate the effect of this monster.
"""
for effect in self.effects:
eval(effect)
def pendulum_activate(self):
"""
Activate the effect of this monster while in Spell/Trap Zone.
"""
for effect in self.pendulum_effects:
eval(effect)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:22:08.773",
"Id": "419008",
"Score": "0",
"body": "What you really need are some unit tests. I see some pretty noticable bugs in the `Deck` class, that a simple test would highlight"
}
] | [
{
"body": "<ul>\n<li>I know you're trying to abbreviate \"defense,\" but you could consider writing the whole thing out instead of making inconsistent naming with the preceding underscore. As such, you could write out \"attack\" as well to keep it more consistent.</li>\n<li>Perhaps all those monster classes should be part of a common base class inheritance. There are a lot of repeated <code>self</code> statements and similar functions (especially <code>activate()</code>), making the code harder to follow and maintain.</li>\n<li><p>The <code>60</code>, <code>15</code>, and <code>3</code> are \"magic numbers\" (numbers without some kind of given context), and from where they are, they could be harder to maintain.</p>\n\n<p>Although Python doesn't have actual constants like other languages, you can still do something similar above the functions:</p>\n\n<pre><code>MAX_DECK_CARDS = 60\n</code></pre>\n\n<p></p>\n\n<pre><code>MAX_EXTRA_CARDS = 15\n</code></pre>\n\n<p></p>\n\n<pre><code>MAX_EXTRA_CARDS = 3\n</code></pre></li>\n<li><p>There's a grammatical error here:</p>\n\n<blockquote>\n<pre><code>\"You have to many copies of that card in your deck (3).\"\n</code></pre>\n</blockquote>\n\n<p>It should be \"too\" instead of \"to.\"</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T08:01:05.363",
"Id": "418951",
"Score": "3",
"body": "ATK and DEF are probably considered [special terminology](https://yugioh.fandom.com/wiki/ATK) in Yu-Gi-Oh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T15:44:29.530",
"Id": "418980",
"Score": "0",
"body": "@jingyu9575: I was already aware of that (maybe I didn't word it as such)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T02:50:12.313",
"Id": "216564",
"ParentId": "216560",
"Score": "9"
}
},
{
"body": "<h2>Trim redundant <code>else</code></h2>\n\n<p>...here:</p>\n\n<pre><code>if len(self.main_deck) > 60:\n return \"You have to many cards in your deck (60).\"\nelse:\n</code></pre>\n\n<p>The <code>else</code> isn't needed because you've already returned. This pattern happens in a few places.</p>\n\n<h2>Lose some loops</h2>\n\n<p>This:</p>\n\n<pre><code> card_counter = 0\n for card in self.main_deck:\n if card == card_to_add:\n card_counter += 1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>card_counter = sum(1 for card in self.main_deck if card == card_to_add)\n</code></pre>\n\n<p>If this happens often, you may want to do some preprocessing in a different method to make this easier. As in the comments, it shouldn't replace the sequential-format deck, but it could supplement it:</p>\n\n<pre><code>from collections import Counter\ncard_counts = Counter(main_deck)\n# ...\ncard_counter = card_counts[card_to_add]\n</code></pre>\n\n<h2>Don't <code>eval</code></h2>\n\n<p>Just don't. There's never a good reason. Make <code>effects</code> an iterable of functions, and simply call them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T10:33:30.770",
"Id": "418960",
"Score": "5",
"body": "I would argue that the first point is a manner of style. I personally prefer writing it like you have suggested, but sometimes I do it the other way to be explicit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T20:00:11.727",
"Id": "418998",
"Score": "1",
"body": "Nice edits. I would still suggest `self.main_deck.count(card_to_add)` over `sum(1 for card in self.main_deck if card == card_to_add)`, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T11:18:12.500",
"Id": "419062",
"Score": "0",
"body": "I'd guess the `eval` might be because the card data isn't coming from code files (but, for example, a set of external files defining what cards exist). The idea of being able to update the card database without updating code is always an alluring one for a trading card game. Of course, eval still probably isn't a good choice, but that would mean there are no \"easy\" fixes like the one you described."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T04:15:41.430",
"Id": "216567",
"ParentId": "216560",
"Score": "19"
}
},
{
"body": "<p>Since you're using python 3.7, I would take advantage of f-strings.\nFor example, this:</p>\n\n<pre><code>return \"That card hasn't been added to the game yet (\" + card_to_add + \").\"\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>return f\"That card hasn't been added to the game yet ({card_to_add}).\"\n</code></pre>\n\n<p>As others have said, avoid hardcoding magic numbers like 60, 3 etc.\nGive these numbers meaningful names so that it is immediately obvious\nwhat the numbers represent.</p>\n\n<p>Also, unless I'm missing something critical, those monster classes are begging to use inheritance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T06:36:39.130",
"Id": "216571",
"ParentId": "216560",
"Score": "11"
}
},
{
"body": "<p>In your class <code>Deck</code> the methods <code>add_normal_card</code> and <code>add_extra_cards</code> share a lot of duplicated code which only differs in the maximum number of allowed cards and the error message displayed if this number is exceeded.<br>\nYou could pull out the <code>else</code> path in an own method.</p>\n\n<p>Also I was a bit confused about the attribute <code>main_deck</code> which is passed in <code>__init__</code>:</p>\n\n<ul>\n<li>since the class itself is already named <code>Deck</code> one could assume that <code>main_deck</code> is also an instance of some kind of custom <code>Deck</code> class, while it is just a <code>list</code>. This could be clarified by picking another name (like <code>list_of_cards</code>), adding a docstring to <code>__init__</code> or using type hints.</li>\n<li><code>add_extra_cards</code> checks the size of <code>main_deck</code> but returns the error message \"You have to many cards in your extra deck (15).\" I would assume that an extra deck and main deck are separate instances. Is this a bug?</li>\n</ul>\n\n<p>Last but not least the error handling of <code>add_normal_cards</code> and <code>add_extra_cards</code> can be improved. Right now they simply return <code>None</code> if all went well (which is OK), but if some of your conditions like maximum desk size are not met you simply return a <code>str</code>.<br>\nThink about the caller of your methods and how he or she should handle those errors.\nWith your current implementation, they would need to check if the returned object is not <code>None</code> and then compare string values to determine what happened and react to it.\nThis is error prone because if you decide to change the phrasing of your return values the caller's code will break.<br>\nInstead, you should raise a meaningful exception. Since you are dealing with three potential problems, you should define two custom exception classes, like <code>DeckSizeExceeded</code> and <code>CardCountExceeded</code>.<br>\nThe last possible error (<code>card_to_add not in all_cards</code>) could simply lead to an IndexError, so there is no need for a custom exception class here. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T15:38:35.117",
"Id": "216587",
"ParentId": "216560",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p><a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"noreferrer\"><code>dataclasses.dataclass</code></a> would single handedly remove the majority of your code.</p>\n\n<pre><code>from dataclasses import dataclass\nfrom typing import List\n\n\n@dataclass\nclass Monster(object):\n name: str\n effects: List[str]\n attributes: str\n type: str\n atk: int\n def_: int\n description: str\n\n def effect(self):\n \"\"\"\n Activate the effect of this monster.\n \"\"\"\n for effect in self.effects:\n eval(effect)\n</code></pre></li>\n<li><p>Your classes are setup for <em>inheritance</em>.</p>\n\n<pre><code>class FusionMonster(Monster):\n pass\n</code></pre></li>\n<li><p>I'd use composition over inheritance. <a href=\"https://yugioh.fandom.com/wiki/Equip_Card#Monster_Card\" rel=\"noreferrer\">This as equip monster cards can go into multiple types</a>. It should be noted that things like <a href=\"https://yugioh.fandom.com/wiki/Relinquished\" rel=\"noreferrer\">Relinquished</a> can make any monster an equipable.</p></li>\n<li><p>Your current <code>effect</code> method doesn't care about <a href=\"https://www.yugioh-card.com/en/gameplay/fasteffects_timing.html\" rel=\"noreferrer\">any of the timing rules</a>. This <a href=\"https://yugioh.fandom.com/wiki/Missing_the_timing\" rel=\"noreferrer\">wiki page</a> seems pretty complete on explaining the edge cases. I remember having this happen a couple times, IIRC it was because of my opponent playing an <a href=\"https://yugioh.fandom.com/wiki/Iron_Chain\" rel=\"noreferrer\">Iron Chain</a> deck.</p>\n\n<p>IIRC to do this you'd want to make a 'chain' class that is a stack, you then put all of the effects onto the stack. Once you have built the stack you then run <em>backwards</em> through the chain to to resolve the effects. (I.e. build with <code>Stack.append</code> and resolve with <code>Stack.pop</code>.)</p>\n\n<p>A rudimentary example would be a D.D. deck vs a Frog deck.</p>\n\n<p>Say I use my <a href=\"https://yugioh.fandom.com/wiki/Dupe_Frog\" rel=\"noreferrer\">Dupe frog</a> to attack and kill itself to one of your monsters, to send it to the graveyard to start up my combo. If <a href=\"https://yugioh.fandom.com/wiki/Dimensional_Fissure\" rel=\"noreferrer\">dimensional fissure</a> was a quick spell. After I declare my attack, you could use DF, if that's the end of the chain then DFs effect would activate. Then Dupe frog wouldn't be sent to the graveyard and its timing would be missed.</p></li>\n<li><p><a href=\"https://yugioh.fandom.com/wiki/Infinite_loop\" rel=\"noreferrer\">Yugioh has a lot of infinite loops</a>, and so you should design the chain class to take these into affect too.</p></li>\n</ol>\n\n<p>I think taking these factors into account at <em>the start</em> are very important as it'll force you to implement your code in the correct manner.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T16:59:10.693",
"Id": "216591",
"ParentId": "216560",
"Score": "16"
}
}
] | {
"AcceptedAnswerId": "216567",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T02:10:04.380",
"Id": "216560",
"Score": "15",
"Tags": [
"python",
"python-3.x",
"playing-cards"
],
"Title": "Yu-Gi-Oh cards in Python 3"
} | 216560 |
<p>I'm studying <a href="https://en.wikipedia.org/wiki/Support-vector_machine" rel="noreferrer">SVMs</a> and wrote a demo in MATLAB (because I couldn't get a quadratic programming package to work correctly in Python). Right now it's simple and can only do linearly-separable cases (nonlinear kernels will be implemented later). This is the first MATLAB program I've written outside of a MATLAB seminar I'm taking, so any thoughts would be appreciated.</p>
<pre><code>% simple SVM demo
clc;clear all;
% input data; y's are labels for data
y = [ -1; -1; -1; -1; -1; 1; 1; 1; 1; 1; 1 ];
data = [
0 3;
1 2;
2 1;
3 3;
5 1;
5 5;
6 5;
6 7;
7 3;
8 6;
8 1;
];
% separate positive and negative datapoints
posDps = data(find(y == 1), :);
negDps = data(find(y == -1), :);
% space is number of dimensions (n-space)
% right now, b/c being plotted in 2D, can only be 2-space
space = size(data, 2);
% n is number of input variables
n = length(data);
[ y1, y2 ] = meshgrid(y, y);
[ i, j ] = meshgrid(1:n, 1:n);
% generate matrices for minimization
P(i, j) = y1(i, j) .* y2(i, j) .* (data(i,:) * data(j,:)');
q = -1 * ones(n, 1);
% generate matrices for inequality constraint (alpha >= 0)
% also can use LB parameter
A = -1 * eye(n);
b = zeros(n, 1);
% generate matrices for equality constraint
Aeq = y';
beq = [ 0 ];
% use quadprog package to generate alphas
alpha = quadprog(P, q, A, b, Aeq, beq, [], [], [], optimoptions('quadprog', 'Display', 'off'));
% calculate w from alpha
w = (data' .* repmat(y', [space 1])) * alpha;
% finding b parameter
% (y_n)(x_n * w + b) = 1 for support vector, so b = y_n - w * x_n
threshold = 1e-5;
svIndices = find(alpha > threshold);
b = y(svIndices(1)) - data(svIndices(1),:) * w;
% display points
figure;
hold on;
scatter(posDps(:,1), posDps(:,2));
scatter(negDps(:,1), negDps(:,2));
% draw line (only 2D for now)
margin = 1;
domain = (min(data(:,1)) - margin):(max(data(:,1)) + margin);
plot(domain, (w(1) .* domain + b)/(-w(2)));
% plotting gutters
plot(domain, (-1 + w(1) .* domain + b)/(-w(2)), 'g:');
plot(domain, (1 + w(1) .* domain + b)/(-w(2)), 'g:');
</code></pre>
<p>I'd like any feedback, but here are some specific questions I had in mind:</p>
<ol>
<li>For storing one-dimensional data (arrays), is there usually a preference between column and row matrices?</li>
<li><p>Is there an easy way to deal with nested matrices? I tried to combine the labels and attribute vectors like so:</p>
<pre><code>data = [
-1 [ 0 3 ];
-1 [ 1 2 ];
% ...
]
</code></pre>
<p>and use more indices (e.g., <code>data(1,2,2)</code>) but that didn't work.</p></li>
<li>There are a ton of different ways to create matrices, and I'm not sure if the ones I am using are the most appropriate (e.g., via literals, <code>find()</code>, <code>meshgrid()</code>, <code>ones()</code> and <code>zeros()</code>, <code>repmat()</code>, etc.).</li>
<li>What is there to do about arbitrary imprecision? For example, I had to put in an arbitrary value <code>threshold</code> to find non-zero values because using <code>find(A > 0)</code> wasn't working. (Since the values were on the magnitude of about 1e-12, this was larger than the value of <code>eps()</code> so that function didn't seem very helpful.)</li>
<li>Naming conventions -- is there one for MATLAB? I don't believe I've seen a consistent style.</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T02:43:28.750",
"Id": "418940",
"Score": "0",
"body": "I'm new to Code Review.SE, so if there's anything I'm doing wrong that I should fix (off-topic, additional info, etc.) please let me know!"
}
] | [
{
"body": "<p>First to answer your specific questions:</p>\n\n<blockquote>\n <ol>\n <li>For storing one-dimensional data (arrays), is there usually a preference between column and row matrices?</li>\n </ol>\n</blockquote>\n\n<p>It doesn't matter, use what is most convenient. Often horizontal vectors are used because they are easy to create: <code>1:10</code>.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Is there an easy way to deal with nested matrices?</li>\n </ol>\n</blockquote>\n\n<p>The best way to collect matrices is using <a href=\"https://www.mathworks.com/help/matlab/cell-arrays.html\" rel=\"nofollow noreferrer\">a cell array</a>. A cell array's elements are arbitrary values (matrices, other cell arrays, objects, function handles, whatever you can assign to a variable).</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>There are a ton of different ways to create matrices, and I'm not sure if the ones I am using are the most appropriate (e.g., via literals, <code>find()</code>, <code>meshgrid()</code>, <code>ones()</code> and <code>zeros()</code>, <code>repmat()</code>, etc.).</li>\n </ol>\n</blockquote>\n\n<p>Yes, MATLAB has a huge library and it is impossible to know if you are using the best possible function in each case. Experience will help.</p>\n\n<blockquote>\n <ol start=\"4\">\n <li>What is there to do about arbitrary imprecision? For example, I had to put in an arbitrary value threshold to find non-zero values because using <code>find(A > 0)</code> wasn't working. (Since the values were on the magnitude of about 1e-12, this was larger than the value of <code>eps()</code> so that function didn't seem very helpful.)</li>\n </ol>\n</blockquote>\n\n<p>Yes, you need to pick some threshold there. It depends on the source of the data what an appropriate value is. <code>eps</code> is the distance between <code>1.0</code> and the next representable floating-point value. That is, there are no possible values in between <code>1.0</code> and <code>1.0+eps</code>. <code>eps</code> is not necessarily an appropriate threshold to find \"approximately zero\" values.</p>\n\n<blockquote>\n <ol start=\"5\">\n <li>Naming conventions -- is there one for MATLAB? I don't believe I've seen a consistent style.</li>\n </ol>\n</blockquote>\n\n<p>Not that I know of. Early versions of MATLAB were not case sensitive, so all code was typically written in lower case. Currently some built-in functionality uses an upper case for the first letter, and some use camelCase. There is no PEP8 for MATLAB. :)</p>\n\n<hr>\n\n<p>Now I'll go through the bits of code that can be improved:</p>\n\n<blockquote>\n<pre><code>clc;clear all;\n</code></pre>\n</blockquote>\n\n<p>Please use the MATLAB Editor, and heeds its warnings. <code>clear all</code> is not useful here, it not only clears variables, it also clears functions from memory. These will need to be read in and parsed again, slowing down your program. <code>clear</code> suffices to remove variables from your workspace.</p>\n\n<blockquote>\n<pre><code>posDps = data(find(y == 1), :);\nnegDps = data(find(y == -1), :);\n</code></pre>\n</blockquote>\n\n<p>Here you can remove <code>find</code>. The MATLAB Editor also warns about this.</p>\n\n<pre><code>posDps = data(y == 1, :);\nnegDps = data(y == -1, :);\n</code></pre>\n\n<p><code>find</code> is usually not necessary when indexing, only when you need to store an index to an array element.</p>\n\n<blockquote>\n<pre><code>space = size(data, 2);\nn = length(data);\n</code></pre>\n</blockquote>\n\n<p>It is always better to specify directly what size you need. <code>length(data)</code> is defined as <code>max(size(data))</code>, I consider this dangerous. Instead:</p>\n\n<pre><code>[n,space] = size(data);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>space = size(data, 2);\nn = size(data, 1);\n</code></pre>\n\n<p>You should also know <code>numel</code>, which returns the number of elements in a matrix. This is much more efficient than <code>prod(size(data))</code>.</p>\n\n<blockquote>\n<pre><code>[ y1, y2 ] = meshgrid(y, y);\n[ i, j ] = meshgrid(1:n, 1:n);\n</code></pre>\n</blockquote>\n\n<p>These are not necessary at all. Since MATLAB R2016b we have implicit singleton expansion, but before that you could use <code>bsxfun</code> to operate on two arrays of different sizes. So none of the following indexing operations are really necessary.</p>\n\n<blockquote>\n<pre><code>P(i, j) = y1(i, j) .* y2(i, j) .* (data(i,:) * data(j,:)');\n</code></pre>\n</blockquote>\n\n<p>can be rewritten as</p>\n\n<pre><code>P = (y .* y.') .* (data * data.');\n</code></pre>\n\n<p>Note that I use <code>.'</code> here, where you had <code>'</code>. <code>'</code> is the complex conjugate transpose. Unless you want to compute a dot product, you should avoid it. <code>.'</code> transposes the matrix without changing any of its values. For real-valued data they're the same, but it's good to get used to using the right form, it will prevent difficult to find errors down the road.</p>\n\n<blockquote>\n<pre><code>Aeq = y';\n</code></pre>\n</blockquote>\n\n<p>Same here: <code>y.'</code>.</p>\n\n<blockquote>\n<pre><code>beq = [ 0 ];\n</code></pre>\n</blockquote>\n\n<p>Again, the MATLAB Editor warns here about the useless <code>[]</code> brackets. Heed the warnings!</p>\n\n<p>There is actually no difference in MATLAB between a matrix and a scalar. A scalar is a matrix with a single value. The <code>[...]</code> operator is for concatenation. It concatenates two or more matrices into a single matrix. Every time you have a single matrix inside <code>[]</code>, the MATLAB Editor will warn you about it.</p>\n\n<p>Similarly, I often see things like <code>[1:10]</code>. <code>1:10</code> is a matrix, the <code>[]</code> don't do anything there.</p>\n\n<blockquote>\n<pre><code>w = (data' .* repmat(y', [space 1])) * alpha;\n</code></pre>\n</blockquote>\n\n<p>Same here: <code>data.'</code>, <code>y.'</code>.</p>\n\n<blockquote>\n<pre><code>svIndices = find(alpha > threshold);\nb = y(svIndices(1)) - data(svIndices(1),:) * w;\n</code></pre>\n</blockquote>\n\n<p>Here you can use the second argument to <code>find</code> to tell it to give you only one index:</p>\n\n<pre><code>svIndex = find(alpha > threshold,1);\nb = y(svIndex) - data(svIndex,:) * w;\n</code></pre>\n\n<blockquote>\n<pre><code>domain = (min(data(:,1)) - margin):(max(data(:,1)) + margin);\n</code></pre>\n</blockquote>\n\n<p>You don't need this many parentheses here, but they don't hurt either. I actually think they help readability. But the <code>:</code> has a much lower precedence than <code>+</code> and <code>-</code>. This should also work:</p>\n\n<pre><code>domain = min(data(:,1))-margin : max(data(:,1))+margin;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T01:24:15.467",
"Id": "420728",
"Score": "0",
"body": "Thanks! All good thoughts, and answered the questions I had."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T23:22:57.020",
"Id": "216955",
"ParentId": "216563",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216955",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T02:42:02.500",
"Id": "216563",
"Score": "5",
"Tags": [
"machine-learning",
"matlab"
],
"Title": "Simple SVM in MATLAB"
} | 216563 |
This tag is for questions regarding the international standard ISO 9899:1990, also known as "C89", "C90" or "ANSI C", with amendments and technical corrigenda (as opposed to K&R C, C99, C11 or later C standard revisions). | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T02:53:35.060",
"Id": "216566",
"Score": "0",
"Tags": null,
"Title": null
} | 216566 |
<h2>Goal of Program</h2>
<p>Consider a template file <code>template.txt</code> with double brace variables, intended to be replaced by values:</p>
<pre><code>hello there {{ MY_VAR1 }}
some other stuff
some other stuff
foo: {{ MY_VAR2 }}
{{ MY_VAR2 }} is the value of MY_VAR2
</code></pre>
<p>and assume you have defined and exported those variables:</p>
<pre><code>export MY_VAR1=val1
export MY_VAR2=val2
</code></pre>
<p>we want a script <code>fill_template</code> such that <code>fill_template template.txt</code> produces:</p>
<pre><code>hello there val1
some other stuff
some other stuff
foo: val2
val2 is the value of MY_VAR2
</code></pre>
<p>and which gives an appropriate error message if any of the required template variables are not defined.</p>
<h2>Code for review</h2>
<p>Here is working code for <code>fill_template</code>:</p>
<pre><code>#!/bin/bash
if [[ ! -f $1 ]]; then
>&2 echo "Usage: $0 <filename>"
exit 1
fi
# Gather all the required template variables
vars=()
while IFS= read -r line; do
vars+=( "$line" )
done < <( awk 'match($0, /{{ (.*) }}/, a) { print a[1] }' "$1" | sort -u )
# Verify that all template variables are set and exported
missing=()
for var in "${vars[@]}"; do
if [[ -z ${!var+x} ]]; then
missing+=( "$var" )
fi
done
if [[ ${#missing[@]} -gt 0 ]]; then
>&2 echo "The following required variables have not been set and exported:"
for var in "${missing[@]}"; do
>&2 echo "${var}"
done
exit 1
fi
# Dynamically construct the sed cmd to do the replacement
sed_cmd=
for var in "${vars[@]}"; do
sed_cmd+="s/\\{\\{ *${var} *}}/${!var}/g;"
done
sed -E "${sed_cmd}" "$1"
</code></pre>
<h2>Notes</h2>
<ul>
<li>All comments welcome, from the high-level approach to nitpicks.</li>
<li>Currently we assume there will be only one <code>{{ TEMPLATE_VAR }}</code> per line</li>
</ul>
| [] | [
{
"body": "<h3>Make the template variable name extraction more strict</h3>\n\n<p>The Awk command extracts the template variable names using the pattern <code>/{{ (.*) }}/</code>.\nThis leaves some room to human errors.\nFor example excess whitespace, as in <code>{{ MY_VAR }}</code>.\nThis can be especially frustrating for trailing whitespace, which will be invisible when printing the list of missing variables.\nI think it would be good to strip whitespaces after <code>{{</code> and before <code>}}</code>.</p>\n\n<p>But that's not quite enough. Consider such line in the input:</p>\n\n<blockquote>\n<pre><code>hello there {{ MY_VAR1 }} foo bar {{ baz }}\n</code></pre>\n</blockquote>\n\n<p>Although using multiple variables is explicitly unsupported,\nthis blows up in the face of the user in a nasty way:</p>\n\n<blockquote>\n<pre><code>$ MY_VAR1=foo/bar/bazo MY_VAR2=bar bash script.sh input.txt\na.sh: line 19: MY_VAR1 }} foo bar {{ baz: bad substitution\na.sh: line 33: MY_VAR1 }} foo bar {{ baz: bad substitution\nhello there {{ MY_VAR1 }} foo bar {{ baz }}\nsome other stuff\nsome other stuff\nfoo: {{ MY_VAR2 }}\n{{ MY_VAR2 }} is the value of MY_VAR2\n</code></pre>\n</blockquote>\n\n<p>The error messages are unfortunately incomprehensible.</p>\n\n<p>Since the template variable names are expected to take values from shell variables,\nit would make sense to enforce a stricter pattern.</p>\n\n<p>Even if the script is not intended to handle sophisticated scenarios,\nI think it should handle such user mistakes more gracefully.</p>\n\n<h3>Consistency</h3>\n\n<p>The Sed command replacing template variable names with values uses the pattern <code>\\\\{\\\\{ *${var} *}}</code>.\nThis is not consistent with the one in the Awk command,\nbecause of stripping the whitespace.\nAs mentioned earlier, I would adjust the Awk command to make it consistent.</p>\n\n<h3>Error handling</h3>\n\n<p>In the example above with a user mistake,\nthe script continued to execute even after the error.\nTo catch such issues and terminate the program early I recommend adding this line at the very beginning:</p>\n\n<pre><code>set -euo pipefail\n</code></pre>\n\n<h3>Beware of some gotchas</h3>\n\n<p><code>/</code> in the template variable names and values will break the Sed command.</p>\n\n<p>As for the names, a more strict handling as mentioned earlier will prevent this issue.</p>\n\n<p>As for the values, <code>/</code> appearing in the values doesn't sound too crazy,\nbecause I can easily imagine wanting to insert path strings.\nSo I think it's a legitimate concern that would be good to address.</p>\n\n<h3>Usability</h3>\n\n<p>The limitation to one template variable per line seems a bit artificial.</p>\n\n<p>Currently the script fails fast when the user mistakenly tries to use multiple per line, that's a good behavior to preserve.\n(I'm pointing this out because if you simply enforce more stricter checking on the name patterns, this fail-fast behavior may no longer be the case.\nAnd if I had to choose between cryptic failures, and quietly ignored missed template variables, I would prefer cryptic failures.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:38:47.677",
"Id": "418974",
"Score": "0",
"body": "Janos, great comments. Tyvm. I'm going to make the suggested changes and then repost the revised version. As a side note, I was curious what you thought of [this warning against set -e](https://mywiki.wooledge.org/BashFAQ/105) -- not in relation to my script, but just in general."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:46:00.147",
"Id": "418975",
"Score": "0",
"body": "@Jonah my personal recommendation is to go ahead and use `set -e`, but beware of possible gotchas, *and* add your own error checking too ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T09:29:17.737",
"Id": "216578",
"ParentId": "216569",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216578",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T04:38:17.727",
"Id": "216569",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Pure bash program for auto-filling a template file with ENV variables"
} | 216569 |
<p>I would like to know if this code follows recommended practices and standards for AJAX/PHP calls. Can this AJAX + PHP code be improved in terms of security, performance, etc.?</p>
<p><strong>ajax.js:</strong></p>
<pre><code>function getTableData() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.querySelector('#test-table tbody').innerHTML = this.responseText;
}
}
xmlhttp.open('GET', 'ajax.php', true);
xmlhttp.send();
}
$(document).ready(function () {
getTableData();
});
</code></pre>
<p><strong>ajax.php:</strong></p>
<pre><code><?php
$data = prepareDataForTable();
$data_length = count($data);
$columns = 4;
for ($row = 0; $row < $data_length; $row += $columns) {
echo '<tr>';
for ($col = 0; $col < $columns && ($col + $row) < $data_length; $col++) {
echo '<td>' . $data[$col + $row] . '</td>';
}
echo '</tr>';
}
?>
</code></pre>
<p><strong>ajax.html:</strong></p>
<pre><code><table id="test-table">
<tbody>
</tbody>
</table>
</code></pre>
<p><strong>I specifically want to know if this is a good way to send information back to the client - by running loops and echoing output.</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T07:50:52.760",
"Id": "418948",
"Score": "0",
"body": "All I can say is that the little code you show us could be a lot shorter. You could use JQuery for the ajax call (it does all the complicated & compatibility stuff for you) and if `prepareDataForTable()` would return a 2D data array you could use 2 simple `foreach` loops to echo the table. That would even be more flexible than what you have now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T08:00:11.233",
"Id": "418950",
"Score": "0",
"body": "@KIKOSoftware actually meant something else...Is it fine to echo data like that? Or should I transport it in JSON? - or something along those lines..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T08:13:43.300",
"Id": "418953",
"Score": "0",
"body": "@KIKOSoftware Also, I prefer vanilla JS over jQuery. `prepareDataForTable()` actually returns 1D array but I need to print `<tr>` tags for every 4th element in array so I thought `for` loop was a better choice here. If you can demonstrate how to do the same with `foreach`, then I'll appreciate it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T08:45:13.580",
"Id": "418955",
"Score": "0",
"body": "In this basic code I think you can echo either HTML or JSON, it doesn't really matter. You're not using a MVC framework, or anything like it. Using vanilla JS is brave but also a bit stupid (sorry!). Other people have done the hard work for you, why not use it? Moreso, if JS evolves, which it will, all you have to do is update JQuery, instead of changing all your code. Finally, I know `prepareDataForTable()` return a 1D array of 2D data. Returning a 2D array will make it easier to handle the data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T19:25:53.070",
"Id": "418997",
"Score": "0",
"body": "@KIKOSoftware I am actually using vanilla JS here because the project is not too big. I usually go to other libraries/frameworks if the project is big enough. I know it is a big debate whether to use vanilla JS or its libraries:)"
}
] | [
{
"body": "<p>Trying to follow your mathematical loop conditions makes my eyes go crossed in a hurry.</p>\n\n<p>Perhaps you'd entertain a less-math-heavy alternative:</p>\n\n<pre><code>foreach (array_chunk($array, 4) as $row) {\n echo '<tr><td>' , implode('</td><td>', $row) , '</td>' , str_repeat('<td></td>', 4-count($row)) , '</tr>';\n}\n</code></pre>\n\n<p>Granted this will be making a no-output call of <code>str_repeat()</code> on all rows except potentially the final row, but I think this technique will be more developer friendly. I'm assuming that I understand your <code>$data</code> (<a href=\"https://3v4l.org/L861q\" rel=\"nofollow noreferrer\">Demo</a>). I could have written a conditional for <code>str_repeat()</code> but felt that would only bloat the code.</p>\n\n<p>I tend to lean toward passing json back from an ajax call, but for this situation sending back html is the simpler approach.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T19:12:55.580",
"Id": "418996",
"Score": "0",
"body": "Thanks. Can you please expand your answer and show me how to pass JSON back in my case?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T12:13:07.987",
"Id": "216582",
"ParentId": "216572",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T06:37:08.897",
"Id": "216572",
"Score": "3",
"Tags": [
"javascript",
"php",
"ajax"
],
"Title": "PHP AJAX handler to fill an HTML table"
} | 216572 |
<p>I'd love for someone to review my code. It works fairly well, but I'm still getting the hang of PHP and want to make sure I've got an iron-clad system that isn't hilariously vulnerable. I'm also open to better ways to handle registering/logging in and out. I know the general answer is to not do this yourself, but I'm interested in learning to do this for myself rather than utilizing a framework. I definitely feel like I'm repeating code in several places, and would love to make this more concise.</p>
<p><strong>index.php</strong></p>
<pre><code><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Neue World</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<?php
if (isset($_SESSION["message"])) {
echo "<p>" . $_SESSION["message"] . "</p>";
unset($_SESSION["message"]);
}
if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"]) {
echo "<p>Welcome back! Click <a href=\"profile.php\">here</a> to view your profile, " . $_SESSION["username"] . ".</p>";
} else {
echo "<p>Welcome! Please <a href=\"register.php\">register</a> an account, or <a href=\"login.php\">login</a></p>";
}
?>
<script src="main.js"></script>
</body>
</html>
</code></pre>
<p><strong>register.php</strong></p>
<pre><code><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Neue World - Register</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<?php
if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"]) {
$_SESSION["message"] = "You're already logged into an account. Please <a href=\"?logout\">logout</a> to register a new account.";
header("Location: profile.php");
die();
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$errors = [];
$username = "";
$password = "";
$email = "";
if (isset($_POST["register"])) {
if (isset($_POST["username"])) {
$username = htmlspecialchars(trim($_POST["username"]));
if (empty($username)) {
$errors["username"] = "Please enter a username.";
} elseif (strlen($username) > 32) {
$errors["username"] = "Your username must be more than one character and less than 32 characters.";
}
}
if (isset($_POST["password"])) {
$password = trim($_POST["password"]);
if (empty($password)) {
$errors["password"] = "Please enter a password.";
} elseif (strlen($password) < 8) {
$errors["password"] = "Your password must be longer than eight characters.";
}
}
if (isset($_POST["email"])) {
$email = htmlspecialchars(trim($_POST["email"]));
if (empty($email)) {
$errors["email"] = "Please enter an e-mail address.";
} elseif (strlen($email) > 64) {
$errors["email"] = "Please enter an e-mail address shorter than 64 characters.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Please enter a valid e-mail address.";
}
}
try {
$db = new PDO("sqlite:dev.sqlite3", null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $db->prepare("SELECT username FROM users WHERE username = :username");
$stmt->execute([":username" => $username]);
$username_exists = $stmt->fetchColumn();
if ($username_exists) {
$errors["username"] = "Username already exists. Please enter another username.";
}
$stmt = $db->prepare("SELECT email FROM users WHERE email = :email");
$stmt->execute([":email" => $email]);
$email_exists = $stmt->fetchColumn();
if ($email_exists) {
$errors["email"] = "This e-mail address has already been used. Please enter another e-mail address.";
}
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
$_SESSION["temporary_username"] = htmlspecialchars($_POST["username"]);
$_SESSION["temporary_email"] = htmlspecialchars($_POST["email"]);
header("Location: register.php");
die();
}
$stmt = $db->prepare("INSERT INTO users (username, password, email) VALUES (:username, :password, :email)");
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$stmt->execute([
":username" => $username,
":password" => $password_hash,
":email" => $email
]);
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
$_SESSION["message"] = "Registration complete!";
header("Location: profile.php");
die();
}
catch (PDOException $e) {
echo "<p>" . $e->getMessage() . "</p>";
}
}
}
if (isset($_SESSION["errors"])) {
foreach ($_SESSION["errors"] as $error) {
echo "<p>" . $error . "</p>";
}
unset($_SESSION["errors"]);
}
?>
<form action="register.php" method="post">
<div><label for="username">Username</label></div>
<div><input type="text" name="username" id="username" value="<?php echo isset($_SESSION["temporary_username"]) ? $_SESSION["temporary_username"] : "" ?>" required></div>
<div><label for="password">Password</label></div>
<div><input type="password" name="password" id="password" required></div>
<div><label for="email">E-mail</label></div>
<div><input type="email" name="email" id="email" value="<?php echo isset($_SESSION["temporary_email"]) ? $_SESSION["temporary_email"] : "" ?>" required></div>
<div><input type="submit" name="register" value="Register Account"></div>
</form>
<?php
unset($_SESSION["temporary_username"]);
unset($_SESSION["temporary_email"]);
?>
<script src="main.js"></script>
</body>
</html>
</code></pre>
<p><strong>login.php</strong></p>
<pre><code><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Neue World - Login</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<?php
if (isset($_SESSION["message"])) {
echo "<p>" . $_SESSION["message"] . "</p>";
unset($_SESSION["message"]);
}
if (isset($_SESSION["loggedin"]) && $_SESSION["loggedin"]) {
$_SESSION["message"] = "You're already logged in!";
header("Location: profile.php");
die();
}
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$errors = [];
$username = "";
$password = "";
if (isset($_POST["login"])) {
if (isset($_POST["username"])) {
$username = $_POST["username"];
if (empty($username)) {
$errors["username"] = "Please enter a username.";
}
}
if (isset($_POST["password"])) {
$password = $_POST["password"];
if (empty($password)) {
$errors["password"] = "Please enter a password.";
}
}
try {
$db = new PDO("sqlite:dev.sqlite3", null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $db->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute([":username" => $username]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result["username"] !== $username) {
$errors["login"] = "Incorrect login credentials.";
}
if (!password_verify($password, $result["password"])) {
$errors["login"] = "Incorrect login credentials.";
}
if (!empty($errors)) {
if (!empty($errors)) {
$_SESSION["errors"] = $errors;
$_SESSION["temporary_username"] = htmlspecialchars($_POST["username"]);
header("Location: login.php");
die();
}
}
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
$_SESSION["message"] = "Successfully logged in!";
header("Location: profile.php");
die();
}
catch (PDOException $e) {
echo "<p>" . $e->getMessage() . "</p>";
}
}
}
if (isset($_SESSION["errors"])) {
foreach ($_SESSION["errors"] as $error) {
echo "<p>" . $error . "</p>";
}
unset($_SESSION["errors"]);
}
?>
<form action="login.php" method="post" name="login-form">
<div><label for="username">Username</label></div>
<div><input type="text" name="username" id="username" value="<?php echo isset($_SESSION["temporary_username"]) ? $_SESSION["temporary_username"] : "" ?>" required></div>
<div><label for="password">Password</label></div>
<div><input type="password" name="password" id="password" required></div>
<div><input type="submit" name="login" value="Login"></div>
</form>
<?php
unset($_SESSION["temporary_username"]);
?>
<script src="main.js"></script>
</body>
</html>
</code></pre>
<p><strong>profile.php</strong></p>
<pre><code><?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();
if ($_SERVER["REQUEST_METHOD"] === "GET") {
if (isset($_GET["logout"])) {
session_unset();
session_destroy();
header("Location: index.php");
die();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Project Neue World - Profile</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<?php
if (isset($_SESSION["message"])) {
echo "<p>" . $_SESSION["message"] . "</p>";
unset($_SESSION["message"]);
}
if (!isset($_SESSION["loggedin"]) || !$_SESSION["loggedin"]) {
$_SESSION["message"] = "Please <a href=\"register.php\">register</a> an account to view your profile.";
header("Location: index.php");
die();
}
?>
<p>Welcome to your profile, <?php echo $_SESSION["username"]; ?>.</p>
<?php
try {
$db = new PDO("sqlite:dev.sqlite3", null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $db->prepare("SELECT * FROM users WHERE username = :username");
$stmt->execute([":username" => $_SESSION["username"]]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo "<p>User ID: " . $result["id"] . "</p>";
echo "<p>E-mail Address: " . $result["email"] . "</p>";
}
catch (PDOException $e) {
echo "<p>" . $e->getMessage() . "</p>";
}
?>
<p><a href="?logout">Logout</a>.</p>
<script src="main.js"></script>
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T07:55:21.793",
"Id": "418949",
"Score": "1",
"body": "You should remove the `error_reporting(E_ALL); ini_set(\"display_errors\", 1);` in production. Any errors or warnings can give away information to a hacker. I would create a seperate 'start.php' file to include in each php file containing this, that way you only have to change it in one location."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T08:01:55.237",
"Id": "418952",
"Score": "1",
"body": "If you remove an user from the database they will stay logged in as long as 'loggedin' stays 'true' in their session. This could be for days, or longer. It is better to check `$_SESSION[\"username\"]` against the database each time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T18:22:32.367",
"Id": "418990",
"Score": "0",
"body": "@KIKOSoftware partially true for display_errors but absolutely wrong for error_reporting. You need your error reporting in production more than in dev. And surely you meant \"change display_errors to 0\", not remove."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T18:24:33.340",
"Id": "418992",
"Score": "0",
"body": "@YourCommonSense I would suggest to use your common sense in this case. :-) You're right that only removing 'display_errors' is enough (set to zero). Perhaps you should say why 'error_reporting' should stay?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T08:51:02.507",
"Id": "419042",
"Score": "1",
"body": "Why would you `trim` the password? What if the user wishes to use a space?"
}
] | [
{
"body": "<p>You should not be presenting any errors in production and don't offer the caught <code>$e->getMessage()</code>. These details will only help malicious actors (and not your users).</p>\n\n<p>When you want to check if a variable exists AND it is not zero-ish/falsey/null/empty, just use <code>!empty()</code> instead of doing <code>isset(...) && !empty(...)</code>.</p>\n\n<p>If you have already checked that a variable <code>isset()</code> then you want to check if it is zero-ish/falsey/null/empty, just use <code>!$variable_name</code> -- this has the same effect and avoids the unnecessary function call.</p>\n\n<p>I do not support the initialization of <code>$errors = [];</code>, <code>$username = \"\";</code>, <code>$password = \"\";</code>, and <code>$email = \"\";</code>. Just don't declare them. Empty username, password, or email should prevent any processes that rely on them. <code>!empty($errors)</code> both checks if the variable was declared AND has a positive count.</p>\n\n<p>You should not be bothering to make a trip to the database if the submission lacks a username, password, or email.</p>\n\n<p>You are rushing right into processing <code>$result[\"username\"]</code> from <code>$result = $stmt->fetch(PDO::FETCH_ASSOC);</code>, but you should check that that element was <em>actually</em> generated.</p>\n\n<p>This simply looks careless, remove the redundant check:</p>\n\n<pre><code>if (!empty($errors)) {\n if (!empty($errors)) {\n ...\n }\n}\n</code></pre>\n\n<p>You shouldn't be throwing <code>htmlspecialchars()</code> around so much. You should be calling that ONLY just before printing to screen (<code>$_SESSION[\"temporary_username\"]</code>). Definitely don't foul with users' email account before processing the value. If you want to sanitize certain input values so that specific characters are filtered out, fine, just be clear about this value mutating when the user is filling the form so that no one has any surprises.</p>\n\n<p>Minimize total trips to the database. Combine the logic in <code>SELECT username FROM users WHERE username = :username</code> with <code>SELECT email FROM users WHERE email = :email</code> to form <code>SELECT email FROM users WHERE username = :username OR email = :email</code>, then process the single result set to check for either pre-existing value.</p>\n\n<p>In <code>login.php</code>, you know you are only processing the <code>username</code> and <code>password</code> values so update your query's SELECT clause to nominate those two columns only. Only ever ask the database for the values that you intend to use.</p>\n\n<p><code>!isset($_SESSION[\"loggedin\"]) || !$_SESSION[\"loggedin\"]</code> can be condensed to <code>empty($_SESSION[\"loggedin\"])</code>.</p>\n\n<p>I don't recommend using SESSION storage to hold any \"identifiable\" values. Just keep the <code>id</code> in there and use that for all subsequent interactions. <a href=\"https://stackoverflow.com/a/42869960/2943403\">I have mentioned this before at StackOverflow</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T18:23:02.423",
"Id": "418991",
"Score": "0",
"body": "Surely you meant switch off display errors, not error reporting"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T20:56:34.227",
"Id": "418999",
"Score": "1",
"body": "Yes. I've edit my poor wording. Welcome back to SO. Let's hope you stick around for a while."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:04:20.393",
"Id": "419070",
"Score": "0",
"body": "Thank you for the in-depth answer! Lots of useful information here.\n\nIn regards to `$e->getMessage()`, how should I go about handling the `catch` part of my `try-catch` block instead?\n\nRegarding variable initialization, are you saying I can just use those variables by declaring them when I need them, or I shouldn't be using variables at all in this case?\n\nRe: `$result[\"some_var\"]`. Are you saying I need to make sure result contains... results before trying to use them?\n\nOn the last bit about `SESSION`s, would I just want to do something akin to `$_SESSION[\"user_id\"] = $id`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:10:44.097",
"Id": "419136",
"Score": "1",
"body": "Regarding catching pdo errors, I'll recommend reading the link in YCS's answer. You can present a vague error message to the user which states that something went wrong and that the developer has been made aware. Just don't ever give any specific details that a baddie would find valuable. Rather than instantiating `$username` then conditionally overwriting it, I recommend refactoring the flow so that disqualifying inputs from the user do not declare a `$username` and instead just exit that section of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:13:20.043",
"Id": "419137",
"Score": "1",
"body": "After executing your SELECT query, you should perform an `if` or `while` check to see if the result is `null` (lots of places to research this on Stackoverflow.). Finally, yes, I recommend using an arbitrary / autoincremented value as the user's id for SESSION storage."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T11:42:01.443",
"Id": "216580",
"ParentId": "216574",
"Score": "2"
}
},
{
"body": "<p>I would say that this code is quite above the average at whole. Yet there are some issues as well.</p>\n\n<h3>Error reporting</h3>\n\n<p>To elaborate on what others said about error reporting. Actually I've got a comprehensive article on <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">PHP error reporting basics</a>, which I highly recommend to read, but here is a gist just to get it right:</p>\n\n<p>Error reporting is essential. A good programmer always crave for the every error message they can get. And it should be at max all the time. The difference is only the destination: on a local dev server it is naturally should be your screen, but on a production server errors should be completely banned from screen, going to the log file instead. Hence the two different setups:</p>\n\n<ul>\n<li>On a development server\n\n<ul>\n<li><strong>error_reporting</strong> should be set to E_ALL value;</li>\n<li><strong>display_errors</strong> should be set to 1</li>\n</ul></li>\n<li>On a production server\n\n<ul>\n<li><strong>error_reporting</strong> should be set to E_ALL value;</li>\n<li><strong>display_errors</strong> should be set to 0</li>\n<li><strong>log_errors</strong> should be set to 1</li>\n</ul></li>\n</ul>\n\n<p>So this setup contradicts a bit with what you have been told before but it makes a perfect sense. </p>\n\n<h3>Database exposed</h3>\n\n<p>Another security issue is the Sqlite database location. Assuming it is on the same level with other files, it means it is accessible by site users, so anyone would be able to download your whole database. I don't think its a good idea to let is so. Consider moving the database file outside the site root. And also use the <strong>absolute path</strong> to the file. To help with this issue I also have an article on <a href=\"https://phpdelusions.net/articles/paths\" rel=\"nofollow noreferrer\">files and directories</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:01:00.360",
"Id": "419044",
"Score": "0",
"body": "As you have written extensively on PDO and you stress the importance of setting `EMULATE_PREPARES` to `false`, is there a reason why you haven't mentioned it? (P.S. Not bashing just genuinely curious why no-one has mentioned it, your resource on PDO has been invaluable)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:24:02.310",
"Id": "419049",
"Score": "0",
"body": "@Script47 it is definitely not me who stressed on the importance, I would rather say that security-wise emulated statements are no worse than real ones. It is for convenience in the first place I recommend to have the emulation off. Besides, I am no expert in sqlite, and just don't know how the emulation works for this driver."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:25:02.040",
"Id": "419050",
"Score": "0",
"body": "Fair enough, thanks for the clarity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:05:23.980",
"Id": "419071",
"Score": "0",
"body": "Thank you for the answer! So would you recommend I move the database to a subfolder within the site root, or to a folder \"above\" the root?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:06:55.533",
"Id": "419072",
"Score": "1",
"body": "@RobertHolman Definitely above the site root"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T19:10:39.427",
"Id": "216597",
"ParentId": "216574",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216580",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T07:35:49.120",
"Id": "216574",
"Score": "4",
"Tags": [
"php",
"authentication",
"pdo"
],
"Title": "Rudimentary registration and login system"
} | 216574 |
<p>I have created an employee object to be immutable.</p>
<pre><code>package com.immutable.ex01;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public final class Employee implements Cloneable, Externalizable{
private final Integer age;
private final String name;
private final List<String> companies;
private final Date dob;
public Employee(Integer age, String name,List<String> companies, Date dob) {
this.age = age;
this.name = name;
this.companies = companies;
this.dob = dob;
}
public Integer getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public Date getDob() {
Calendar cal = Calendar.getInstance();
cal.setTime(this.dob);
return cal.getTime();
}
public List<String> getCompanies() {
List<String> clone = new ArrayList<String>(this.companies.size());
for(String companyName : this.companies) {
clone.add(companyName);
}
return clone;
}
@Override
public String toString() {
StringBuffer strb = new StringBuffer();
strb.append("AGE").append(" ").append(this.age)
.append(", NAME ").append(this.name)
.append(", DOB ").append(this.getDateString())
.append(", COMPANIES WORKED IN ");
for(String companyName : this.companies) {
strb.append(companyName).append(",");
}
strb.deleteCharAt(strb.length() - 1);
return strb.toString();
}
@Override
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException("Cannot be cloned");
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
throw new IOException("This operation is not supported");
}
@Override
public void readExternal(ObjectInput in) throws IOException {
throw new IOException("This operation is not supported");
}
private String getDateString() {
String date = null;
DateFormat df = null;
try {
df = new SimpleDateFormat("dd MMM yyyy");
date = df.format(this.dob);
}catch(Exception e) {
e.printStackTrace();
}
return date;
}
}
</code></pre>
<p>My main method class</p>
<pre><code>package com.immutable.ex01;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MainTest01 {
public static void main(String [] args) {
Employee emp = null;
List<String> companyList = null;
Date date = null;
try {
companyList = new ArrayList<String>();
companyList.add("IBM");
companyList.add("Google");
companyList.add("Norton");
companyList.add("Seable");
companyList.add("Nekki");
date = toDate("28 Oct 1981");
emp = new Employee(23, "John Molkovich", companyList, date);
date = emp.getDob();
date = new Date();
companyList = emp.getCompanies();
companyList.add("Toyo Corp");
System.out.println(emp);
}catch(Exception e) {
e.printStackTrace();
}
}
private static Date toDate(String dateString) throws Exception{
Date d = null;
DateFormat df = new SimpleDateFormat("dd MMM yyyy");
d = df.parse(dateString);
return d;
}
}
</code></pre>
<p>Please review my code and check if I have achieved immutability for my employee class.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T15:04:06.540",
"Id": "418976",
"Score": "2",
"body": "If you create an immutable Employee, there's no need to clone it, never. So implementing Cloneable doesn't make sense."
}
] | [
{
"body": "<p>Your <code>Employee</code> is frozen in time; they can never get any older!</p>\n\n<p>Age should be calculated from date-of-birth and “today”, not stored in an immutable field. </p>\n\n<hr>\n\n<p>The <code>getCompanies()</code> method could be written simply as:</p>\n\n<pre><code>return new ArrayList<>(this.companies);\n</code></pre>\n\n<p>Or perhaps:</p>\n\n<pre><code>return Collections.unmodifiableList(this.companies);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:55:25.880",
"Id": "216585",
"ParentId": "216581",
"Score": "2"
}
},
{
"body": "<p>First, I'll note that your class is <em>not</em> immutable currently. You allow the user to pass in a <code>List</code> of companies, but don't make a copy of them. If the user modifies the list after passing it in, it will be modified inside the <code>Employee</code> as well. Just make a copy of it to remedy this:</p>\n\n<pre><code>public Employee(Integer age, String name, List<String> companies, Date dob) {\n this.age = age;\n this.name = name;\n this.companies = new ArrayList<>(companies);\n this.dob = dob;\n}\n</code></pre>\n\n<p>And you can do the same in <code>getCompanies</code> as @AJ noted.</p>\n\n<hr>\n\n<hr>\n\n<p>And I'll mention some warnings that pop up as soon as I pasted this into IntelliJ:</p>\n\n<blockquote>\n <p>Externalizable class 'Employee' has no 'public' no-arg constructor</p>\n</blockquote>\n\n<p>At <code>class Employee...</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>Iteration can be replaced with bulk 'Collection.addAll' call</p>\n</blockquote>\n\n<p>In <code>getCompanies</code> in the <code>add</code> loop. You can just pass a collection to <code>addAll</code> and have it do the looping.</p>\n\n<hr>\n\n<blockquote>\n <p>'StringBuffer strb' may be declared as 'StringBuilder'</p>\n</blockquote>\n\n<p>In <code>toString</code>. <code>StringBuffer</code> is a synchronized version of <code>StringBuilder</code>. You don't need synchronization here though.</p>\n\n<hr>\n\n<blockquote>\n <p>@Override is not allowed when implementing interface method</p>\n</blockquote>\n\n<p>At the <code>@Override</code> annotations for the <code>Externalizable</code> methods.</p>\n\n<hr>\n\n<hr>\n\n<p>You can also simplify the stringification of <code>companies</code> in <code>toString</code> using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html\" rel=\"nofollow noreferrer\"><code>StringJoiner</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-\" rel=\"nofollow noreferrer\"><code>String.join</code></a>:</p>\n\n<pre><code>public String toString() {\n StringJoiner joiner = new StringJoiner(\", \");\n joiner.add(\"AGE \" + this.age)\n .add(\"NAME \" + this.name)\n .add(\"DOB \" + this.getDateString())\n .add(\"COMPANIES WORKED IN: \"\n + String.join(\", \", this.companies));\n\n return joiner.toString();\n}\n</code></pre>\n\n<blockquote>\n <p>AGE 23, NAME John Molkovich, DOB 28 Oct 1981, COMPANIES WORKED IN: IBM, Google, Norton, Seable, Nekki</p>\n</blockquote>\n\n<p><code>StringJoiner</code> is like <code>StringBuffer</code>/<code>StringBuilder</code>, but it automatically adds a <code>\", \"</code> between each addition, and <code>String.join</code> adds a <code>\", \"</code> between each company. No more needing to manually add commas for each field, and needing to delete the trailing company comma.</p>\n\n<p>And don't worry about using <code>append</code> methods instead of <code>+</code> at every opportunity like you were doing. Iirc, <code>+</code> is automatically optimized to a <code>StringBuilder</code> with <code>append</code> calls when possible, and even when it's not, the overhead you'll suffer from using <code>+</code> likely won't be a problem. Go for the readable code here instead of the over-optimized code.</p>\n\n<hr>\n\n<hr>\n\n<p>And what exception are you anticipating being thrown in <code>main</code>? You should get rid of the whole <code>try</code>. Let the sucker crash if it's going to crash. It's usually easier to get information about an exception when the IDE is allowed to process the actual crash instead of just a printout.</p>\n\n<hr>\n\n<hr>\n\n<p>And a small note, I don't see any reason to have <code>this.age</code> be a wrapped <code>Integer</code>. It would be better for it to be a primitive <code>int</code> (or even a <code>short</code>). I'd change the field type to <code>int</code>, along with the <code>Employee</code> constructor parameter and the return type of <code>getAge</code>.</p>\n\n<hr>\n\n<hr>\n\n<p>You could even get rid of the getters for your immutable fields like <code>age</code>. They can't be overwritten anyways since they're final:</p>\n\n<pre><code>class Immutable {\n public final int age;\n\n public Immutable(int age) {\n this.age = age;\n }\n\n public static void main(String[] args) {\n Immutable i = new Immutable(10);\n\n i.age = 4;\n\n System.out.println(i.age);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>Error:(11, 10) java: cannot assign a value to final variable age</p>\n</blockquote>\n\n<p>A getter is necessary for cases like <code>getCompany</code> where the field is mutable, but numbers are immutable. <a href=\"https://stackoverflow.com/questions/6927763/immutable-type-public-final-fields-vs-getter\">There's a discussion on the topic here.</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T23:09:34.317",
"Id": "216609",
"ParentId": "216581",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T12:05:58.790",
"Id": "216581",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"immutability"
],
"Title": "Immutable employee class"
} | 216581 |
<p>I have created a Spring Boot Microservice for playing Rock Paper Scissrors. I have tried to follow best practices, but still would appreciate some critique on my code. Thanks.</p>
<pre><code>@RestController
public class RockPaperScissorsController {
@Autowired
private PlayerService playerService;
@Autowired
private HttpServletRequest context;
@Autowired
private GameSessionService gameSessionService;
@Autowired
private GameplayService gameplayService;
public RockPaperScissorsController(PlayerService playerService,
GameSessionService gameSessionService) {
this.playerService = playerService;
this.gameSessionService = gameSessionService;
}
@GetMapping(value = "/ping", produces = "application/json")
public ResponseEntity<String> ping() {
return ResponseEntity.ok("{\"response\":\"pong\"}");
}
@GetMapping(value = "/player/{playerName}", produces = "application/json")
public ResponseEntity player(@PathVariable("playerName") String playerName) {
try {
Player player = playerService.getPlayer(playerName);
return ResponseEntity.ok(player);
} catch (RPSException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@PostMapping(value = "/player/{playerName}", produces = "application/json")
public ResponseEntity playerPOST(@PathVariable("playerName") String playerName) {
try {
playerService.createPlayer(playerName);
return ResponseEntity.ok().body("");
} catch (RPSException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@DeleteMapping(value = "/player/{playerName}", produces = "application/json")
public ResponseEntity playerDELETE(@PathVariable("playerName") String playerName) {
try {
playerService.deletePlayer(playerName);
return ResponseEntity.ok("");
} catch (RPSException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@PostMapping(value = "/createInvite/{playerName}", produces = "application/json")
public ResponseEntity createInvite(@PathVariable("playerName") String inviter) {
try {
Player player = playerService.getPlayer(inviter);
GameSession session = gameSessionService.createSessionFrom(new Invite(player));
return ResponseEntity.ok(session);
} catch (RPSException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@PostMapping(value = "/acceptInvite/{inviteCode}/{playerName}", produces = "application/json")
public ResponseEntity acceptInvite(@PathVariable("inviteCode") String inviteCode,
@PathVariable("playerName") String playerName) throws InvalidOperationException {
try {
Player player = playerService.getPlayer(playerName);
return ResponseEntity.ok(gameSessionService.acceptInvite(player, inviteCode));
} catch (RPSException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@GetMapping(value = "/session/{inviteCode}", produces = "application/json")
public ResponseEntity session(@PathVariable("inviteCode") String inviteCode) {
return ResponseEntity.ok(gameSessionService.sessions().get(inviteCode));
}
@PostMapping(value = "/readyplayer/{playername}", produces = "application/json")
public ResponseEntity ready(@PathVariable("playername") String playerName) {
try {
Player player = playerService.changePlayerState(playerName, Player.State.READY);
return ResponseEntity.ok(player);
} catch (RPSException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
@PostMapping(value = "/play", produces = "application/json")
public ResponseEntity play(@RequestBody PlayRequest playRequest) {
try {
gameplayService.play(playRequest);
return ResponseEntity.ok().body("");
} catch (RPSException e) {
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.NOT_IMPLEMENTED).body("");
}
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>field-based vs constructor-based dependency injection<br>\nPlacing the <code>@AutoWired</code> annotation on the instance variables means the Spring container will use field-based injection. It will <strong>NOT</strong> use the constructor to populate the dependencies. If you want to signal to the container to use constructor-based injection, you need to place the annotation on the method. and why the constructor is initializing only two dependencies when there are three?</p></li>\n<li><p>ping return<br>\nreturning hard-coded json String is not best practice. in the future, you may want to extend the functionality for example to return detailed status of external resources (like Database, storage, etc). either use a Map or a user defined POJO.</p></li>\n<li><p>Method names<br>\n<code>playerPOST</code>, <code>playerDELETE</code> is both uninformative as well as doesn't follow naming convention. why no use the names of the service methods? and why return an empty String? just don't return any body at all.</p></li>\n<li><p>producing json<br>\nSpring has an enumerated set of values for <code>produces</code> attribute. class name: <code>org.springframework.http.MediaType</code> </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T07:06:55.937",
"Id": "216631",
"ParentId": "216584",
"Score": "1"
}
},
{
"body": "<ol>\n<li>You do not need ping within your controller. Check out Spring boot actuator</li>\n<li>Each method having duplicated error handling. You can move it to <code>@ControllerAdvice</code></li>\n<li>Method names like <code>playerPOST</code>, <code>playerDELETE</code> aren't helpful. Consider this as a normal class and have normal method names like <code>createPlayer</code>, <code>deletePlayer</code></li>\n<li>You need not define <code>produces</code> attribute for each mapping, <code>RestController</code> defaults to JSON</li>\n<li>Returning <code>ok(\"\")</code> doesn't make sense. Should be either returning the player object, or use <code>ResponseEntity.created()</code> (<code>201</code>)</li>\n<li>Why are you autowiring <code>HttpServletRequest context</code>?</li>\n<li>Should use <code>AllArgsConstructor</code> - constructor based autowiring</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T08:14:12.007",
"Id": "216632",
"ParentId": "216584",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T14:54:49.750",
"Id": "216584",
"Score": "4",
"Tags": [
"java",
"rest",
"spring"
],
"Title": "Rest Controller in Spring Boot for Rock Paper Scissors REST API"
} | 216584 |
<p>A function which replaces an unicode character in a string:</p>
<pre><code>void replaceAllOccurences(std::string& source,
const std::string& replaceFrom,
const std::string& replaceTo)
{
std::vector<std::uint8_t> data(source.begin(), source.end());
std::vector<std::uint8_t> pattern(replaceFrom.begin(), replaceFrom.end());
std::vector<std::uint8_t> replaceData(replaceTo.begin(), replaceTo.end());
std::vector<std::uint8_t>::iterator itr;
while((itr = std::search(data.begin(), data.end(), pattern.begin(), pattern.end())) != data.end())
{
data.erase(itr, itr + pattern.size());
data.insert(itr, replaceData.begin(), replaceData.end());
}
source = std::string(data.begin(), data.end());
}
</code></pre>
<p>Usage:</p>
<pre><code>std::string source = "123€AAA€BBB";
std::string replaceFrom = "€";
std::string replaceTo = "\x80";
replaceAllOccurences(source, replaceFrom, replaceTo);
</code></pre>
<p><code>replaceTo</code> may be get from some external conversion library, for example: <a href="https://github.com/unnonouno/iconvpp" rel="nofollow noreferrer">iconvpp</a>. Normally I would convert the whole source using iconvpp library but I have a case where I need to convert only particular character, for example "€".</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:29:14.210",
"Id": "419114",
"Score": "0",
"body": "Does this have anything specific to do with unicode or is it simply a way of replacing one sequence of characters with another?"
}
] | [
{
"body": "<p>You don't need the <code>std::vector<std::uint8_t></code> objects at all. You can use the input <code>std::string</code> objects directly.</p>\n\n<p>Also, the code in the <code>while</code> loop needs to be updated for the following issues:</p>\n\n<ol>\n<li><p>Make sure to capture the return value opf <code>source.erase</code>. If you don't the iterator is invalid.</p></li>\n<li><p>To avoid infinite loop, use <code>itr</code> as the first argument to <code>std::search</code>.</p></li>\n<li><p>Update <code>itr</code> inside the loop appropriately to avoid an infinite loop.</p></li>\n</ol>\n\n<p></p>\n\n<pre><code>void replaceAllOccurences(std::string& source,\n const std::string& replaceFrom,\n const std::string& replaceTo)\n{\n std::string::iterator itr = source.begin();\n while((itr = std::search(itr, source.end(), replaceFrom.begin(), replaceFrom.end())) != source.end())\n {\n itr = source.erase(itr, itr + replaceFrom.size());\n\n // itr is going be invalid after insert. Keep track of its\n // distance from begin() so we can update itr after insert.\n auto dist = std::distance(source.begin(), itr);\n\n source.insert(itr, replaceTo.begin(), replaceTo.end());\n\n // Make itr point to the character 1 past what got replaced.\n // This will avoid infinite loop incase the first character of\n // replaceTo is the same as the character being replaced.\n itr = std::next(source.begin(), dist+1);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:22:12.777",
"Id": "419076",
"Score": "1",
"body": "Doesn't `insert()` invalidate iterators?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:28:06.440",
"Id": "419113",
"Score": "1",
"body": "Might have an issue with infinite loops."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:16:19.107",
"Id": "419123",
"Score": "0",
"body": "@TobySpeight, yes, it does. Thanks for pointing it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:16:35.047",
"Id": "419124",
"Score": "0",
"body": "@MartinYork, Indeed. Updated to address that issue."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T05:37:57.890",
"Id": "216624",
"ParentId": "216598",
"Score": "1"
}
},
{
"body": "<p>If you're not worried about performance, you can replace all the manual work by using the <code><regex></code> facilities, which results in a considerable reduction of code to test and maintain.</p>\n\n<pre><code>#include <regex>\n\nsource = std::regex_replace(source, std::regex(\"€\"), \"\\x80\");\n</code></pre>\n\n<p>I would still keep it in a separate function to make it easy to change the implementation afterwards.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T06:51:05.450",
"Id": "216629",
"ParentId": "216598",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T19:16:00.577",
"Id": "216598",
"Score": "4",
"Tags": [
"c++",
"c++11",
"unicode"
],
"Title": "Replace unicode character in the string"
} | 216598 |
<p>I am writing a simple game with pyGame.</p>
<p>Structure-wise, I have separated my game into several files:</p>
<ul>
<li>main.py <code># the main runner, it loads up the environment</code></li>
<li>class_tank.py <code># it defines the player-controlled tank class</code></li>
<li>class_shell.py <code># it defines the shells that shoot from the player's tank</code></li>
<li>class_mob.py <code># it defines the enemies</code></li>
</ul>
<p>The relationship of the modules above is:</p>
<ul>
<li><code>main.py</code> imports <code>class_tank.py</code>, <code>class_shell.py</code> and <code>class_mob.py</code></li>
<li>all of <code>class_tank.py</code>, <code>class_shell.py</code> and <code>class_mob.py</code> are subclasses of <code>pygame.Sprite.sprite</code>. </li>
</ul>
<p>Currently, I noticed that I am repeating myself by having the following code snippets in all four files:</p>
<pre><code>current_path = os.path.dirname(os.path.realpath(__file__))
resource_path = os.path.join(current_path, 'Resources')
img_folder_path = os.path.join(resource_path, 'Images')
bg_img_path = os.path.join(img_folder_path, "xxxx.png")
</code></pre>
<p><code>xxxx.png</code> is the image I need to load for the background (main.py), for the player (class_tank.py), for bullets (class_shell.py) and for enemies (class_mob.py).</p>
<p>Logically, this code snippet does belong to each of the file, but is there any elegant way to not repeat myself? The only way I can think of is to define an additional <code>helper</code> class.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T23:04:09.357",
"Id": "419002",
"Score": "0",
"body": "What is the class hierarchy (if any) in your program? Which files import which other files? Without more context, we can’t give you a very good answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T23:11:35.417",
"Id": "419003",
"Score": "0",
"body": "@AJNeufeld, thanks. I added more info to my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T02:23:14.440",
"Id": "419019",
"Score": "4",
"body": "I want to answer your question, but as it currently stands, without actual code, it is not really a \"Code Review\" question. There are several ways to avoid repeating yourself. 1) Your \"helper\" class. 2) An `Entity` class that derives from `pygame.sprite.Sprite`, with an image load method, that your other classes derive from. 3) Dependency injection; your main module could load all images and inject them into each `class`. Or combinations of the above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T02:55:10.073",
"Id": "419021",
"Score": "0",
"body": "@AJNeufeld, thank you so much. I did not know anything about dependency injection, I will take a look."
}
] | [
{
"body": "<p>You don't necessarily need classes in Python. The <code>helper</code> class approach is the same direction as I would go, just with a plain module.<br>\nBasically, your <code>resource_path</code> and <code>img_folder_path</code> are constants, so I would simply create a module <code>constants.py</code> with the following:</p>\n\n<pre><code>import os\n\nRESOURCE_PATH = os.path.join(os.path.realpath(__file__), 'Resources')\nIMG_FOLDER_PATH = os.path.join(resource_path, 'Images')\n</code></pre>\n\n<p>You can then simply import <code>constants.py</code> everywhere you need to know those paths.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T16:57:44.280",
"Id": "216664",
"ParentId": "216600",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216664",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T19:32:31.563",
"Id": "216600",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"pygame",
"helper"
],
"Title": "Locating an image file in a pyGame"
} | 216600 |
<p>I have written a simplified version of the <a href="https://archive.codeplex.com/?p=marsroverexercise" rel="nofollow noreferrer"><strong>Mars Rover</strong> challenge</a> in Ruby. Please review it for best coding practices.</p>
<blockquote>
<p>A rover’s position and location is represented by a combination of x and y co-ordinates and a letter representing one of the four cardinal compass points. The plateau is divided up into a grid to simplify navigation. An example position might be 0, 0, N, which means the rover is in the bottom left corner and facing North.</p>
<p>In order to control a rover , NASA sends a simple string of letters. The possible letters are ‘L’, ‘R’ and ‘M’. ‘L’ and ‘R’ makes the rover spin 90 degrees left or right respectively, without moving from its current spot. ‘M’ means move forward one grid point, and maintain the same heading.</p>
</blockquote>
<pre><code>class Rover
def initialize(x, y, direction)
@x = x
@y = y
@direction = direction
end
def instruction(position)
position.each do |input|
if input == 'L'
left
elsif input == 'R'
right
else
move
end
end
puts "this is where the rover should be: x= #{@x} y= #{@y} facing= #{@direction}"
end
def right
if @direction == 'S'
puts "the rover is facing West."
@direction = 'W'
elsif @direction == 'N'
puts "the rover is facting East"
@direction = 'E'
elsif @direction == 'W'
puts "the rover is facting North"
@direction = 'N'
else
puts "the rover is facing South"
@direction = 'S'
end
end
def left
if @direction == 'N'
puts "the rover is facing North."
@direction = 'W'
elsif @direction == 'W'
puts "the rover is facting West"
@direction = 'S'
elsif @direction == 'E'
puts "the rover is facting East"
@direction = 'N'
else
puts "the rover is facing South"
@direction = 'E'
end
end
def move
if @direction == 'N'
@y += 1
elsif @direction == 'E'
@x += 1
elsif @direction == 'S'
@y -= 1
else
@x -= 1
end
end
end
#instance of our rovers with direction x, y, direction facing N, E, S, or W
mars_rover_a = Rover.new(0,0,'N')
# mars_rover_a.move()
mars_rover_b = Rover.new(1,1,'E')
#call the instruction for each instance of the object rover
mars_rover_a.instruction(['L','M','R','M','L','M','R','R','M'])
mars_rover_b.instruction(['R','M','M','L','M','L','L','M'])
</code></pre>
| [] | [
{
"body": "<p>I'd suggest that the position, and maybe orientation also, ought to be its own object ... \"Location\"?</p>\n\n<p>I'd also prefer to use symbols rather than strings where possible, and rely on data rather than logic (see use of hashes below).</p>\n\n<p>You might be interested in implementing a builder method, in which the methods called simply return the original object, which allows commands to be daisy-chained ...</p>\n\n<pre><code>class Location\n LEFT = {\n n: :w,\n e: :n,\n s: :e,\n w: :s\n }\n\n RIGHT = {\n n: :e,\n e: :s,\n s: :w,\n w: :n\n }\n\n def initialize(x:, y:, direction:)\n @x = x\n @y = y\n @direction = direction\n end\n\n def left\n @direction = LEFT.fetch(@direction)\n self\n end\n\n def right\n @direction = RIGHT.fetch(@direction)\n self\n end\n\n def move\n case direction\n when :n\n self.y += 1\n when :e\n self.x += 1\n when :s\n self.y -= 1\n when :w\n self.x -= 1\n end\n self\n end\n\n attr_reader :x, :y, :direction\n\n private\n\n attr_writer :x, :y, :direction\nend\n</code></pre>\n\n<p>Hence:</p>\n\n<pre><code>2.4.5 :125 > l = Location.new(x: 0, y: 0, direction: :n)\n => #<Location:0x00007f9f5329e858 @x=0, @y=0, @direction=:n> \n2.4.5 :126 > l.left.move.right.move.left.move.right.right.move\n => #<Location:0x00007f9f5329e858 @x=-1, @y=1, @direction=:e> \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T12:21:58.633",
"Id": "216776",
"ParentId": "216601",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T20:12:32.930",
"Id": "216601",
"Score": "3",
"Tags": [
"programming-challenge",
"ruby"
],
"Title": "Mars Rover challenge in Ruby"
} | 216601 |
<p>I've been looking for a solution to the may readers one writer in Java.
I was intrigued by <a href="https://codereview.stackexchange.com/questions/127234/reader-writers-problem-using-semaphores-in-java?newreg=afcfc71833ab4152b20bffdaccd175d7">this question</a> posted here and I read the <a href="https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem" rel="nofollow noreferrer">Wikipedia entry</a> about it.</p>
<p>So far, I've reached a fine solution, or at least that's what I think. I've set up a new <a href="https://github.com/oscar-besga-panel/JManyReadersOneWriter" rel="nofollow noreferrer">GitHub repo</a> to put the code to be used in another project if people want. But I'm open to improvements and critics if you see fit.</p>
<p>The pseudocode of the main class is here:</p>
<pre><code>abstract class AbsrtactReadersWriter<T> {
Semaphore readCountSempaphote = new Semaphore(1);
Semaphore resourceSemaphore = new Semaphore(1, true);
Semaphore serviceQueueSemaphore = new Semaphore(1,true);
int readCount = 0;
public final T read() {
T data = null;
try {
// Entry to read
serviceQueueSemaphore.acquire();
readCountSempaphote.acquire();
readCount++;
if (readCount == 1){
resourceSemaphore.acquire();
}
serviceQueueSemaphore.release();
readCountSempaphote.release();
// CRITICAL SECTION Do read
data = executeReading();
// Exit to read
readCountSempaphote.acquire();
readCount--;
if (readCount == 0){
resourceSemaphore.release();
}
readCountSempaphote.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
return data;
}
// Protected critical section that read the resource
abstract protected T executeReading();
public final void write(T data) {
try {
// Entry write
serviceQueueSemaphore.acquire();
resourceSemaphore.acquire();
serviceQueueSemaphore.release();
// CRITICAL SECTION Do Write
executeWriting(data);
// Exit write
resourceSemaphore.release();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
// Protected critical section that writes to the resource
abstract protected void executeWriting(T data);
}
</code></pre>
<p>This pseudocode lacks some elements (privates, comments) form the class on the <a href="https://github.com/oscar-besga-panel/JManyReadersOneWriter" rel="nofollow noreferrer">GitHub repo</a>, but hits the point. In the repo, you can also see examples and tests.</p>
<p>The starvation problem on readers/writer is solved by Java itself, as the semaphores are created with the <code>fair</code> parameter, that forces the fairness of the blocking and a FIFO queue on the waiting threads. I use an <code>AtomicInteger</code> to store the <code>readcount</code>, even it's protected; the equality operation maybe not and doesn't impose a great penalty.</p>
<p>[EDIT1] As suggested by @greybeard I now use an integer and not an AtomicInteger. Code tested and changed into git</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T23:44:01.663",
"Id": "419005",
"Score": "0",
"body": "Welcome to Code Review! I find a name like `readCountSempaphote` unsettling. Using a (`java.util.concurrent.`?)`Semaphore` around a (`…atomic`?)`AtomicInteger` looks *belt and braces*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:58:27.840",
"Id": "419210",
"Score": "0",
"body": "I'll try to use a simple int and see if it works. If that the case, I'll upload the changes and edit the question"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T20:41:11.947",
"Id": "216603",
"Score": "2",
"Tags": [
"java",
"multithreading",
"concurrency",
"producer-consumer"
],
"Title": "Many-readers-one-writer with semaphores and multithreading"
} | 216603 |
<p>So i have written this code to save and load data for my C++ game to a file, this way I don't have to hard code every single room and item for the game. Essentially here's how the game works: So you have a Map, and a map consists of rooms. A room contains tiles and items. there are 32x18 tiles in a room, and a tile is just a 40x40 image basically, and each tile has a unique numeric ID. An item works similarly, however, it can be at any coordinate in the room and isn't necessarily 40x40 pixels, it has a sprite, and a unique numeric ID, and of course data for it's position in the room (the tiles don't need this because their index in the tiles matrix act as their coordinates, just multiply it's indexes by 40 and you have it's coordinates for screen). There is a RoomBuilder class which my saving and loading feature is in, and this allows me as the developer to click on the screen and place tiles/items which will be added to the current room i'm in. If you need further clarification on how a room system works, think original Legend of Zelda on the NES, how you are in a room then when you go off the screen you are in another room pretty much.</p>
<p>What I do is I Save the data as a string to the output file like this: A line will have Tiles: at the beginning to signify that it is the tiles for that room, there are 576 numbers on that line each separated by a space (32x18 tiles per room = 576). It starts at the top left and saves them row by row, left to right.</p>
<p>When I read the line with Tiles, i save each number into a vector, then loop through that vector at the beginning and set each tile ID in the room based on that vector, so it will start at index 0 in the vector, get that number, go all the way to 32 and save those as the first row of tiles, then go to 64 from there and save those as the second row of tiles, and so on.</p>
<p>For the items, each item in the room has it's own line, it starts with ID: to signify that it's an item, and there are 3 numbers on an item's line in the text file; the first one is it's numeric ID, the second one is it's X position, the third one is it's Y position. I read that, and add an item to the room's vector of items based on the item's ID and position.</p>
<p>The code works, but i'm not happy with it because it's ugly, very finicky, could have bugs I don't know about, and there are parts that I don't fully understand about it (mainly the string stream in the loading method where i have a temporary string and then parse each integer out, I found that code online and tested it, it worked great for my purposes but the point of this project is to learn, and i'm not learning from that since I don't understand it). If I change anything slightly that could break the whole loading/saving system and it will cause a segfault error if that breaks because now I am in a room that doesn't exist since I wasn't able to load any of the rooms.</p>
<p>Feedback is greatly appreciated, I'm looking for things I did wrong with this code, things that could cause it to break, and some tips on how I could improve it, specifically formatting the output and reading it easier.</p>
<p>Saving Method:</p>
<pre><code>bool RoomBuilder::saveRooms(){
//open the output file to save the rooms to:
std::ofstream out("GameData\\DefaultMapRoomBuilder.klvl");
//loop through each room in the rooms vector
for(int i = 0; i < rooms.size(); i++){
//write the tiles matrix for this room to the file:
out << "Tiles: ";
for(int j = 0; j < 32; j++){
for(int k = 0; k < 18; k++){
out << rooms.at(i).getTile(j, k) << " ";
}
}
out << "\n";
//save the items and their positions to the room:
for(int j = 0; j < rooms.at(i).items.size(); j++){
out << "Items: \n";
int itemID = rooms.at(i).items.at(j).getItemID();
float xPos = rooms.at(i).items.at(j).getPosition().x;
float yPos = rooms.at(i).items.at(j).getPosition().y;
out << "ID: " << itemID << " " << xPos << " " << yPos << std::endl;
}
//text to signify end of current room:
out << "END_OF_ROOM" << "\n";
}
return true;
}
</code></pre>
<p>loading method:</p>
<pre><code>bool RoomBuilder::loadRooms(){
std::ifstream in("GameData\\DefaultMapRoomBuilder.klvl");
std::vector<std::string> lines;
//only happens if input stream is open:
if(in.is_open()){
//string to store the current line we're on:
std::string line;
//while loop to loop through each line:
while(std::getline(in, line)){
//add each line to the lines vector:
lines.push_back(line);
}
//close the file now that we no longer need it:
in.close();
}
rooms.push_back(Room());
int roomIndex = 0;
for(int i = 0; i < lines.size(); i++){
std::cout << lines.at(i) << std::endl;
if(lines.at(i).find("END_OF_ROOM") != std::string::npos){
if(i != lines.size()-1)
rooms.push_back(Room());
roomIndex++;
std::cout << "loaded room at iteration: " << i << std::endl;
}
else if(lines.at(i).find("Tiles:") != std::string::npos){
std::vector<int> tiles;
std::stringstream ss;
ss << lines.at(i);
std::string temp;
int found;
while(!ss.eof()){
ss >> temp;
if(std::stringstream(temp) >> found)
tiles.push_back(found);
temp = "";
}
int tIndex = 0;
for(int x = 0; x < 32; x++){
for(int y = 0; y < 18; y++){
rooms.at(roomIndex).setTile(x, y, tiles[tIndex]);
tIndex++;
}
}
}
else if(lines.at(i).find("ID:") != std::string::npos){
std::vector<int> itemInfo;
std::stringstream ss;
ss << lines.at(i);
std::string temp;
int found;
while(!ss.eof()){
ss >> temp;
if(std::stringstream(temp) >> found)
itemInfo.push_back(found);
temp = "";
}
Item I = *Materials::getItem(itemInfo[0]);
I.setPosition(sf::Vector2f(itemInfo[1], itemInfo[2]));
rooms.at(roomIndex).addItem(I);
std::cout << "added item at iteration: " << i << std::endl;
}
}
return true;
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:32:26.100",
"Id": "419117",
"Score": "0",
"body": "I would use a common serialization convention like YAML or JSON. Then you don't need to worry about the serialization and deserialization so much as this can be done via a standard library."
}
] | [
{
"body": "<p>You have not provided full details, so let me go on partly guessing here. First, here's a few suggestions that you can likely do immediately.</p>\n\n<ul>\n<li><p>Both methods return a boolean, but it's always <code>true</code>. What's even worse, it seems that <code>loadRooms()</code> return true even if you were unable to open the stream! Probably you intended to return <code>false</code> in both cases in case of any I/O failures.</p></li>\n<li><p>You can avoid human errors by using proper constants. Don't use magic numbers 32 and 18, but rather make them constants like <code>const int ROOM_WIDTH</code> and <code>const int ROOM_HEIGHT</code> at a suitable place.</p></li>\n<li><p>Because <code>itemID</code>, <code>xPos</code> and <code>yPos</code> can be <code>const</code>, make them such. This helps the reader see that the variables won't change later on, reducing mental effort.</p></li>\n<li><p>In <code>saveRooms()</code>, you might only want to retrieve <code>rooms.at(i).items.at(j).GetPosition()</code>, and then print out <code>x</code> and <code>y</code> to avoid making two function calls to the getter.</p></li>\n<li><p>In both methods, you have hard-coded the name of the file resource. Why? Instead, consider taking that as an input to the constructor to <code>RoomBuilder</code>, again reducing the chance of errors.</p></li>\n<li><p>In <code>loadRooms()</code>, you could first check if the stream is OK, and if not, then return false. Otherwise, you could apply <a href=\"https://www.bfilipek.com/2016/11/iife-for-complex-initialization.html\" rel=\"nofollow noreferrer\">IIFE</a> to initialize <code>const std::vector<std::string> lines</code> appropriately.</p></li>\n<li><p>I think <code>loadRooms()</code> is doing too much. Why not separate the logic of reading tiles into one and reading item information into another function? Those can be called from the method then.</p></li>\n<li><p>You are not really checking for whether the input is valid. As per your checks, it's fine as long as you find say \"ID:\" or \"Tiles:\" <em>anywhere</em> in the string. I would suggest using some well-known structured format like JSON for storing all this information.</p></li>\n<li><p>With <code>std::stringstream</code>, you can initialize the object with the correct string input, e.g., <code>std::stringstream ss(\"id 15 20\");</code> after which you can do say <code>ss >> id >> x >> y;</code>, where id is a string and x and y are ints.</p></li>\n<li><p>For checking streams, you can just invoke their <code>operator()</code>, i.e., you can do <code>if(ss) { ... }</code> or <code>if(in) { ... }</code>.</p></li>\n</ul>\n\n<p>In addition to these points, I would recommend you consider the following more breaking changes.</p>\n\n<ul>\n<li><p>Why is the responsibility of <code>RoomBuilder</code> to know how a specific room is saved to a file?</p></li>\n<li><p>The above should be the responsbility of every room: they know their details and how to draw itself. That way, the room builder could really just say \"for each room r, call r.draw()\" and that's it. In that way, rooms can easily be of different size, have different cool special effects, etc.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:33:30.217",
"Id": "216640",
"ParentId": "216606",
"Score": "2"
}
},
{
"body": "<p>Although most of the code is not shown, which makes the code much harder to review, by the way, here are some observations that may help you improve your code.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>saveRooms</code> member function of <code>RoomBuilder</code> does not appear to alter the underlying object and therefore should be declared <code>const</code>.</p>\n\n<pre><code>bool RoomBuilder::saveRooms() const {\n // code here\n}\n</code></pre>\n\n<h2>Don't hardcode file names</h2>\n\n<p>In maintaining this code later, the name of the output file might be something that could be placed elsewhere. Right now, it appears to have a Windows-centric name but if you wanted to port this to Mac or Linux, it would probably be better to pick out the file name as a named compile-time constant like this:</p>\n\n<pre><code>constexpr const char *roomFileName{\"DefaultMapRoomBuilder.klvl\"};\n</code></pre>\n\n<p>That way both the <code>loadRooms</code> and <code>saveRooms</code> could refer to exactly the same file without having to type the filename twice. Better might be to pass the file name as a parameter to both functions.</p>\n\n<h2>Don't write getters and setters for everything</h2>\n\n<p>There are a lot of functions like <code>Item::setPosition</code> and <code>Item::getPosition</code> that suggest you're attempting to write Java in C++. Don't do that. If other classes truly <em>require</em> unfettered access to the details of another class, just make it a <code>struct</code> and directly set and fetch the contents. </p>\n\n<h2>Use appropriate data structures</h2>\n\n<p>In the description of your code, you write that the rooms have a fixed number of tiles, but your code does not seem to reflect this directly, using a <code>std::vector</code> instead of a <code>std::array</code>. If you're relying on a fixed size (as the code appears to do) then use a fixed size data structure as well. If not, then the code would need to be altered to somehow account for variable sized data. </p>\n\n<h2>Rethink item numbering</h2>\n\n<p>The current code contains these lines:</p>\n\n<pre><code>int tIndex = 0;\nfor(int x = 0; x < 32; x++){\n for(int y = 0; y < 18; y++){\n rooms.at(roomIndex).setTile(x, y, tiles[tIndex]);\n tIndex++;\n }\n}\n</code></pre>\n\n<p>This probably works just fine for you, but the usual order of storing this is the other way around. That is, the <em>inner</em> loop would more typically be the <code>x</code> loop.</p>\n\n<h2>Use standard library functions</h2>\n\n<p>Here's how I would write <code>saveRooms</code>:</p>\n\n<pre><code>bool RoomBuilder::saveRooms() const {\n std::ofstream out{roomFileName};\n std::copy(rooms.begin(), rooms.end(), std::ostream_iterator<Room>(out, \"\\n\"));\n return static_cast<bool>(out);\n}\n</code></pre>\n\n<p>There's a lot going on here in just a few lines. First note that I'm using the C++11 <a href=\"http://www.stroustrup.com/C++11FAQ.html#uniform-init\" rel=\"nofollow noreferrer\">uniform initialization syntax</a> to initialize the variable. </p>\n\n<p>The last line takes advantage of the fact that <code>std::ofstream</code> has an <code>explicit operator bool()</code> that returns the state of the stream. (Some people would write <code>return !!out;</code> but I think my version is more clear in intent.) </p>\n\n<p>The <code>std::copy</code> is an elegant function that allow you to use an already defined extractor for <code>Room</code>. Here's one way to write that as a <code>friend</code> function of <code>Room</code>:</p>\n\n<pre><code>friend std::ostream& operator<<(std::ostream& out, const Room& r) {\n out << \"Tiles: \";\n std::copy(r.tile.begin(), r.tile.end(), std::ostream_iterator<int>(out, \" \"));\n out << '\\n';\n std::copy(r.items.begin(), r.items.end(), std::ostream_iterator<Item>(out, \"\\n\"));\n return out << \"END_OF_ROOM\";\n}\n</code></pre>\n\n<p>This, in turn, relies on a similar function for <code>Item</code>:</p>\n\n<pre><code>friend std::ostream& operator<<(std::ostream& out, const Item& item) {\n return out << \"Items: \\nID: \" << item.id << \" \" << item.pos.x << \" \" << item.pos.y;\n}\n</code></pre>\n\n<p>I have exactly reproduced the behavior of the original in which the \"Items:\" line is repeated for each item. If this were my code, I'd probably either change that to only write it once, or eliminate it entirely, since the \"ID:\" string is enough to uniquely identify the item in this context.</p>\n\n<h2>Rethink the interface</h2>\n\n<p>In the same logic as the rewritten function above, in reality, I probably wouldn't have <code>loadRooms</code> and <code>saveRooms</code> functions, but instead define <code>ostream</code> and <code>istream</code> functions like the ones described above for <code>Item</code> and <code>Room</code>.</p>\n\n<h2>Do more error handing</h2>\n\n<p>If the input file is malformed, there is very little error checking in the existing code. I'd suggest instead that the code <code>throw</code> if an error is found in the formatting or contents of the input file.</p>\n\n<h2>Avoid pointless complexity</h2>\n\n<p>The use of <code>lines</code> in <code>loadRooms()</code> makes little sense and only contributes complexity to the code. One could much more simply read and process each line directly from the file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:31:33.227",
"Id": "419187",
"Score": "0",
"body": "Thanks a lot, this was very helpful. I scrapped the entire roombuilder class and named it's replacement WorldMap, i made ostream operators for Room, Item, and now Player. I changed the vector to a 2d array so i was able to scrap a ton of code related to room's neighbor rooms in game. I didn't know about std::copy before, it was helpful. I added the file name to WorldMap's constructor. I made a lot of stuff a constant global variable, and now changing the resolution works! Thats all i had time to do today but i spent all of it just refactoring my code instead of just slapping new features on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T11:13:11.940",
"Id": "419213",
"Score": "0",
"body": "I'm glad you found it useful. Some of my most productive days have been spent in just refactoring code. One thing that may help is to also have [automated unit tests](http://cppunit.sourceforge.net/doc/cvs/cppunit_cookbook.html). I find that having such tests helps me refactor code with confidence and efficiency."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:46:18.967",
"Id": "216659",
"ParentId": "216606",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216659",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T21:51:22.930",
"Id": "216606",
"Score": "6",
"Tags": [
"c++",
"parsing"
],
"Title": "C++ Saving And Loading Data For A Game To a Text File Using fstream"
} | 216606 |
<p>I have written this code to simulate <a href="https://en.wikipedia.org/wiki/Ising_model" rel="noreferrer">Ising Model</a> at one particular temperature in presence of magnetic field to observe <a href="https://en.wikipedia.org/wiki/Hysteresis" rel="noreferrer">hysteresis effect</a> using the metropolis algorithm.</p>
<p>While the code runs and gave me a desired output, it is a badly written code(I feel so) because of my lack of coding experience. Could you help me out as to how could I have written this in a better way? Or what can I do to optimize it next time I write such a code? Or are there any inbuilt functions I could have called instead of writing a block?</p>
<p>I borrowed the random number generator directly from someone's answer to a thread on this site. I cannot find the exact thread, apologies! (I will cite it once I do).</p>
<p>Function to assign random spins to the lattice</p>
<pre><code>int spin(int r)
{
int s;
if(r>5)
{
s=+1;
}
else
{
s=-1;
}
return s;
}
</code></pre>
<p>Random number generator</p>
<pre><code>float prandom(int i,int N)
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_real_distribution<> dis(i,N);
// Use dis to transform the random unsigned int generated by gen into a
// double in [1, 2). Each call to dis(gen) generates a new random double
int t = dis(gen);
return t;
}
</code></pre>
<p>Function to randomly flip the spins</p>
<p>I am selecting a random site and seeing how the total energy will change by calculating the energy dE for the neighbouring sites. If the energy is negative then I make the spin flip permanent if it is not negative then I gave a probability exp(-dE) by which it can flip the spin</p>
<pre><code>std::vector< std::vector < int > > flip (int N,std::vector< std::vector < int > >lattice, float beta,int tab[],float H)
{
int a =prandom(0,N);
int b =prandom(0,N);
int s=lattice[a][b];
float dE=(2*s*H)+(2*s*(lattice[tab[a+2]][b]+lattice[tab[a]][b]+lattice[a][tab[b+2]]+lattice[a][tab[b]]));
//std::cout<<dE<<"\t"<<a<<"\t"<<b<<"\n";
if(dE<0)
{
s=-1*s;
}
else
{
float k = 1.0*prandom(0.0,1000)/1000;
float H = exp(-beta*dE);
if(k<=H)
{
s=-1*s;
}
else
{
s = 1*s;
}
}
lattice[a][b]=s;
return lattice;
}
</code></pre>
<p>Main program</p>
<pre><code>int main()
{
std::ofstream outdata;
outdata.open("ising_model_field_final2.txt");
int a,b,N=20,i,j,k,r,t,sweep=1500;
float M=0,M_sweep=0,H=-0.10;
int tab[N];
tab[0] = N-1;
tab[N+1] = 0;
for (i=1;i<=N;i++)
{
tab[i]=i-1; // this is the periodic boundary condition to make my lattice infinite (lattice site [x][0] is a neighbour of [x][N] and so on..)
}
float T, beta;
//beta=1.0/T; // boltzman constant is assumed to be 1.
//creating a 2d lattice and populating it
std::vector< std::vector < int > >lattice;
//populate the lattice
for (i=0; i<N; i++)
{
std::vector< int > row; //create a row of the lattice
for (j=0;j<N;j++)
{
row.push_back(-1); //populate the row vector
}
lattice.push_back(row); //populate the column vector
}
lattice=flip(N,lattice,beta, tab,H);
/* for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
std::cout<<lattice[j][i]<<"\t";
}
std::cout<<std::endl;
}*/
for(int temp=1;temp<=30;temp++)
{
if(temp>15)
{
H=H-0.015;
}
else
{
H=H+0.015;
}
//M=0;
T=2.2;
beta=1.0/T;
std::cout<<beta<<"\n";
for(i=0;i<=sweep;i++)
{
//T=0.1*i;
//printf("Sweep = %d\n",i);
for(j=1;j<=N*N;j++)
{
lattice=flip(N,lattice,beta, tab,H);
}
M_sweep=0;
for(t=0;t<N;t++)
{
for(int u=0;u<N;u++)
{
if(i>=500)
{M_sweep=M_sweep+lattice[t][u];}
}
//std::cout<<"Mag="<<M<<"\t";
}
M=M+ M_sweep/(N*N);
//std::cout<<"Mag="<<M<<"\t";
}
M=M/(sweep-1000);
std::cout<<T<<"\n";
outdata << M <<"\t"<< H <<"\n";
}
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
std::cout<<lattice[j][i]<<"\t";
}
std::cout<<std::endl;
}
outdata.close();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T07:42:29.120",
"Id": "419038",
"Score": "4",
"body": "I was trying to see how you were using that `spin()` function, but apparently you aren't. I'd say the first thing to start with is not asking people to review dead code. :)"
}
] | [
{
"body": "<p>There are many, <em>many</em> things wrong with your code; I'll list some, and then I advise you to fix as many of them as you can (and more) and then repost a new question with the revised code.</p>\n\n<p>First of all, you should compile your code with <code>-W -Wall -Wextra</code> (or <code>-W4</code> if you use MSVC). Read the first warning diagnostic. Fix it. Recompile. Read the first diagnostic. Fix it. ...until all the warnings are completely gone.</p>\n\n<p>Procedural nit: When you post code to CodeReview, please post it in one big cut-and-pasteable chunk, or at least just a couple of chunks. Your current post mixes code and commentary in a way that makes it hard for the reviewer to cut-and-paste the whole piece of code into a file for testing.</p>\n\n<hr>\n\n<p>Speaking of commentary:</p>\n\n<pre><code> float T, beta;\n //beta=1.0/T; // boltzman constant is assumed to be 1.\n //creating a 2d lattice and populating it\n std::vector< std::vector < int > >lattice;\n</code></pre>\n\n<p>Is <code>beta</code> supposed to be <code>1.0 / T</code>, or not? By commenting out that line of code, you make it invisible to the compiler. Better make it invisible to the <em>reader</em>, too, and just delete it! (If you're commenting things out to preserve the \"history\" of the code, read up on version control systems like <code>git</code>, and then use one. It's easy!)</p>\n\n<p>Furthermore, since you don't initialize <code>beta</code>, you can probably just get rid of the variable entirely.</p>\n\n<p>Finally, the idiomatic way to place the whitespace when you're defining a variable of type <code>std::vector<std::vector<int>></code> is simply thus:</p>\n\n<pre><code>std::vector<std::vector<int>> lattice;\n</code></pre>\n\n<p>Notice the space between the variable's type and its name; and the lack of space anywhere else.</p>\n\n<hr>\n\n<p>Populating that lattice can be done quickly and easily using <a href=\"https://en.cppreference.com/w/cpp/container/vector/vector\" rel=\"noreferrer\"><code>vector</code>'s \"filling\" constructor</a>:</p>\n\n<pre><code>std::vector<std::vector<int>> lattice(N, std::vector<int>(N, -1));\n</code></pre>\n\n<p>Now you don't need those nested <code>for</code> loops anymore!</p>\n\n<hr>\n\n<p>Going back up to the top of your code:</p>\n\n<pre><code>int spin(int r) \n{\n int s;\n if(r>5)\n {\n s=+1;\n }\n else\n {\n s=-1;\n }\n\n return s;\n}\n</code></pre>\n\n<p>Replace this 14-line function with a 4-line function that does the same thing more clearly and simply:</p>\n\n<pre><code>int spin(int r)\n{\n return (r > 5) ? 1 : -1;\n}\n</code></pre>\n\n<p>No local variables, no mutation, no startling use of the <code>=+</code> \"operator\"; and perhaps most importantly for the reader, there's now 10 more lines available on my screen so I can look at <em>other</em> code at the same time! Vertical real estate can be important for reading comprehension.</p>\n\n<hr>\n\n<pre><code>float prandom(int i,int N)\n{\n std::random_device rd; //Will be used to obtain a seed for the random number engine\n std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\n std::uniform_real_distribution<> dis(i,N);\n // Use dis to transform the random unsigned int generated by gen into a \n // double in [1, 2). Each call to dis(gen) generates a new random double\n int t = dis(gen);\n return t;\n}\n</code></pre>\n\n<p>This is wrong in at least two ways. First, most importantly: you're constructing a <code>std::random_device</code> on <em>each call to this function.</em> That is extremely expensive. Think of <code>std::random_device</code> as an open file handle to <code>/dev/urandom</code>, because that's what it is, under the hood. That means every time you call <code>prandom</code>, you're opening a file, reading some bytes, and closing it again!</p>\n\n<p>You should keep a <em>global</em> random number generator, initialized just once at the start of the program. One way to do this (not cheap, but not as expensive as opening a file on every call to <code>prandom</code>) would be</p>\n\n<pre><code>float prandom(int i,int N)\n{\n static std::mt19937 gen = []() {\n std::random_device rd;\n return std::mt19937(rd());\n }();\n std::uniform_real_distribution<float> dis(i, N);\n // ...\n</code></pre>\n\n<p>Notice that <code>uniform_real_distribution<></code> is secretly an alias for <code>uniform_real_distribution<double></code>. Your code doesn't use <code>double</code>s; it uses <code>float</code>s. So it's (always) better to be explicit and say what type you mean — you have less chance of getting it wrong by accident!</p>\n\n<pre><code> int t = dis(gen);\n return t;\n</code></pre>\n\n<p>...And then you go ahead and stuff the return value into an <code>int</code> anyway! So what was the point of using a <code>uniform_real_distribution</code> in the first place? And what's the point of returning a <code>float</code> from <code>prandom</code>? Did you mean to simply</p>\n\n<pre><code>return dis(gen);\n</code></pre>\n\n<p>instead?</p>\n\n<p>You're also <a href=\"http://www.pcg-random.org/posts/cpp-seeding-surprises.html\" rel=\"noreferrer\">seeding your PRNG wrong</a>, but seeding it correctly is a huge headache in C++17, so never mind that.</p>\n\n<hr>\n\n<pre><code> if(temp>15)\n {\n H=H-0.015;\n }\n</code></pre>\n\n<p>Please indent your code correctly. You can use the <code>clang-format</code> command-line tool to automatically indent everything, or if you use a graphical IDE it almost certainly has an \"Indent\" option somewhere in the menus.</p>\n\n<hr>\n\n<p>That's enough for one day. As I said above, I advise you to fix as much as possible (that is, fix <em>everything</em> I talked about here, and then fix everything else you can think of, too) and then repost.</p>\n\n<p>After you fix everything, but before you repost, <em>read your code from top to bottom one more time!</em> Find two more things that need fixing, and fix them. <em>Then</em> repost.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:11:28.543",
"Id": "216616",
"ParentId": "216607",
"Score": "15"
}
},
{
"body": "<p>I'll build off of Quuxplusone's answer.</p>\n\n<hr>\n\n<p>You have issues with <code>tab</code>.</p>\n\n<pre><code>int tab[N];\ntab[0] = N-1;\ntab[N+1] = 0; // out of bounds\n</code></pre>\n\n<p>Only the elements <code>0</code> through <code>N-1</code> are available, so this assignment is wrong. Your initialization loop also attempts to initialize <code>tab[N]</code>. And in <code>flip</code>, since <code>a</code> and <code>b</code> are randomly generated between <code>0</code> and <code>N-1</code>, getting <code>tab[a+2]</code> can be <code>N+1</code> at maximum, also out of bounds.</p>\n\n<p>While many compilers will accept it, you're not allowed to create an array with a non-const int. However, all these issues can be fixed pretty easily; just create it with a bit of extra room.</p>\n\n<pre><code>const int N = 20; // set to const\nint tab[N+2];\n</code></pre>\n\n<p>As a side note, I would personally not use <code>tab</code> at all! I would simply do the wraparound logic within <code>flip()</code>:</p>\n\n<pre><code>int val1 = lattice[a > 0 ? a-1 : N-1][b];\nint val2 = lattice[a < N-1 ? a+1 : 0][b];\nint val3 = lattice[a][b > 0 ? b-1 : N-1];\nint val4 = lattice[a][b < N-1 ? b+1 : 0];\n</code></pre>\n\n<p>That way, you don't have to worry about creating it or passing it as a parameter at all. </p>\n\n<hr>\n\n<p>Your <code>flip</code> function needlessly copies <code>lattice</code> each call. You should pass it as a reference.</p>\n\n<pre><code>void flip (int N, std::vector<std::vector<int>>& lattice, float beta, int tab[], float H)\n // ^\n{\n ...\n return;\n}\n\n</code></pre>\n\n<p>I've also made the function return <code>void</code> since you don't need to reassign <code>lattice</code> since its passed by reference and just call it like so:</p>\n\n<pre><code>flip(N, lattice, beta, tab, H);\n</code></pre>\n\n<hr>\n\n<p>Make a separate function like <code>print_lattice</code>. It makes it clear whats happening without even looking at it and you can use it in multiple places (like the one you've commented out).</p>\n\n<hr>\n\n<p>Don't declare your loop variables outside the loop (unless you need to). And get rid of any unused variables.</p>\n\n<p><code>int</code><strike>a,b,</strike><code>N=20,</code><strike>i,j,k,r,t,</strike><code>sweep=1500;</code></p>\n\n<hr>\n\n<p>Use better variable names. Consider using <code>x</code> and <code>y</code> instead of <code>a</code> and <code>b</code> since they'd be more immediately understandable. And give a more descriptive name to <code>H</code> and <code>M</code>, I'm not familiar with the algorithm and these names don't help much.</p>\n\n<hr>\n\n<pre><code>for(int u=0;u<N;u++)\n{\n if(i>=500)\n {M_sweep=M_sweep+lattice[t][u];}\n}\n</code></pre>\n\n<p>This loop checks for <code>i</code> but never modifies it, this check can be moved outside the loop like so:</p>\n\n<pre><code>if (i >= 500)\n{\n for(int u=0;u<N;u++)\n {\n M_sweep = M_sweep + lattice[t][u];\n }\n}\n</code></pre>\n\n<p>On second look, it can moved even higher to outside the <code>t</code> loop.</p>\n\n<hr>\n\n<p>You use lots of constants:</p>\n\n<pre><code>H=H+0.015;\n...\nT=2.2;\n</code></pre>\n\n<p>Consider giving these constants names.</p>\n\n<pre><code>const float H_STEP = 0.015f;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:16:34.713",
"Id": "216620",
"ParentId": "216607",
"Score": "10"
}
},
{
"body": "<p>Building on the answers of Quuxplusone and kmdreko, here's a few more issues I noticed. I'll start with a couple of serious ones, before moving on to stylistic issues and potential optimizations:</p>\n\n<h3>Dead code</h3>\n\n<p>The only thing seriously wrong with your <code>spin()</code> function is that you never call it. It's generally not very useful to ask people to review code you're not using.</p>\n\n<p>(The other, minor thing wrong with it is that it seems to be written with the assumption that the input is a random integer from 1 to 10. Or maybe it's meant to be from 0 to 9, in which case the <code>r > 5</code> should be <code>r >= 5</code>? But either way is needlessly complicated: since you're only using the input value to make a binary choice, just have it be 0 or 1. Or you could have the input be a float between 0.0 and 1.0, if you'd like to have the ability to bias the initial magnetization state. But of course, none of that makes any difference if you don't actually <em>use</em> the function.)</p>\n\n<h3>Use of uninitialized variables</h3>\n\n<p>On line 29 of your main function (10 lines below <code>//populate the lattice</code>), you're calling <code>flip()</code> and passing <code>beta</code> as an argument to it. But <code>beta</code> has not been initialized at that point, since you've commented out the line that would do it!</p>\n\n<p><a href=\"https://en.cppreference.com/book/uninitialized\" rel=\"noreferrer\">That's a bad thing, and you shouldn't do it.</a> Not only can the value passed to <code>flip()</code> be anything (and possibly vary between runs), leading to unpredictable results, but using the value of an uninitialized variable <a href=\"https://en.cppreference.com/w/cpp/language/ub\" rel=\"noreferrer\">makes the behavior of your program formally undefined</a>, which means that the compiler is allowed to make it do <em>anything</em>, up to and including <a href=\"http://catb.org/jargon/html/N/nasal-demons.html\" rel=\"noreferrer\">making demons fly out of your nose</a> when you run it. A slightly more likely (but still protentially catastrophic) result is that the compiler might simply decide to <a href=\"https://kukuruku.co/post/undefined-behavior-and-fermats-last-theorem/\" rel=\"noreferrer\">optimize out your entire main function</a>, since it can prove that there are no code paths through it that don't have undefined behavior!</p>\n\n<p>(Of course, the out-of-bounds array access pointed out by kmdreko also leads to undefined behavior, so just setting an initial value for <code>beta</code> isn't enough to fix your code.)</p>\n\n<h3>Confusing variable naming</h3>\n\n<p>In <code>flip()</code>, you use <code>H</code> both as an argument to the function and as the name of a local variable. While that's technically allowed, it's very confusing to read. Rename one of them.</p>\n\n<p>Also, your use of <code>temp</code> as the name of a <em>temp</em>orary(?) variable in the main function is potentially confusing too, given that the surrounding code deals with (thermodynamic) <em>temp</em>eratures. For that matter, <code>temp</code> isn't a particularly informative or appropriate variable name anyway. If you really can't think of a good name for a variable, <a href=\"https://en.wikipedia.org/wiki/Metasyntactic_variable\" rel=\"noreferrer\">call it <code>foo</code> or something</a> so that readers can at least tell at a glance that the name means nothing. But in this case, something like <code>iteration</code> would be a decently meaningful name.</p>\n\n<h3>Optimization opportunities</h3>\n\n<p>First of all, note that your code spends almost all of its time calling <code>flip()</code> repeatedly, so making that function run fast should be your first optimization priority.</p>\n\n<p>Getting rid of the indirect indexing via the <code>tab</code> array, as suggested by kmdreko, is a good start. In the same vein, you might want to turn <code>lattice</code> from a vector of vectors into a <a href=\"https://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c/4810676#4810676\">proper two-dimensional array</a>, which will eliminated another layer of indirection.</p>\n\n<p>(The down side of using two-dimensional arrays is that you'll have to know the dimensions at compile time, but in your code that's the case anyway. If you want to allow the size of the lattice to be specified at runtime, one option is to dynamically allocate a <em>one-dimensional</em> array of the appropriate size and <a href=\"http://www.cplusplus.com/doc/tutorial/arrays/#multidimensional\" rel=\"noreferrer\">treat it as a pseudo-multidimensional array</a> by indexing it e.g. as <code>lattice[a*N + b]</code> instead of <code>lattice[a][b]</code>.)</p>\n\n<p>You can also trivially save some memory by using <code>signed char</code> instead of <code>int</code> as the type of the <code>lattice</code> elements. You might even want to consider using <a href=\"https://en.cppreference.com/w/cpp/utility/bitset\" rel=\"noreferrer\">std::bitset</a> (or implementing your own bit-packed lattice representation) to save even more memory, but this would require you to represent your lattice spin states as 0 and 1 instead of -1 and +1 (which in itself is not necessarily a bad idea at all), and likely comes at the cost of some minor speed reduction and added code complexity. For relatively small values of <code>N</code>, it's probably not worth it.</p>\n\n<hr>\n\n<p>Also, calculating <code>exp(-beta*dE)</code> inside <code>flip()</code> looks like it could potentially be <a href=\"http://www.latkin.org/blog/2014/11/09/a-simple-benchmark-of-various-math-operations/\" rel=\"noreferrer\">somewhat slow</a> (although, of course, you really ought to profile the code first before spending too much effort on such optimizations). It would be nice to move the exponential calculation out of the inner loop, if we can. Can we?</p>\n\n<p>Expanding the definition of <code>dE</code> earlier in the code (and using the definitions of the neighbor site values <code>val1</code> to <code>val4</code> from kmdreko's answer), the argument to <code>exp()</code> is <code>-beta * 2 * s * (H + val1 + val2 + val3 + val4)</code>. Here, <code>beta</code> and <code>H</code> do not change within the inner loop, while <code>s</code> and <code>val1</code> to <code>val4</code> are always either +1 or -1.</p>\n\n<p>The addition of the external field parameter <code>H</code> to the summed spin of the neighbors makes things a bit more complicated, but we can deal with it by distributing the common <code>-beta * 2 * s</code> term over the sum, giving <code>-beta*2*s*H - beta*2*s*val1 - beta*2*s*val2 - beta*2*s*val3 - beta*2*s*val4</code>. Now, depending on the signs of <code>s</code> and <code>val1</code>...<code>val4</code>, each of these terms can only take one of two values: ±<code>beta*2*H</code> for the first term, and ±<code>beta*2</code> for the others. If we precalculate the exponentials of each of these values outside the <code>flip()</code> function (and the inner loop that calls it), we can calculate <code>exp(-beta*dE)</code> simply by multiplying these precalculated terms together, e.g. like this:</p>\n\n<pre><code>void flip (float exp_2_beta, float exp_m2_beta, float exp_2_beta_H, float exp_m2_beta_H)\n{\n int a = (int)prandom(0, N);\n int b = (int)prandom(0, N);\n int s = lattice[a][b];\n\n // calculate exp(-beta * 2 * s * (H + sum(neighbors))) based on precalculated\n // values of exp(2*beta), exp(-2*beta), exp(2*beta*H) and exp(-2*beta*H):\n float prob = (s != 1 ? exp_2_beta_H : exp_m2_beta_H);\n prob *= (lattice[a > 0 ? a-1 : N-1][b] != s ? exp_2_beta : exp_m2_beta);\n prob *= (lattice[a < N-1 ? a+1 : 0][b] != s ? exp_2_beta : exp_m2_beta);\n prob *= (lattice[a][b > 0 ? b-1 : N-1] != s ? exp_2_beta : exp_m2_beta);\n prob *= (lattice[a][b < N-1 ? b+1 : 0] != s ? exp_2_beta : exp_m2_beta);\n\n // flip spin of this site with probability min(prob, 1.0)\n if (prob >= 1 || prob >= prandom(0, 1))\n {\n lattice[a][b] = -s;\n }\n}\n</code></pre>\n\n<p>This makes use of <a href=\"https://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"noreferrer\">short-circuit evaluation</a> to avoid calling <code>prandom(0, 1)</code> when it's not needed. Rewriting the code like this also avoids making an unnecessary write to <code>lattice[a][b]</code> if the spin doesn't change. (Also, I'm assuming that <code>N</code> and <code>lattice</code> are global constants, since there's really no good reason for them not to be, and that you've fixed <code>prandom()</code> to actually return a float.)</p>\n\n<p>Now, passing all these precalculated factors as parameters to <code>flip()</code> may feel a bit ugly, since they're really just an internal optimization detail. Fortunately, there's a simple fix to that: just move the inner loop (and the precalculation of those values) <em>into</em> the function, e.g. like this:</p>\n\n<pre><code>void do_flips (int count, float beta, float H)\n{\n // precalculate some useful exponential terms\n float exp_2_beta = exp(2 * beta), exp_m2_beta = exp(-2 * beta);\n float exp_2_beta_H = exp(2 * beta * H), exp_m2_beta_H = exp(-2 * beta * H);\n\n // do up to (count) spin flips\n for (int i = 0; i < count; i++) {\n int a = (int)prandom(0, N);\n int b = (int)prandom(0, N);\n int s = lattice[a][b];\n\n // calculate prob = exp(-beta * 2 * s * (H + sum(neighbors)))\n float prob = (s != 1 ? exp_2_beta_H : exp_m2_beta_H);\n prob *= (lattice[a > 0 ? a-1 : N-1][b] != s ? exp_2_beta : exp_m2_beta);\n prob *= (lattice[a < N-1 ? a+1 : 0][b] != s ? exp_2_beta : exp_m2_beta);\n prob *= (lattice[a][b > 0 ? b-1 : N-1] != s ? exp_2_beta : exp_m2_beta);\n prob *= (lattice[a][b < N-1 ? b+1 : 0] != s ? exp_2_beta : exp_m2_beta);\n\n // flip spin of this site with probability min(prob, 1.0)\n if (prob >= 1 || prob >= prandom(0, 1))\n {\n lattice[a][b] = -s;\n }\n }\n}\n</code></pre>\n\n<p>Finally, instead of \"sweeping\" the lattice periodically to calculate its overall magnetization state, it may be more efficient to just keep track of the sum of the spin states as you update them. For example, you could take the code above and replace the last <code>if</code> statement with:</p>\n\n<pre><code> // flip spin of this site with probability min(prob, 1.0)\n if (prob >= 1 || prob >= prandom(0, 1))\n {\n lattice[a][b] = -s;\n lattice_sum += -2*s; // keep track of the sum of all the spins\n }\n</code></pre>\n\n<p>where <code>lattice_sum</code> is either a global — or, better yet, a local copy of a global variable — or passed into the function as a parameter and returned from it at the end.</p>\n\n<p>Whether such real-time tracking of the total magnetization is faster or slower than periodic sweeping depends on how often you want to sample the magnetization state. With one sample per transition per lattice site, as your current code effectively does, I'd expect the real-time tracking to be somewhat faster, if only because it has better cache locality. Especially so if you make <code>lattice_sum</code> a local variable in <code>do_flips()</code>, which ensures that the compiler will know that it can't be <a href=\"https://stackoverflow.com/questions/9709261/what-is-aliasing-and-how-does-it-affect-performance\">aliased</a> and can be safely stored in a CPU register during the loop.</p>\n\n<p>(Also, the way you're updating the time-averaged magnetization state <code>M</code> looks wonky, and I'm pretty sure you have a bug in it. To test this, try fixing <code>M_sweep</code> to a non-zero constant value and see if <code>M</code> correctly evaluates to <code>M_sweep/(N*N)</code>. The way your code is currently written, it doesn't look like it will. Maybe you changed one of your \"magic numbers\" from 1000 to 500 — or vice versa — and forgot to update the other? One more reason to prefer named constants...)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:40:30.667",
"Id": "419077",
"Score": "1",
"body": "There's a lot of variables you can also make `const` in these examples. This improves readability, reduces the chance of unintended errors, and reduces the mental effort to understand what is going on."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:18:50.307",
"Id": "216652",
"ParentId": "216607",
"Score": "5"
}
},
{
"body": "<p>One thing to do, is to create a lookup table for the float H = exp(-beta*dE) . As your change in energy can only take 4 different values, it is more efficient to store the result of the above exponential for each of those 4 values, and then access it via an index instead of calculating it everytime. (You will actually only need 2 of those values.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:47:54.733",
"Id": "419120",
"Score": "1",
"body": "Actually, if `H` (the parameter, not the local variable of the same name!) is not an integer, `dE` can take up to 10 different values depending on the spin of the chosen site (2 possibilities) and the sum of the spins of its neighbors (5 possibilities). But yes, precalculating a look-up table of all those values is a possible optimization, and worth at least benchmarking against my suggestion of factoring the expression."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:14:48.113",
"Id": "419228",
"Score": "0",
"body": "You're right, I was thinking of the zero field model."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T15:12:49.247",
"Id": "216660",
"ParentId": "216607",
"Score": "2"
}
},
{
"body": "<pre><code>float prandom(int i,int N)\n{\n std::random_device rd; //Will be used to obtain a seed for the random number engine\n std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()\n std::uniform_real_distribution<> dis(i,N);\n // Use dis to transform the random unsigned int generated by gen into a \n // double in [1, 2). Each call to dis(gen) generates a new random double\n int t = dis(gen);\n return t;\n}\n</code></pre>\n\n<p>As noted by Quuxplusone you should store the mt19937 engine rather than reinstantiate it every time by taking data from <code>std::random_device</code>. You also have the issue that you are initialising a random number generator with a state size of 19937 bits with the <code>unsigned int</code> returned by <code>rd()</code> (likely to be 32 bits on most common architectures). This is clearly an insufficient amount of randomness. You should actually be using a <code>std::seed_seq</code> for this purpose.</p>\n\n<p><code>std::seed_seq::result_type</code> is <code>std::uint_least32_t</code>. Annoyingly the <code>std::random_device::result_type</code> is an alias of <code>unsigned int</code>, which could potentially be a 16-bit type, so this requires an intermediate distribution, otherwise we run the risk of having zero padding in the supplied integers.</p>\n\n<p>The next question is how many values we need: this can be calculated by multiplying the state size of the generator <code>std::mt19937::state_size</code> by the word size <code>std::mt19937::word_size</code> and dividing by 32. (For <code>std::mt19937</code> the word size is 32, so you'd be able to just use the state size, but if you decided to replace it with <code>std::mt19937_64</code> this would become relevant).</p>\n\n<p>Putting that all together gives something along the lines of:</p>\n\n<pre><code>std::mt19937 getengine()\n{\n std::random_device rd;\n\n // uniform int distribution to ensure we take 32-bit values from random_device\n // in the case that std::random_device::result_type is narrower than 32 bits\n std::uniform_int_distribution<std::uint_least32_t> seed_dist{ 0, 0xffffffffu };\n\n // create an array of enough 32-bit integers to initialise the generator state\n constexpr std::size_t seed_size = std::mt19937::state_size * std::mt19937::word_size / 32;\n std::array<std::uint_least32_t, seed_size> seed_data;\n std::generate_n(seed_data.data(), seed_data.size(), [&rd, &seed_dist]() { return seed_dist(rd); });\n\n // use the seed data to initialise the Mersenne Twister\n std::seed_seq seq(seed_data.begin(), seed_data.end());\n return std::mt19937{ seq };\n}\n</code></pre>\n\n<p>This should take enough data from <code>std::random_device</code> to seed the generator. Unfortunately there are implementations where <code>std::random_device</code> is deterministic (MinGW is the main culprit here) and there is no reliable way to detect this. The <code>entropy()</code> method on <code>std::random_device</code> should return zero for a deterministic implementation, unfortunately there are non-deterministic implementations that also return zero (e.g. LLVM libc++), which is rather unhelpful.</p>\n\n<p>There are also various subtle flaws in <code>std::seed_seq</code> to be aware of, see <a href=\"http://www.pcg-random.org/posts/cpp-seeding-surprises.html\" rel=\"nofollow noreferrer\">Melissa O'Neill's article on C++ Seeding Surprises</a> for details: basically it turns out that even using an (apparently) sufficient amount of data, there are still various states that cannot be output.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T18:31:45.387",
"Id": "216808",
"ParentId": "216607",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T22:25:44.610",
"Id": "216607",
"Score": "10",
"Tags": [
"c++",
"simulation",
"physics"
],
"Title": "Ising model simulation"
} | 216607 |
<p>I have been developing a cross-platform game based on open C libraries (mainly glfw) with a direct focus on Windows development. The beginning of my programming career taught me familiarity in Objective-C, however I've been using pure C for the past few years in embedded applications. </p>
<p>Now that I'm trying to return to proper desktop program development, I'm wondering if it's a good idea to transfer my Objective-C skills to Windows in order to tidy up my C code. My current way of programming is creating a struct for data that I need and then creating functions around those structs: <code>struct Point {int x, int y};</code> and then <code>float Point_calculateDistance(struct Point *obj1, struct Point *obj2)</code>. This approach to me seemed very redundant and too object-oriented to write all in C. It would make more sense to me to write an Objective-C class to do this where everything can be more encapsulated.</p>
<p>I prefer not to use any framework for my code to increase the portability. I'm currently using VS Code and MSYS2 (mingw64) with GCC 8.3.0. I threw together a working example that demonstrates how I attempt to build a simple class. Does my code look reasonable? Am I performing any bad habits (within reason considering that I'm not using a framework)? Does this currently leak memory? Let me know what you think.</p>
<pre><code>#include <objc/objc.h>
#include <objc/runtime.h>
#include <objc/Object.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
@interface Point : Object {
float x;
float y;
}
@property float x;
@property float y;
-(id)initWithX: (float)xval AndY: (float)yval;
-(float)calculateDistance: (Point *)other;
@end
@implementation Point
@synthesize x;
@synthesize y;
+(id)alloc {
id obj = malloc(class_getInstanceSize(self));
object_setClass(obj, self);
return obj;
}
-(void)dealloc {
free(self);
}
-(id)init {
x = 0.0;
y = 0.0;
return self;
}
-(id)initWithX: (float)xval AndY: (float)yval {
x = xval;
y = yval;
return self;
}
-(float)calculateDistance: (Point *)other {
return sqrt((x - other.x) * (x - other.x) + (y - other.y) * (y - other.y));
}
@end
int main(int argc, char **argv) {
Point *point1 = [[Point alloc] init];
Point *point2 = [[Point alloc] initWithX: 1.5 AndY: 1.5];
printf("Distance is %f.\n", [point1 calculateDistance: point2]);
[point1 dealloc];
[point2 dealloc];
return EXIT_SUCCESS;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:19:46.850",
"Id": "419007",
"Score": "0",
"body": "where is the [super init]?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:29:59.950",
"Id": "419010",
"Score": "0",
"body": "@E.Coms The base class `Object` only has the variable `isa` and the methods `class` and `isEqual:` so calling `[super init]` causes a seg. fault."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:31:22.720",
"Id": "419011",
"Score": "0",
"body": "I use Xcode and not familiar with Object. I use NSObject and found it runs well at least in grammar. Without super. it just looks missing Root Object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:34:25.590",
"Id": "419012",
"Score": "0",
"body": "@E.Coms NSObject is a piece of Foundation.h which is written by Apple. Finding a class that does something similar would require writing my own or using a framework like GNUStep, both of which are overkill for my uses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:40:28.230",
"Id": "419013",
"Score": "0",
"body": "how about subclass of Point, will you still miss `super`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:43:31.447",
"Id": "419014",
"Score": "0",
"body": "Not sure, depends on how much the memory the Objective-C runtime says it needs to allocate for `class_getInstanceSize(self)` for a subclass. If it only allocates enough memory for the parent class alone, I might need to think the structure out more."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:47:38.253",
"Id": "419015",
"Score": "0",
"body": "If it's a small game I think your current knowledges and skills is good enough. But if it's a large one, at least you may need to write some framework by yourself before moving on. OBJC is a real objctive-oriented, very flexible and a charming one in a middle-large size project. So if you plan to use it , you may consider if OBJC is matching your goals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:36:39.583",
"Id": "419024",
"Score": "0",
"body": "\"I prefer not to use any framework for my code to increase the portability.\" Why not just choose frameworks that support portability...?"
}
] | [
{
"body": "<p>It's an interesting idea to write Windows code in Objective-C. If you were using NeXTStep frameworks (or GNUStep) it would make a little more sense. I don't understand your desire to avoid frameworks, which tend to be force multipliers saving you time and effort. (And of course, you are using OpenGL and GLFW, so this seems like an arbitrary choice.) Regardless, given those constraints, here are my thoughts.</p>\n<h1>Language</h1>\n<p>In my opinion Objective-C is the wrong choice for this particular project. I say that as someone who makes a living programming largely in Objective-C. The problem, as I see it, is that you lose 2 important things that you would get from other languages:</p>\n<ol>\n<li>The ability to use objects or <code>structs</code> for doing your work and passing them directly to OpenGL/GLFW.</li>\n<li>The ability to use operator overloading.</li>\n</ol>\n<p>OpenGL expects to receive geometry as an array of vertex attributes (or several different arrays – one for each attribute). That's going to be impossible using the class as you've written it. Each Objective-C object is its own entity on the heap. If you have an array of them, it's really just an array of pointers to the objects, which may or may not be contiguous in memory. You won't be able to just call <a href=\"https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glVertexAttribPointer.xhtml\" rel=\"noreferrer\"><code>glVertexAttribPointer()</code></a> or other similar functions and pass a pointer to the array since the array will just be an array of other pointers. In C you'd have an array of <code>Point</code> <code>struct</code>s either on the stack or the heap and could just pass the address of the first element to the above function. Likewise with something like a C++ <code>std::vector<Point></code> you'd be able to pass the address of the first element (assuming <code>Point</code> had no v-table). In addition to making it harder to send the data to the GPU, it also makes processing the data on the CPU slower because you lose cache coherency when the data isn't contiguous.</p>\n<p>You'll also want to do math on your <code>Point</code> objects. While you can write methods on your Objective-C class to add, subtract, etc., it's not as natural as using a language that allows you to overload operators. In particular, C++ and Swift both allow this and it makes writing graphics code feel much more natural.</p>\n<h1>Class</h1>\n<p>This class is rather thin. It doesn't do very much that's useful. What it does do, it appears to do correctly. It might be useful to swap the <code>sqrt()</code> call with a call to <a href=\"https://en.wikipedia.org/wiki/Hypot\" rel=\"noreferrer\"><code>hypot(x,y)</code></a> instead.</p>\n<p>At a minimum, if you're doing 2D graphics, you'll probably want to add the following methods:</p>\n<pre><code>- (void)add:(Point*)p;\n- (void)subtract:(Point*)p;\n- (float)dotProduct:(Point*)p;\n- (void)normalize;\n- (void)multiplyScalar:(float)s;\n- (void)multiplyVector:(Point*)p;\n- (void)divideScalar:(float)s;\n- (void)divideVector:(Point*)p;\n</code></pre>\n<p>And eventually, you'll probably want a <code>Matrix</code> class for things like scaling and rotation operations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T01:02:34.893",
"Id": "419016",
"Score": "0",
"body": "Thank you for the comments, but perhaps I didn't make my intentions completely clear. I was really just using the `Point` example to demonstrate a functioning, compiling class more than something I would use to interact directly with OpenGL. If I were storing vertices, I would probably make a `Point_3D` struct with a `float x, y, z` and then perhaps implement it in an array as an instance variable of a larger object class (along with things like textures and shaders)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:49:06.343",
"Id": "216613",
"ParentId": "216611",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "216613",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-31T23:30:16.427",
"Id": "216611",
"Score": "5",
"Tags": [
"objective-c",
"windows"
],
"Title": "Point distance program written without a framework"
} | 216611 |
<p>I referred to the post <a href="https://codereview.stackexchange.com/questions/41930/simple-in-memory-database">here</a> but it does not address the question that I have with regards to my implementation. I have a C# implementation of an in-memory database that I came up with during a recent interview. I was told that my code was okay in terms of getting the job done but could be more efficient dealing with transactions. I am not sure how I could improve this. I would greatly appreciate any suggestions. </p>
<p>The database should support GET, SET, DELETE, COUNT as basic operations. END signifies that the user is not going to issue any more commands. Input is read from stdin.</p>
<p>eg. </p>
<pre><code>SET a 10
GET a //returns 10
COUNT a //returns 1
DELETE a
GET a //returns NULL
COUNT a //returns 0.
</code></pre>
<p>A transaction is the equivalent of the DB transactions and supports the above operations in an atomic manner. It is initiated by a BEGIN command, rollback means rolling back the active transaction, since nested transactions are supported, commit writes all open transactions to memory. A rollback or commit issued with no transactions open will result in a "NO TRANSACTIONS" being printed.</p>
<pre><code>BEGIN
SET a 10
GET a
BEGIN
SET a 20
GET a
ROLLBACK
GET a
ROLLBACK
GET a
END
</code></pre>
<p>Here are my classes:</p>
<pre><code>public class Operation
{
private readonly Dictionary<string, int> valueStore;
private readonly Dictionary<int, int> valueCount;
public Operation()
{
valueStore = new Dictionary<string, int>();
valueCount = new Dictionary<int, int>();
}
//Used for copying over old data for supporting transactions
public Operation(Operation operation)
{
valueStore = new Dictionary<string, int>(operation.valueStore);
valueCount = new Dictionary<int, int>(operation.valueCount);
}
//set a variable to a value in the datastore and update counts
internal void Set(string variable, int value)
{
if (!valueStore.ContainsKey(variable))
{
valueStore.Add(variable, value);
}
else
{
valueCount[valueStore[variable]] -= 1;
valueStore[variable] = value;
}
if (!valueCount.ContainsKey(value))
{
valueCount.Add(value, 1);
}
else
{
valueCount[value] += 1;
}
}
//Get value from datastore, return null if not present
internal void Get(string variable)
{
if (valueStore.ContainsKey(variable))
Console.WriteLine(valueStore[variable]);
else
Console.WriteLine("NULL");
}
//Get count from datastore, return 0 if not present
internal void Count(int value)
{
if (valueCount.ContainsKey(value))
Console.WriteLine(valueCount[value]);
else
Console.WriteLine("0");
}
//Delete value from data store and update count.
internal void Delete(string variable)
{
if (valueStore.ContainsKey(variable))
{
int value = valueStore[variable];
valueCount[value] -= 1;
valueStore.Remove(variable);
}
else
Console.WriteLine("Variable does not exist");
}
/*
* We need to override equals to compare two operations
* because when we have two begins, 1 commit followed by
* a rollback we should technically have no transactions
* to rollback, because the last committed and current
* transactions are both same
*/
public bool Equals(Operation other)
{
if (valueStore.Keys.Count == other.valueStore.Keys.Count)
{
foreach (string variable in valueStore.Keys)
{
if (other.valueStore.ContainsKey(variable)
&& other.valueStore[variable] == valueStore[variable])
continue;
else
return false;
}
}
else
return false;
return true;
}
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = hash * 31 + valueStore.GetHashCode();
hash = hash * 31 + valueCount.GetHashCode();
return hash;
}
}
}
public class Transaction
{
private readonly Stack<Operation> transactions;
public Transaction()
{
transactions = new Stack<Operation>();
}
internal Operation Begin(Operation operation)
{
transactions.Push(operation);
return new Operation(operation);
}
internal Operation Commit(Operation operation)
{
transactions.Clear();
transactions.Push(operation);
return new Operation(operation);
}
internal Operation Rollback(Operation operation)
{
if (transactions.Count != 0)
{
Operation lastCommitted = transactions.Pop();
if (lastCommitted.Equals(operation))
{
Console.WriteLine("NO TRANSACTION");
transactions.Push(lastCommitted);
}
return lastCommitted;
}
else
{
Console.WriteLine("NO TRANSACTION");
return operation;
}
}
}
public class Database
{
private Operation commands;
private Transaction transaction;
public Database()
{
commands = new Operation();
transaction = new Transaction();
}
public void HandleInput()
{
Console.WriteLine("Hello user, enter some commands");
string line = "";
while ((line = Console.ReadLine()) != null)
{
if (line == "END")
break;
else
{
HandleUserInput(line);
}
}
}
private void HandleUserInput(string inputLine)
{
/*
* Need to use exceptions for parsing and use try catch block for FormatException
* Assuming that input commands will be valid(eg. Get will have 2 params,
* Count will have 2 params etc.)
*/
string[] parameters = inputLine.Split(' ');
string op = parameters[0];
string variable;
int value;
switch (op.ToUpper())
{
case "GET":
variable = parameters[1];
commands.Get(variable);
break;
case "SET":
variable = parameters[1];
value = int.Parse(parameters[2]);
commands.Set(variable, value);
break;
case "DELETE":
variable = parameters[1];
commands.Delete(variable);
break;
case "COUNT":
value = int.Parse(parameters[1]);
commands.Count(value);
break;
case "BEGIN":
commands = transaction.Begin(commands);
break;
case "ROLLBACK":
commands = transaction.Rollback(commands);
break;
case "COMMIT":
commands = transaction.Commit(commands);
break;
default:
Console.WriteLine("Invalid operation: " + op + "\nTry again.");
break;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T10:19:13.800",
"Id": "419534",
"Score": "2",
"body": "Could you please explain what exactly COUNT is supposed to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T22:05:26.463",
"Id": "419926",
"Score": "0",
"body": "The number of items in the value store that currently have the same value as the input. For eg., if the value store has {{a -> 10}, {b ->10}}, then Count 10 gives 2."
}
] | [
{
"body": "<h3>Main problems</h3>\n\n<ul>\n<li>Several parts of the code interact directly with the console. This mixing of responsibilities results in code that's difficult to reuse and test.</li>\n<li>Copying all data when a transaction is started is an easy and quick way to implement transactions, but it's indeed not the most efficient approach, and doesn't allow for concurrent transactions. Instead, a transaction could keep track of performed operations, and only apply them to the underlying key-value store on commit. Querying performed within a transaction should check these pending modifications before looking at the parent transaction or the underlying data store.</li>\n<li>The class names are somewhat confusing:\n\n<ul>\n<li><code>Operation</code> sounds like it represents a single database operation. Instead, it's the actual key-value store, so I would rename this to <code>KeyValueStore</code>.</li>\n<li><code>Transaction</code> sounds like it represents a single transaction. Instead, it tracks multiple transactions, so I'd rename this to <code>TransactionManager</code>.</li>\n<li>I'd expect <code>Database</code> to provide a database or query API, but instead it handles user input directly.</li>\n</ul></li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li><code>Operation.Get</code> and <code>Operation.Count</code> are of little use if they don't return their results.</li>\n<li>Use <code>TryGetValue</code> instead of a <code>ContainsKey</code> call followed by an indexing operation. This gives you the information you need with just a single dictionary lookup.</li>\n<li>Why does <code>Operation</code> keep track of value counts? Was there a specific requirement that <code>COUNT</code> had to operate in <span class=\"math-container\">\\$O(1)\\$</span> time? If not, why not keep things simple and do a linear search? It's a trade-off, of course, but without a clear reason to do this I would favor the less complicated approach: more code usually means more bugs and more maintenance.</li>\n<li>I don't see why <code>Operation</code> needs to implement <code>Equals</code> and <code>GetHashCode</code>. It's a potentially expensive operation, and the only place where it's used (<code>Transaction.Rollback</code>) doesn't make sense: rolling back a transaction with no changes should not put that transaction back on the stack.</li>\n<li>The nesting in <code>Operation.Equals</code> can be reduced by using early-out returns: <code>if (Count != other.Count) return false; ...</code> instead of <code>if (Count == other.Count) { ... } else return false;</code>.</li>\n<li>I'd expect an empty operations stack to indicate that no transaction is active, but because <code>Commit</code> pushes an operation on the stack that's not always the case. Why would <code>Commit</code> need to do that? It already returns the current (committed) state.</li>\n<li>You may want to document (in the code) that <code>Commit</code> commits all transactions, while <code>Rollback</code> only rolls back the innermost transaction.</li>\n<li>By reading input directly in <code>Database</code>, your code cannot be reused in a different context (GUI, server-side, library). Move <code>HandleInput</code> to another place (<code>Program.Main</code> for example), rename <code>HandleUserInput</code> to <code>ExecuteQuery</code> and have that method return results instead of writing them to the console. Now you can reuse your database code elsewhere, and it's possible to write automated tests.</li>\n<li>Adding a few empty lines here and there would improve code readability: some whitespace between methods, and between unrelated if/else statements makes it easier to tell them apart.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T11:31:53.183",
"Id": "217196",
"ParentId": "216612",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T00:11:45.167",
"Id": "216612",
"Score": "5",
"Tags": [
"c#",
".net",
"interview-questions",
"reinventing-the-wheel"
],
"Title": "In-Memory database supporting transactions"
} | 216612 |
<p>I have created a program that calculates pi using a Monte Carlo method. It also animates the process and displays the value as it is updated to show how it gets closer and closer to the actual value as more time passes. It is made with HTML canvas. I would like some feedback on my program.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";
function hypot(a, b) {
return Math.sqrt(a * a + b * b);
}
function randInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min
}
class Circle {
constructor(x, y, r) {
this.x = x;
this.y = y;
this.r = r;
}
draw() {
ctx.strokeStyle = "#000";
ctx.lineWidth = "5px";
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
ctx.stroke();
}
collidePoint(pt) {
var dx = this.x - pt.x;
var dy = this.y - pt.y;
return hypot(dx, dy) <= this.r;
}
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
draw() {
ctx.fillStyle = "rgba(0, 0, 0, 16)";
ctx.fillRect(this.x, this.y, 1, 1);
}
}
const canvas = document.getElementById("disp");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var width = parseInt(canvas.width);
var height = parseInt(canvas.height);
var trys = 0;
var lands = 0;
var area = width * height;
var points = [];
var ball = new Circle(width / 2, height / 2, Math.min(width, height) / 2);
setInterval(step, 10);
function drawAll() {
ctx.clearRect(0, 0, width, height);
ball.draw();
points.forEach((point) => {
point.draw();
});
}
function step() {
drawAll();
var pnt = new Point(randInt(0, width), randInt(0, height));
trys++;
if (ball.collidePoint(pnt)) {
lands++;
}
var prob = lands / trys;
var pi = (prob * area) / Math.pow(ball.r, 2);
document.getElementById("out").innerText = pi.toString();
points.push(pnt);
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
height: 100%;
overflow: hidden;
}
#disp {
width: 100vw;
height: 100vh;
margin: 0;
}
#box {
position: absolute;
z-index: 1;
width: 200px;
height: 20px;
left: 5%;
top: 5%;
background-color: whitesmoke;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Monte Carlo Pi</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<canvas id="disp"></canvas>
<span id="box">Pi &#x2248; <span id="out"></span></span>
<script src="script.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>The jungle</h2>\n<p>OO design tends to create unneeded eco systems when the focus is the objects not the task at hand.</p>\n<p>In this case <code>Point</code>, <code>Circle</code>, <code>points</code> and supporting functions have nothing to do with the problem. They exist to serve each other.</p>\n<p>You clear the canvas so you can draw all the points, seams to me that the only reason you keep an array of points is so you can draw them after you clear the canvas.</p>\n<p>Storing the points means no machine today using your function will ever be able to solve PI to over 6 digits as none have either the memory to hold all the points, nor the time to draw them.</p>\n<p>Having an open <code>setInterval</code> (no handle to stop the interval) constitutes a memory leak because you push to the <code>points</code> array each time.</p>\n<p>The task is to calculate Pi via Monte Carlo method and show the points, it can be done without the overhead,of the OO eco system and supporting scope.</p>\n<h2>General point</h2>\n<ul>\n<li><p>Use <code>const</code> for constants.</p>\n</li>\n<li><p>ECMAScripts <code>Math</code> has a <code>hypot</code> method already, however it is much quicker to do the calculation inline. As the calculation requires the radius squared, you may as well store the radius as such and then test if inside with <code>x * x + y * y < radiusSqr</code></p>\n</li>\n<li><p><code>window</code> is the default object, you don't use it for <code>window.parseInt</code> so why use it for <code>innerWidth</code>?</p>\n</li>\n<li><p><code>canvas.width</code>, and <code>canvas.height</code> represent the resolution of the canvas. They can only be integer values. <code>parseInt</code> is thus redundant.</p>\n</li>\n<li><p>You are moving the ball to the center of the canvas and with it all the points. As such need to move each point back to the origin to calculate its distance from the ball. If you moved the canvas origin to the canvas center you only need the radius, and you don't need to move the points to the ball origin to get the distance.</p>\n</li>\n<li><p>The calculation works for random distribution of points. You introduce a very non uniform distribution by rounding the points to the nearest pixel.</p>\n</li>\n<li><p>Every 10 ms you redraw the canvas content. All browsers have a MAX display rate of 60 frame per second. you draw 100 so 40 of the frames you draw are never seen. Never render to the DOM or to canvas using <code>setInterval</code> at rates above a few frames per second. Use <code>requestAnimationFrame</code></p>\n</li>\n<li><p>You Search the DOM for an element with <code>id</code> <code>"out"</code>. every 10 ms. Better to get it once at the start. better yet use direct reference via the <code>id</code> See example</p>\n</li>\n<li><p>You call the <code>Number.toString</code> when you set <code>out.textContent</code> ECMAScript does type coercion automatically you don't need to call <code>toString</code> when assign a number to a string</p>\n</li>\n<li><p>Your DOM element ids are rather poor and could be improved</p>\n</li>\n<li><p>You should set the body margin and padding to "0px" so that the canvas fits without needing to have overflow clip the canvas.</p>\n</li>\n<li><p>If you don't need to locate an element uniquely use a CSS class to set its style rather than id</p>\n</li>\n<li><p>Use the <code>setTimeout</code> rather than <code>setInterval</code> to give a interval between rather than an interval over. Many devices need time to cool or they will force the issue and reduce the clock speed. <code>setInterval</code> can result in back to back calls to the function giving no rest for the CPU/GPU, the result will be slower performance for all services the machine is running.</p>\n</li>\n</ul>\n<h2>Example</h2>\n<p>The example removes the overhead of storing points.</p>\n<p>The constant <code>pointsPerInterval</code> defines how many points to calculate each interval. The points are added to the current 2D context path and only rendered when it can be displayed using <code>requestAnimationFrame</code></p>\n<p>Having high rated of points quickly results in a black canvas. So the number of points drawn per frame is only a sub set of the points used. Thus it draws only ~1000 points per second and uses ~10million points per second to calculate PI.</p>\n<p>The example also exposes a simple interface to reset the animations, or stop.</p>\n<p>Also shows number of points use. "Mp" represents Mega points (1,000,000 points)</p>\n<p>Click the canvas to reset.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nconst calculatePi = (() => {\n const ctx = canvas.getContext(\"2d\");\n const width = canvas.width = innerWidth, halfWidth = width / 2;\n const height = canvas.height = innerHeight, halfHeight = height / 2;\n const radiusSqr = Math.min(halfWidth, halfHeight) ** 2;\n const areaScale = width * height / radiusSqr;\n const pointsPerInterval = 100000, interval = 10, showPointCount = 10;\n var pointCount, inCircleCount, timeoutHandle;\n\n ctx.setTransform(1, 0, 0, 1, halfWidth, halfHeight); // Move origin to cent of canvas\n\n resetCanvas();\n requestAnimationFrame(render); \n function resetCanvas() {\n pointCount = 0;\n inCircleCount = 0;\n ctx.clearRect(-halfWidth, -halfHeight, width, height);\n ctx.lineWidth = 5;\n ctx.beginPath();\n ctx.arc(0, 0, radiusSqr ** 0.5, 0, Math.PI * 2);\n ctx.stroke();\n ctx.beginPath();\n addPoints();\n }\n function render(){\n ctx.fill();\n ctx.beginPath();\n currentPiId.innerText = inCircleCount / pointCount * areaScale;\n pointCountId.innerText = pointCount / 1000000 | 0;\n requestAnimationFrame(render);\n }\n function addPoints() {\n var i = pointsPerInterval; \n pointCount += pointsPerInterval;\n while (i --) {\n const x = -halfWidth + Math.random() * width;\n const y = -halfHeight + Math.random() * height;\n i < showPointCount && (ctx.rect(x, y, 1, 1));\n inCircleCount += x * x + y * y < radiusSqr ? 1 : 0;\n }\n timeoutHandle = setTimeout(addPoints, interval);\n } \n return Object.freeze({\n stop() { clearTimeout(timeoutHandle) },\n restart() { \n this.stop();\n resetCanvas();\n },\n });\n})();\n\n\ncanvas.addEventListener(\"click\", () => calculatePi.restart());</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#canvas {\n position: absolute;\n top: 0px;\n left: 0px; \n}\n \n.box {\n position: absolute;\n z-index: 1;\n /*width: 200px;*/\n height: 20px;\n left: 5%;\n top: 5%;\n background-color: whitesmoke;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\"></canvas>\n<span class=\"box\"><span id=\"pointCountId\"></span>Mp = Pi &#x2248; <span id=\"currentPiId\"></span></span></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T05:39:12.913",
"Id": "216625",
"ParentId": "216614",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T01:36:26.833",
"Id": "216614",
"Score": "3",
"Tags": [
"javascript",
"animation",
"numerical-methods",
"canvas"
],
"Title": "Monte Carlo pi animation"
} | 216614 |
<p>I've tried to solve the kattis-challenge called Watchdog. <strong>My code works just fine, but it was too slow on the last test</strong>. I'm wondering if anyone sees any big algorithmic performance issues. </p>
<p>A short description of the task: First line from .in states number of test-cases.
First line in each test-case gives length of a square and number of hatches respectively. For each hatch you'll have one line giving x and y-point of hatch respectively. The mission is to find a point (x,y) where the length from (x,y) to any hatch is not greater than the length from (x,y) to any point outside of the square. If no such point, print <code>poodle</code>. If several such point print point with lowest x, if several points with equal x, print point with lowest y. Hatches and these points cannot overlap.</p>
<p>I think one issue might be extensive usage of lists, but I'm also not sure how to avoid them. Initially I started reading one and one line from <code>stdin</code> using the data. That way things looked way more readable, but it was also slower. And <strong>it's the speed that I'm having issues with</strong>.</p>
<h3>Example input:</h3>
<pre><code>3
10 2
6 6
5 4
20 2
1 1
19 19
10 3
1 1
1 2
1 3
</code></pre>
<h3>Example output:</h3>
<pre><code>3 6
poodle
2 2
2 2
</code></pre>
<h3>My code:</h3>
<pre><code>import sys
from math import sqrt
import itertools
def findmaxdist(x1, y1, list):
'''Finds the distance from x1, y1 to the most
distant point in the list.'''
dist = 0
for x2, y2 in list:
newdist = (x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)
if newdist>dist:
dist=newdist
return sqrt(dist)
fulltext = sys.stdin.readlines()
text = [w.rstrip('\n') for w in fulltext]
cases = int(text[0])
i = 0
j = 1
while i < cases:
side, hatches = text[j].split()
side = int(side)
hatches = int(hatches)
j += 1
hatch_list = list()
for k in range(hatches):
x, y = text[j].split()
hatch_list.append((int(x), int(y)))
j += 1
possibles = list()
for x,y in itertools.product(range(side), range(side)):
if (x, y) not in hatch_list:
dist = findmaxdist(x, y, hatch_list)
if x+dist<=side and x-dist>=0:
if y+dist<=side and y-dist>=0:
possibles.append((x, y))
if len(possibles)==0:
print('poodle')
elif len(possibles)==1:
print(str(possibles[0][0])+' '+str(possibles[0][1]))
elif len(possibles)>1:
smallx = min(possibles, key = lambda t: t[0])[0]
semifinal = list((tuple for tuple in possibles if tuple[0] == smallx))
if len(semifinal)==1:
x,y = semifinal[0]
print(str(x)+' '+str(y))
elif len(semifinal)>1:
smally = min(semifinal, key = lambda t: t[1])[1]
final = list((tuple for tuple in semifinal if tuple[1] == smally))
if len(final)==1:
x,y = final[0]
print(str(x)+' '+str(y))
else:
print('Error: Wrong input-format?')
i+=1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T02:34:12.513",
"Id": "419020",
"Score": "1",
"body": "To specifically answer your question, you'd need to use a profiler to look at the code and see how long it takes. Given there is no sample input with your code, I'm unable to demonstrate how you would do this yourself. Could you add it to your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:17:29.600",
"Id": "419022",
"Score": "0",
"body": "The sample-input is given right before my code, after \"Example in:\", or am I misunderstanding what you're asking for? I could use `timeit` to time the runtime of the code, and I have for myself, but every change I make gives very small differences in computing-time. Therefore I expect something to be obviously slower than an alternative, though I can't see it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:31:33.250",
"Id": "419023",
"Score": "0",
"body": "Oh yes sorry - so I run the program and paste the examples and nothing works. I type in a single line - and nothing works. How are you running the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:42:24.373",
"Id": "419025",
"Score": "0",
"body": "The example is taken directly form stdin. You have a file containing the code, e.g. a file distance.py containing everything from the section \"My code\" above. Then you have a separate file within the same folder containing the example, e.g. a file example.in containing everything from the section \"Example in\" above. Then from the command-line (on windows) you'd run python distance.py < Example.in"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:34:51.450",
"Id": "419031",
"Score": "1",
"body": "Please fix your indentation. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:56:23.960",
"Id": "419032",
"Score": "0",
"body": "Sorry, I added the block-text underneath the definition of findmaxdist after pasting my code, so I slipped up. There should be no other indentation-errors now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:47:09.380",
"Id": "419131",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:59:05.863",
"Id": "419134",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ Thank you! Though added it in its own block, clearly seperating them, with that exact post in mind. I think there were no risk of confusion. If anything I think it will be more confusing posting it as an answer. But I will follow your guidelines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:01:35.397",
"Id": "419135",
"Score": "0",
"body": "IIWY I would choose option number 2 (i.e. _Posting a new question_)... unless you have something insightful to say about your original code and explain why the updated code is better, then you could add a self-answer..."
}
] | [
{
"body": "<p>To specifically answer your question, you'd need to use a profiler to look at the code and see how long it takes.</p>\n\n<pre><code>cprofilev 20190401a.py < 20190401a.txt \n 1273 function calls in 0.001 seconds\n\nOrdered by: cumulative time\n\nncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 0.001 0.001 {built-in method builtins.exec}\n 1 0.000 0.000 0.001 0.001 20190401a.py:1(<module>)\n 593 0.000 0.000 0.000 0.000 20190401a.py:6(findmaxdist)\n 1 0.000 0.000 0.000 0.000 {method 'readlines' of '_io._IOBase' objects}\n 593 0.000 0.000 0.000 0.000 {built-in method math.sqrt}\n 3 0.000 0.000 0.000 0.000 {built-in method builtins.print}\n 2 0.000 0.000 0.000 0.000 /usr/lib/python3.5/codecs.py:318(decode)\n 2 0.000 0.000 0.000 0.000 {built-in method builtins.min}\n 1 0.000 0.000 0.000 0.000 20190401a.py:18(<listcomp>)\n 1 0.000 0.000 0.000 0.000 <frozen importlib._bootstrap>:996(_handle_fromlist)\n 22 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n 4 0.000 0.000 0.000 0.000 20190401a.py:48(<genexpr>)\n 1 0.000 0.000 0.000 0.000 {built-in method builtins.hasattr}\n 11 0.000 0.000 0.000 0.000 {method 'rstrip' of 'str' objects}\n 10 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects}\n 2 0.000 0.000 0.000 0.000 {built-in method _codecs.utf_8_decode}\n 15 0.000 0.000 0.000 0.000 20190401a.py:47(<lambda>)\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 9 0.000 0.000 0.000 0.000 {built-in method builtins.len}\n</code></pre>\n\n<p>I ran cprofile a few times and the function call numbers are static. From the look of your code, we're seeing multiple requests to findmaxdist and math.sqrt, there might be an opportunity to clean that up.<br>\nThere are 22 appends to a list object, which if we look at \"Common Data Structure Operations\" (see <a href=\"http://bigocheatsheet.com/\" rel=\"nofollow noreferrer\">http://bigocheatsheet.com/</a>), which might be an inefficient data structure for what you're trying to achieve. </p>\n\n<p>Looking at your code, regardless of speed, having it all as one giant blob instead of neatly separated into functions (look up the Single Responsibility Principal) can make your code execute faster as functions compile down neatly and very efficiently - especially when written in a functional style of programming (no state maintained in the function after the function completes).</p>\n\n<p>Other than streamlining the calls and changing your data structure, I don't think you'll see much speed improvement with the code as-in. I hope this helps somewhat?<br>\nGood luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:28:22.993",
"Id": "419030",
"Score": "0",
"body": "Thank you, I'll try to make the suggested changes and see how it works!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T01:13:04.817",
"Id": "419394",
"Score": "0",
"body": "LOL why the downvotes? Performance is a valid question criteria for Code Review, and profiling code is the first step towards removing performance hits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T05:22:19.897",
"Id": "419401",
"Score": "0",
"body": "I don't know who downvoted you. I upvoted. Though, after the fact, I think it probably has to do with the fact that the main issue came from a missing break-point, and not the number of calls to each method. In that sense one could easily be sent on a wild goose-chase. Still, I think your post was helpful, as I've made many improvements based on it, and I don't think you should have been downvoted. But I also don't know how this site works, I'm still dumbfounded that I can't post an update to how the code has improved based on suggestions here. But oh well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:20:02.640",
"Id": "419403",
"Score": "1",
"body": "If you see some other posts, people recommend creating a new post/submission with links to the previous posting when the code has changed (perhaps that's covered under the Help in the footer?) But yeah, maybe \"one day\" we will be able to select different versions if they add git as part of the posting/submission process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T15:12:12.073",
"Id": "420937",
"Score": "0",
"body": "I didn't downvote, but given that almost all of the timings are \"0.000\" it doesn't tell you where the performance problems are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T03:37:45.740",
"Id": "420973",
"Score": "0",
"body": "Correct, the program is so tiny there isn't a \"time\" issue per-say, but the profile ncalls clearly state findmaxdist and sqrt can be reduced 90%+ with memoziation. After all, with only 21 inputs, why do we do 593 actions?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:20:33.753",
"Id": "216621",
"ParentId": "216615",
"Score": "-2"
}
},
{
"body": "<p>Your solution is right, but unfortunately the time limit enforces a certain optimization. The key of this is where it says: </p>\n\n<blockquote>\n <p>If several such point print point with lowest x, if several points with equal x, print point with lowest y</p>\n</blockquote>\n\n<p>In your case, you just append all possible candidate and then you have a very complicated way to find the lowest. First of all, this complicated way could have been reduced to sorting and returning first element. </p>\n\n<p>If we think a bit further on how does <code>itertools.product</code> work, it will first iterate over x and then over y. This means that the first candidate we find, is the one with lowest x and lowest y of those x. This means 2 things: you don´t even need that sort, the answer will always be the first candidate. </p>\n\n<p>Now if the answer is always the first candidate, why are we keeping all candidates? And why are we still calculating other possible candidates when we already have the answer? Keeping this in mind, the solution to your time limit is simple adding a <code>break</code> after the <code>possibles.append((x, y))</code> line. This will make us stop processing when we find the answer, and will save enough time for the time limit. </p>\n\n<p>This means all the <code>elif len(possibles)>1:</code> part is unnecessary, making it shorter and cleaner. Another simple optimization is changing <code>hatch_list</code> to a set instead of a list so that the <code>if (x, y) not in hatch_list:</code> takes less than O(n). Its a small change that only requires changing <code>list()</code> to <code>set()</code> and <code>append</code> to <code>add</code>. </p>\n\n<p>There might be more optimization to make but the one of the break is the key to the problem and the expected optimization to make to be able to not have time limit.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:09:22.643",
"Id": "419103",
"Score": "0",
"body": "Thank you very much for your contribution! Incidentally I've made the exact same realization on my own. The whole use of possible solutions is just a waste of computing time. So I have shortened my code quite a bit, and I also did break, and I added a boolean-flag to see if any solutions was found at all (if not poodle is printed). Still though, I get timed out on the very last test. But I have yet to try your suggestion of changing list to set. I will do that next.\n\nIf you someone wouldn't mind: What is the preferred way of showing my \"progress\", I know I'm not supposed to update original."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:20:49.480",
"Id": "419106",
"Score": "0",
"body": "@RoyM you may edit your question and add something like: Update: I have now updated the code to this but it is still giving me time out and show current code. Also I straight copied your code and added the break and submitted to kattis and got accepted before, are you submitting somewhere else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:28:01.347",
"Id": "419128",
"Score": "0",
"body": "You did? Now I'm positively confused. I've been at this one for hours, having a much more minimized solution fail for several of them. I'll provide an update in my question giving my current code – which do fail at `https://open.kattis.com/problems/watchdog`. The only thing I can think of is some misspelling giving me an infinite loop, or an issue with using the \"edit and resubmit\"-function from an old subit that had the timeout."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:45:13.453",
"Id": "419130",
"Score": "0",
"body": "@RoyM I have no idea why your current code gives time limit, but if you copy your old code posted here, add the break line after possibles.append and submit, you will get accepted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:47:38.743",
"Id": "419140",
"Score": "0",
"body": "Oh wow, it did. I still can't see why the improved version edited away from the OP doesn't. It has the same change, and several other improvements. I guess I'll find a rogue parentheses or the like if I just stare at it enough. But you've been a grat help. Thank you!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T16:02:48.953",
"Id": "216663",
"ParentId": "216615",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216663",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T02:05:43.773",
"Id": "216615",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "Programming Challenge from Kattis: Watchdog"
} | 216615 |
<blockquote>
<p>Exercise 6: Rewrite the program that prompts the user for a list of numbers and prints out the maximum and minimum of the numbers at the end when the user enters “done”. Write the program to store the numbers the user enters in a list and use the max() and min() functions to compute the maximum and minimum numbers after the loop completes.</p>
</blockquote>
<pre><code>num_list = []
num = input('Please enter a number: ')
while num != 'done' and num != 'DONE':
try:
num_list.append(int(num))
num = input('Please enter a number: ')
except:
num = input("Not a number. Please enter a number Or 'done' to finish: ")
try:
print('Maximum number: ', max(num_list))
print('Minimum number: ', min(num_list))
except:
print('NO INPUT!')
</code></pre>
| [] | [
{
"body": "<p>You can use lower() on the variable to cover all possible input types,</p>\n\n<pre><code>while num:\n if num.lower()=='done':\n break\n try:\n num_list.append(int(num))\n except:\n print(\"Invalid input\")\n num = input('Please enter a number: ')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T05:12:10.137",
"Id": "419033",
"Score": "0",
"body": "The `and` condition is correct; `or` is wrong! With `or`, the condition is always `true`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T05:15:49.630",
"Id": "419034",
"Score": "0",
"body": "The variable `num` is assigned from `input`(), so it is always a `str`. The `isinstance(num, str)` is completely unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T05:18:53.900",
"Id": "419035",
"Score": "0",
"body": "And `isinstance(num, int)` is always `false`, because `num` is a string!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:12:40.400",
"Id": "419055",
"Score": "1",
"body": "`num = input(…)` should be inside the `while`, not the `except`, otherwise it will keep appending the same number _ad infinitum_ leading to a `MemoryError`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:27:57.817",
"Id": "419085",
"Score": "0",
"body": "I just wonna say that you guys are amazing :). Thank you very much, your help means a lot for me."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T04:11:59.447",
"Id": "216619",
"ParentId": "216617",
"Score": "2"
}
},
{
"body": "<ol>\n<li>Avoid repeating yourself: use a single <code>input</code> call; it isn't much here, but it is easily error-prone if your \"initialization\" phase is several steps long. The usual idiom in such case is to use a <code>while True</code> loop and test the condition after the initialization to <code>break</code> if necessary.</li>\n<li>Please avoid bare <code>except</code>, this is a bad habit to get into. This will catch all exceptions, including the ones you're not expecting (such as <code>KeyboardInterrupt</code> if the user hits Ctrl+C) and, thus, not ready to handle. In both cases, you’re expecting <code>ValueError</code>s here.</li>\n<li>Use functions, this will make your code much more reusable:</li>\n</ol>\n\n\n\n<pre><code>def ask_user_number_list():\n num_list = []\n while True:\n num = input('Please enter a number or 'done' to finish: ')\n if num.lower() == 'done':\n break\n\n try:\n number = int(num)\n except ValueError:\n print('Invalid input')\n else:\n num_list.append(number)\n\n return num_list\n\n\ndef search_min_and_max(lst):\n try:\n return min(lst), max(lst)\n except ValueError:\n return None\n\n\nif __name__ == '__main__':\n bounds = search_min_and_max(ask_user_number_list())\n if bounds is None:\n print('NO INPUT!')\n else:\n print('Maximum number: ', bounds[-1])\n print('Minimum number: ', bounds[0])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:27:00.197",
"Id": "419084",
"Score": "0",
"body": "I just wonna say that you guys are amazing :). Thank you very much, your help means a lot for me."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:10:25.647",
"Id": "216639",
"ParentId": "216617",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216639",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:14:38.740",
"Id": "216617",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Take a list of nums and return max and min"
} | 216617 |
<p>I have built a basic shopping cart simulator. All it does is add and remove items between two different basket (i.e. aisle vs basket).</p>
<p>While working on the problem I started to think about the approach and would love to hear what people think.</p>
<ol>
<li>Avoid initializing the state empty state in the constructor. However, I had to initialize <code>shoppingCart: []</code> in <code>componentDidMount</code> hook to avoid type error. What is the better and cleaner approach?</li>
<li>Is it good practice to keep the logic simple in <code>handleXXXClicks</code>, separation of concern one for handling <code>items</code> and one for <code>shoppingCart</code>?</li>
<li>I feel <code>aisleList</code> and <code>cartList</code> bloated and I could have written <code>itemComponent</code> which is avoidable duplicate code.</li>
<li>Is there any better way to handle the item in <code>setState</code>? I couldn't think of using <code>prevState</code> in my scenario.</li>
</ol>
<p>Use <code>setState</code> without initializing <code>state</code>:</p>
<pre><code>componentDidMount() {
// assuming data comes from API fetch
let items = ["banana", "eggs", "bread", "apple"];
this.setState({
items,
shoppingCart: [] // had to set this empty to avoid typeerror
});
}
</code></pre>
<p>Handle <code>handleClick</code> and <code>setState</code>:</p>
<pre><code>handleCartClick = event => {
let newList = this.state.shoppingCart.filter(item => {
return item !== event.target.value;
});
this.setState({
items: [...this.state.items, event.target.value],
shoppingCart: [...newList]
});
};
</code></pre>
<p>Gist <a href="https://gist.github.com/citta-lab/bd0cdd2170bb15b03ad198b2a8559145" rel="nofollow noreferrer">link</a></p>
<p>Demo <a href="https://codesandbox.io/s/mjx0l2l7jj" rel="nofollow noreferrer">link</a></p>
| [] | [
{
"body": "<h1>Some Tips</h1>\n\n<ul>\n<li>Avoid using constructor.</li>\n<li>Avoid using <code>.bind(this)</code></li>\n<li>Destructuring will help you to make cleaner code.</li>\n</ul>\n\n<h1>Questions</h1>\n\n<blockquote>\n <ol>\n <li>Avoid initializing the state empty state in the constructor. However, I had to initialize shoppingCart: [] in componentDidMount hook to avoid type error. What is the better and cleaner approach?</li>\n </ol>\n</blockquote>\n\n<p>You can have 2 aproaches to this</p>\n\n<ol>\n<li><p>There is a way to avoid this, what you do is destruct the state in the variables you want and set then a default value of an array.</p>\n\n<pre><code>state = {}\n\nrender() {\n const {\n shoppingCart = []\n } = this.state\n ...\n}\n</code></pre>\n\n<p>This way you don't need to check if <code>shoppingCart</code> is an array, and you only need to declare <code>this.state</code> as an object ( it can be just an empty object ).</p>\n\n<p>You can also do </p>\n\n<pre><code>render() {\n const {\n shoppingCart = []\n } = this.state || {}\n ...\n}\n</code></pre>\n\n<p>And now you don't even need <code>state = {}</code> </p></li>\n<li><p>Because you are using arrow functions, you don't need <code>.bind(this)</code> and also you can avoid de constructor and just use</p>\n\n<pre><code>state = {\n ...\n}\n</code></pre>\n\n<p>This way you can declare <code>shoppingCart</code> and <code>items</code> and don't need to declare it in <code>componentDidMount</code> (wich is much better to understand) and now don't need to destruct the state.</p>\n\n<pre><code>state = {\n shoppingCart = [],\n items = []\n}\n</code></pre>\n\n<p>This way is good if the data you will get is always an array (or the type you specify) and another good reason to use this is that when other programmer look at the code, they will immediately know what is stored in that component state, but when you have too many things in the state, it can get confused.</p></li>\n</ol>\n\n<p>This aproaches will solve some problems like using ternary to check if you have an state and then return the mapping or if you don't have, return an empty array.</p>\n\n<pre><code>render() {\n\n const {\n items = [],\n shoppingCart = []\n } = this.state\n\n let aisleList = items.map((item, index) => {\n return (\n <div key={index}>\n <span>{item}</span>\n <input\n type=\"checkbox\"\n id={index}\n value={item}\n onClick={this.handleAileClick}\n />\n </div>\n );\n });\n\n let cartList = shoppingCart.map((item, index) => {\n return (\n <div key={index}>\n <span>{item}</span>\n <input\n type=\"checkbox\"\n autoComplete=\"off\"\n value={item}\n onClick={this.handleCartClick}\n />\n </div>\n );\n });\n ...\n}\n</code></pre>\n\n<p>Looking at this, is much clean and easy to understand.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Is it good practice to keep the logic simple in handleXXXClicks, separation of concern one for handling items and one for shoppingCart?</li>\n </ol>\n</blockquote>\n\n<p>You can do the way you want, but you need to see what you will do in the future, if both will always do the same, you can create one function for both and just send a different parameter, but if they will do some extra stuff, it's good to have then separated.</p>\n\n<p>*(I'm not english native speaker and maybe I didn't understand exaclty what is this part about).</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>I feel aisleList and cartList bloated and I could have written itemComponent which is avoidable duplicate code.</li>\n </ol>\n</blockquote>\n\n<p>Yes, they look so similar that you should create a component for both and pass the diference in props.</p>\n\n<blockquote>\n <ol start=\"4\">\n <li>Is there any better way to handle the item in setState? I couldn't think of using prevState in my scenario.</li>\n </ol>\n</blockquote>\n\n<p>Here is simple <code>setState</code> using a function with <code>prevState</code>. Note that the way you are doing it, you need to have <code>event.persist()</code>, for more info look <a href=\"https://reactjs.org/docs/events.html#event-pooling\" rel=\"nofollow noreferrer\">here</a></p>\n\n<pre><code>handleCartClick = event => {\n event.persist();\n\n this.setState(prevState => {\n return {\n items: [...prevState.items, event.target.value],\n shoppingCart: prevState.shoppingCart.filter(item => {\n return item !== event.target.value;\n })\n };\n });\n};\n</code></pre>\n\n<h1>Overall</h1>\n\n<p>Your code looks ok, there is only one strange thing. You are using checkboxes and when you click, some get marked and other don't. I don't know if that was a test or you also wanted to solve the checkbox problem. Let me know and I can see what I can do.</p>\n\n<p>I recommend you to start using some new things like I mentioned in the tips part, that help you alot and make your code cleaner.</p>\n\n<p>Also have a look at <a href=\"https://reactjs.org/docs/hooks-intro.html\" rel=\"nofollow noreferrer\">hooks</a>.<br>\nFor me, using hooks makes alot of things easier, but also, the code looks cleaner.</p>\n\n<p>I made a <a href=\"https://codesandbox.io/s/y2q17ynnzv\" rel=\"nofollow noreferrer\">demo</a> for you to test and see the new code. I changed some things.</p>\n\n<ul>\n<li>I changed <code>handleCartClick</code> but left <code>handleAileClick</code> the way it was before, so you can try useing <code>prevState</code> yourself.</li>\n<li>And also left the part of <code>itemComponent</code> for you.</li>\n</ul>\n\n<p>The best way to learn, is doing it!</p>\n\n<p>Hope I helped you! </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:39:44.047",
"Id": "423877",
"Score": "0",
"body": "why avoid using of contructor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:41:22.737",
"Id": "423878",
"Score": "0",
"body": "@degr You should think in a different way, Why should I use the constructor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:42:14.373",
"Id": "423879",
"Score": "0",
"body": "I should use constructor because it is common practice in all OOP languages where I can declare state of object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:43:29.173",
"Id": "423880",
"Score": "0",
"body": "You would use contructor for things like `.bind` or declaring the state, but now you don't need to use `.bind` because arrow functions solve this and you can set the state outside this like a normal property of the class e.g. `state = { anythingyouwant: something}`. And also, now with hooks, using class component will desapear over time, and functional components can't have constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:46:17.440",
"Id": "423884",
"Score": "0",
"body": "`I should use constructor because it is common practice in all OOP languages`, Acctualy, you should use only necessary things, but now, you have better ways of doing the same thing, but in simpler way. I'm not saying you can't use contructor, but that is better to use other ways."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:47:21.090",
"Id": "423885",
"Score": "0",
"body": "I said nothing about arrow functions. When I open class, and I see state declaration in constructor, I know all about state structure of this component. If component have no state in constructor, I will definitely create it by self, because it is much more clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:47:53.283",
"Id": "423886",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/93046/discussion-between-vencovsky-and-degr)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:14:26.900",
"Id": "219426",
"ParentId": "216618",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T03:27:47.057",
"Id": "216618",
"Score": "3",
"Tags": [
"javascript",
"ecmascript-6",
"react.js",
"e-commerce",
"react-native"
],
"Title": "React code to build shopping cart"
} | 216618 |
<p>I have a small C# program that validates Swedish social security numbers (<a href="https://en.wikipedia.org/wiki/Personal_identity_number_%28Sweden%29" rel="nofollow noreferrer">'Personnummer'</a>).</p>
<p>I chose to use Regex as there are many different ways it can be input.</p>
<pre><code>using System;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
namespace Personnummer
{
/// <summary>
/// Class used to verify Swedish social security numbers.
/// </summary>
public static class Personnummer
{
private static readonly Regex regex;
private static readonly CultureInfo cultureInfo;
static Personnummer()
{
cultureInfo = new CultureInfo("sv-SE");
regex = new Regex(@"(\d{2}){0,1}(\d{2})(\d{2})(\d{2})([-|+]{0,1})?(\d{3})(\d{0,1})");
}
/// <summary>
/// Calculates the checksum value of a given digit-sequence as string by using the luhn/mod10 algorithm.
/// </summary>
/// <param name="value">Sequense of digits as a string.</param>
/// <returns>Resulting checksum value.</returns>
private static int Luhn(string value)
{
// Luhm algorithm doubles every other number in the value.
// To get the correct checksum digit we aught to append a 0 on the sequence.
// If the result becomes a two digit number, subtract 9 from the value.
// If the total sum is not a 0, the last checksum value should be subtracted from 10.
// The resulting value is the check value that we use as control number.
// The value passed is a string, so we aught to get the actual integer value from each char (i.e., subtract '0' which is 48).
int[] t = value.ToCharArray().Select(d => d - 48).ToArray();
int sum = 0;
int temp;
for (int i = t.Length; i -->0; )
{
temp = t[i];
sum += (i % 2 == t.Length % 2)
? ((temp * 2) % 10) + temp / 5
: temp;
}
return sum % 10;
}
/// <summary>
/// Function to make sure that the passed year, month and day is parseable to a date.
/// </summary>
/// <param name="year">Years as string.</param>
/// <param name="month">Month as int.</param>
/// <param name="day">Day as int.</param>
/// <returns>Result.</returns>
private static bool TestDate(string year, int month, int day)
{
try
{
DateTime dt = new DateTime(cultureInfo.Calendar.ToFourDigitYear(int.Parse(year)), month, day);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Validate Swedish social security number.
/// </summary>
/// <param name="value">Value as string.</param>
/// <returns>Result.</returns>
public static bool Valid(string value)
{
MatchCollection matches = regex.Matches(value);
if (matches.Count < 1 || matches[0].Groups.Count < 7)
{
return false;
}
GroupCollection groups = matches[0].Groups;
int month, day, check;
string yStr;
try
{
yStr = (groups[2].Value.Length == 4) ? groups[2].Value.Substring(2) : groups[2].Value;
month = int.Parse(groups[3].Value);
day = int.Parse(groups[4].Value);
check = int.Parse(groups[7].Value);
}
catch
{
// Could not parse. So invalid.
return false;
}
bool valid = Luhn($"{yStr}{groups[3].Value}{groups[4].Value}{groups[6].Value}{check}") == 0;
return valid && (TestDate(yStr, month, day) || TestDate(yStr, month, day - 60));
}
/// <summary>
/// Validate Swedish social security number.
/// </summary>
/// <param name="value">Value as long.</param>
/// <returns>Result.</returns>
public static bool Valid(long value)
{
return Valid(value.ToString());
}
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p><code>@\"(\\d{2}){0,1}(\\d{2})(\\d{2})(\\d{2})([-|+]{0,1})?(\\d{3})(\\d{0,1})\"</code></p>\n</blockquote>\n\n<p>You <code>Regex</code> pattern should check for start and end anchors by placing an <code>'^'</code> at start and <code>'$'</code> at the end:</p>\n\n<p><code>@\"^(\\d{2}){0,1}(\\d{2})(\\d{2})(\\d{2})([-|+]{0,1})?(\\d{3})(\\d{0,1})$\"</code></p>\n\n<p>If you don't do that, the following \"number\" is valid:</p>\n\n<pre><code>\"xx811228-9874yyyy\"\n</code></pre>\n\n<hr>\n\n<p>You can name the groups in a <code>Regex</code> pattern:</p>\n\n<pre><code>string pattern = @\"^(?<year>(\\d{2}){1,2})(?<month>\\d{2})(?<day>\\d{2})[-|+]{1}(?<litra>\\d{3})(?<check>\\d{1})$\";\n</code></pre>\n\n<p>This will make it more readable and maintainable and you can access each part by name:</p>\n\n<pre><code>int year = int.Parse(match.Groups[\"year\"].Value)\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>yStr = (groups[2].Value.Length == 4) ? groups[2].Value.Substring(2) : groups[2].Value;</code></p>\n</blockquote>\n\n<p>Instead you could do </p>\n\n<pre><code> int year = int.Parse(match.Groups[2].Value) % 100;\n</code></pre>\n\n<p>where the <code>% 100</code> will remove the century part.</p>\n\n<hr>\n\n<blockquote>\n <p><code>int[] t = value.ToCharArray().Select(d => d - 48).ToArray();</code></p>\n</blockquote>\n\n<p>In general <code>string</code> implements <code>IEnumerable<char></code> so there's no need for <code>.ToCharArray()</code></p>\n\n<p>It's safe to write:</p>\n\n<pre><code>int[] t = value.Select(d => d - '0').ToArray();\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> bool valid = Luhn($\"{yStr}{groups[3].Value}{groups[4].Value}{groups[6].Value}{check}\") == 0;\n return valid && (TestDate(yStr, month, day) || TestDate(yStr, month, day - 60));\n</code></pre>\n</blockquote>\n\n<p>I think I'd check the date before calling <code>Luhn()</code> as the Luhn result makes no sense with an invalid date, and you could avoid one of the calls to <code>TestDate</code> if you validate the <code>day</code> value against 60:</p>\n\n<pre><code>if (day > 60) \n{\n day -= 60;\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>for (int i = t.Length; i-- > 0;)</code></p>\n</blockquote>\n\n<p>This is a rather unusual way to use a for-loop and difficult to understand, because you have to think about when <code>i</code> is actually decremented. Is there any reason to iterate backwards?</p>\n\n<p>Why not just do:</p>\n\n<pre><code>for (int i = 0; i < t.Length; i++) {...}\n</code></pre>\n\n<hr>\n\n<p>IMO the <code>Valid()</code> method (which should maybe be called <code>Validate(string number)</code>) is doing too much. Split it up in appropriate dedicated methods like:</p>\n\n<pre><code>public static bool Validate(string number)\n{\n try\n {\n var parts = Split(number);\n CheckDate(parts);\n CheckLuhn(parts);\n }\n catch\n {\n return false;\n }\n\n return true;\n}\n</code></pre>\n\n<p>Here <code>parts</code> could be a named tuple:</p>\n\n<pre><code>(int year, int month, int day, int litra, int check) parts\n</code></pre>\n\n<p>or you could create a dedicated <code>class/struct</code> for that.</p>\n\n<p><code>CheckDate()</code> and <code>CheckLuhn()</code> don't return <code>bool</code> but throws if an error is detected. </p>\n\n<p>You could consider to let <code>Validate()</code> throw as well instead of returning <code>bool</code> on error in order to be able to inform the client of the kind of error and/or where it happened.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T08:55:19.287",
"Id": "216633",
"ParentId": "216623",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216633",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T05:33:45.703",
"Id": "216623",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"regex",
"validation",
"checksum"
],
"Title": "Swedish 'Personnummer' validator"
} | 216623 |
<p>I have written this custom hashset and though it isn't completed yet, I would like to know if there is anything I am overlooking in terms of clean code conventions. My aim was also to apply generics to it. So, would also want any input regarding that.</p>
<pre><code> public class CustomHashset<T> {
private static final int SIZE = 100;
private Entry<T>[] buckets;
private int size;
public CustomHashset() {
this.buckets = new Entry[SIZE];
this.size= 0;
}
private int hash(T element) {
return element.hashCode() % buckets.length;
}
public Boolean add(T element) {
int index = hash(element);
Entry<T> current = buckets[index];
while (current!=null) {
if (current.key.equals(element)) return false;
current = current.next;
}
Entry<T> entry = new Entry<T>();
entry.setKey(element);
entry.setNext(buckets[index]);
buckets[index] = entry;
size++;
return true;
}
public int size() {
return size;
}
private static class Entry<T> {
private T key;
private Entry next;
public T getKey() {
return key;
}
public void setKey(T element) {
this.key = element;
}
public Entry getNext () {
return next;
}
public void setNext(Entry next) {
this.next = next;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T15:05:34.533",
"Id": "419092",
"Score": "1",
"body": "Request for Clarification: do you want your CustomHashSet to be a HashSet? i.e., do you want this to be valid: `HashSet<T> hashSet = new CustomHashSet<>();`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T16:01:12.457",
"Id": "419097",
"Score": "0",
"body": "@Wood Glass, no."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T22:10:27.247",
"Id": "419144",
"Score": "1",
"body": "What are your design goals? Is there a reason that `java.util.HashSet` will not suffice? Do you want to integrate nicely with the Java Collections Framework, or avoid it entirely? It is hard to review this code without more context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T06:38:55.523",
"Id": "419175",
"Score": "0",
"body": "@BenjaminKuykendall, simply learning how to implement these data structures using generics."
}
] | [
{
"body": "<p><strong><em>Improving names:</em></strong></p>\n\n<ul>\n<li><p>Your class has 2 <code>size</code> variables, which looks kinda strange. Better to rename this private static one to something like <code>INITIAL_CAPACITY</code> (or <code>DEFAULT_INITIAL_CAPACITY</code>, if you have plans adding constructor with <code>initialCapacity</code> parameter), because size = how many elements are stored, but this variable denotes initial array length.</p></li>\n<li><p>method <code>hash</code> in reality returns bucket index for given element, thus, should be renamed. For example, to <code>indexFor</code> or <code>bucketIndex</code>. </p></li>\n</ul>\n\n<p><strong><em>Other:</em></strong></p>\n\n<ul>\n<li>in <code>Entry</code> - <code>next</code> is not parameterized (as well as its getter and setter).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T19:04:42.583",
"Id": "419259",
"Score": "0",
"body": "Thanks I will look into those."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:34:17.077",
"Id": "216705",
"ParentId": "216634",
"Score": "2"
}
},
{
"body": "<h2>Problems with generics</h2>\n\n<ul>\n<li><p><code>Entry<T>.next</code> should have type <code>Entry<T></code>.</p></li>\n<li><p><code>CustomHashset<T>.buckets</code> has type <code>Entry<T>[]</code> but is initialized to an <code>Entry[]</code>. Initializing a generic array properly is annoying, but <a href=\"https://stackoverflow.com/questions/529085/how-to-create-a-generic-array-in-java\">this StackOverflow question</a> explores a few solutions. At the end of the day, there's only so much you can do about it; you can at least suppress the compiler warning though.</p></li>\n</ul>\n\n<h2>Interface of <code>Entry</code></h2>\n\n<p>You never use the getters and setters. Remove them.</p>\n\n<h2>Abstract out linked list</h2>\n\n<p>As you implement more methods, it should become apparent that you are using the chain of <code>Entry<T></code> objects as a linked list. Thus the interface it presents could be more abstract: in fact, I would create a <code>LinkedList<T></code> class with <code>add(T t)</code> and <code>contains(T t)</code> methods. Then make <code>buckets</code> an array of <code>LinkedList<T></code>. This way, the hash set never has to deal with individual entries.</p>\n\n<h2>Small problems</h2>\n\n<ul>\n<li>Use or omit <code>this</code> more consistently. I would omit it unless needed.</li>\n<li>Return <code>boolean</code> not <code>Boolean</code>.</li>\n<li>Currently, <code>a null</code> key causes a <code>NullPointerException</code> when you call <code>hash()</code>. You should detect <code>null</code> inputs to <code>add</code> and explicitly throw an <code>IllegalArgumentException</code> instead.</li>\n<li>Use default visibility instead of public to expose methods of private inner classes.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:27:12.167",
"Id": "419415",
"Score": "0",
"body": "Thanks for your review. Very interesting take.\n1. I really didn't have any problem initializing the generic array. Maybe there is something you can point to in the way I have initialized it for a better understanding. I took a look at the link you added and it appears I was doing something close to the checked except I wasn't wrapping it in the way it was explained over there.\n\n2. I did use the setters but not the getters. So, I will remove the getters. Thanks for that.\n\nContinuation ...below"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T07:28:28.653",
"Id": "419417",
"Score": "0",
"body": "3. Could you elaborate further on the 'Abstract out linked list'? I get you want me to make the Entry<T> a LinkedList<T> because, under the hood, I was using node chaining. I don't get making buckets an array of LinkedList<T>. Even though I could do that, would I not be relying on an existing implementation? I could very well have just added a Java HashMap internally and not bother about implementing the hashing and the add contains e.t.c as I would just be calling the hashMap operators under the hood. So, just want to know if this is Ok to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:44:34.963",
"Id": "419448",
"Score": "1",
"body": "I would also ditch the setters in favor of a constructor: `Entry<T>(T element, Entry<T> next)`. If you do this, you can even make both fields `final`. If you don't want to use `java.util.LinkedList`, writing your own `CustomLinkedList` that supports `add` and `contains` is really easy; in fact you have most of the code there, it's just a mater of reorganizing it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T19:38:59.960",
"Id": "216745",
"ParentId": "216634",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216745",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:20:30.737",
"Id": "216634",
"Score": "4",
"Tags": [
"java",
"reinventing-the-wheel",
"hash-map",
"set"
],
"Title": "Custom Hashset in Java"
} | 216634 |
<p><a href="https://stackoverflow.com/questions/55450943/breaking-solid-principles-in-interview-task">Originally asked on Stack Overflow</a></p>
<p>I recently had an interview where interviewers asked me to</p>
<ol>
<li>Rewrite following code with SOLID principles.</li>
<li>Add a new file handler (<code>PriceFileHandler</code> for example).</li>
<li>Add supporting stream parsing (to one parser implementation)</li>
</ol>
<p>Here is the code which I had to change:</p>
<pre><code><?php
class FileHandler
{
public function parse(string $type, string $data)
{
switch ($type) {
case 'xml':
$parser = new XmlParser();
break;
case 'csv':
$parser = new CsvParser();
break;
default:
throw new InvalidArgumentException();
}
return $parser->parse($data);
}
}
class XmlParser
{
/**
* @param string $data
* @return SimpleXMLElement
*/
public function parse(string $data)
{
// ...
}
}
class CsvParser
{
/**
* @param string $data
* @return string
*/
public function parse(string $data)
{
// ...
}
}
</code></pre>
<p>as result I rewrite it to following code:</p>
<pre><code><?php
interface FileHandlerInterface
{
/**
* @param string $type
* @param string $data
*
* @return array >>>> always return parsed data in one format
*/
public function parseString(string $type, string $data);
/**
* @param string $type
* @param resource $data
*
* @return array >>>> always return parsed data in one format
*/
public function parseStream(string $type, resource $data);
}
abstract class AbstractFileHandler implements FileHandlerInterface
{
/**
* @var ParserInterface[]
*/
private $parsers = [];
public function addParser(ParserInterface $parser)
{
$this->loaders[$parser->getAlias()] = $parser;
}
/**
* @param string $alias
* @return StringParserInterface
* @throws Exception
*/
public function getStringParser(string $alias)
{
if (!isset($this->parsers[$alias])) {
throw new Exception;
}
if (!($this->parsers[$alias] instanceof StringParserInterface)) {
throw new Exception;
}
return $this->parsers[$alias];
}
/**
* @param string $alias
* @return StreamParserInterface
* @throws Exception
*/
public function getStreamParser(string $alias)
{
if (!isset($this->parsers[$alias])) {
throw new Exception;
}
if (!($this->parsers[$alias] instanceof StreamParserInterface)) {
throw new Exception;
}
return $this->parsers[$alias];
}
}
class PriceFileHandler extends AbstractFileHandler
{
/**
* @param string $type
* @param string $data
*
* @return array
*/
public function parseString(string $type, string $data)
{
$parser = $this->getStringParser($type);
$parsedData = $parser->parse($data);
// remove items with price <= 0
foreach ($parsedData as $key => $parsedItem) {
if ($parsedItem['price'] <= 0) {
unset($parsedData[$key]);
}
}
return $parsedData;
}
/**
* @param string $type
* @param resource $data
*
* @return array
*/
public function parseStream(string $type, resource $data)
{
throw new Exception('doesn\'t support');
}
}
class FileHandler extends AbstractFileHandler
{
/**
* @param string $type
* @param string $data
*
* @return array
*/
public function parseString(string $type, string $data)
{
$parser = $this->getStringParser($type);
return $parser->parseString($data);
}
/**
* @param string $type
* @param resource $data
*
* @return array
*/
public function parseStream(string $type, resource $data)
{
$parser = $this->getStreamParser($type);
return $parser->parseStream($data);
}
}
interface ParserInterface
{
}
interface StringParserInterface
{
public function parseString(string $data);
}
interface StreamParserInterface
{
public function parseStream(resource $data);
}
class XmlParser implements ParserInterface, StringParserInterface, StreamParserInterface
{
/**
* @param string $data
* @return array
*/
public function parseString(string $data)
{
// ...
}
/**
* @param resource $data
* @return array
*/
public function parseStream(resource $data)
{
// ...
}
}
class CsvParser implements ParserInterface, StringParserInterface
{
/**
* @param string $data
* @return array
*/
public function parseString(string $data)
{
// ...
}
}
</code></pre>
<p>The interviewers said I broke these principles:</p>
<ul>
<li>SRP - perhaps about parsing from different sources in file handlers....</li>
<li>LSP - .... </li>
<li>OCP - ....</li>
</ul>
<p>Could someone describe where and why I've made mistakes or what I've done wrong and how to do it in correct way?</p>
<p>I've read and re-read principles with examples and don't see where I could broke LSP and OCP principles :(</p>
| [] | [
{
"body": "<h2>SRP</h2>\n<p>As you noticed too, this one is fairly clear, your grouping of different sources of data under a single parser interface violates the single responsibility principle. Ideally, you should have a single interface which has a generic method (<code>parse</code>) which all your classes can implement. If that's not possible as the signatures for each method might be different, you should create interfaces for each one and implement said interface.</p>\n<h2>LSP</h2>\n<p>LSP has been covered extensively in <a href=\"https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle\">this</a> SO post - which I advise that you take a look through. I have no intention to regurgitate what has previously been written, so again, I'll keep it brief. Liskov imposes certain standards, one of them being:</p>\n<blockquote>\n<p>No new exceptions should be thrown by methods of the subtype, except where those exceptions are themselves subtypes of exceptions thrown by the methods of the supertype.</p>\n</blockquote>\n<p>When you define the function <code>parseStream</code> in your interface <code>FileHandlerInterface</code>:</p>\n<pre><code>/**\n * @param string $type\n * @param resource $data\n *\n * @return array >>>> always return parsed data in one format\n */\npublic function parseStream(string $type, resource $data);\n</code></pre>\n<p>The return is specified as an array, it actually says <em>'always return parsed data in one format'</em>, so it seems that you were consciously aware of the principle but maybe in the heat of the moment you glanced over it further on. If we look in the <code>PriceFileHandler</code> class, you'll notice that you define the function with nothing but an exception as part of its body:</p>\n<pre><code>/**\n * @param string $type\n * @param resource $data\n *\n * @return array\n */\npublic function parseStream(string $type, resource $data)\n{\n throw new Exception('doesn\\'t support');\n}\n</code></pre>\n<p>Yet, the return type that is documented for <em>this</em> definition is an array too. This falls under the undesired effects category that LSP warns against.</p>\n<p>As far as OCP goes, I can't see anything right now, however, I'll revisit this again if I do see something.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:46:18.000",
"Id": "216707",
"ParentId": "216635",
"Score": "3"
}
},
{
"body": "<p>This question does not contain working code, a requirement of Code Review, and is more about programming principles. This is still an interesting question though. </p>\n\n<p>I have to admit I don't know much about SOLID principles, but I have been programming for decades, so these principles do make some sense to me. They are basic steps towards better code. These principles alone do, however, not produce good code. They are very abstract, and might be difficult to implement in practice. In my opinion code should first and foremost be easy to read/understand, and suited to the task at hand.</p>\n\n<p>So, let's first, before we refactor the code, think about what the code is supposed to do. That is not very clear. Perhaps there was a written introduction accompanying the code, which has been left out of this question? We have a class called <code>FileHandler</code> which parses data, probably from a file, using two different parser classes. That's very little information. The name of the <code>FileHandler</code> class doesn't even cover what it actually does. It doesn't actually handle any file. On the other hand, the vagueness gives us a lot of freedom.</p>\n\n<p>The first thing that is clearly wrong with the code is the way the parser classes are handled. Instead of handing over a certain parse class to the file handler, a <code>$type</code> parameter is given to the the <code>parse()</code> method. This probably breaks several of the SOLID principles. In my own simple words: Whenever a new parser class is created, the file handler class needs to be edited to make use of it. Let us therefore first correct this problem.</p>\n\n<pre><code>class FileHandler\n{\n public function __construct(string $filename, ParserInterface $parser)\n {\n $this->filename = $filename;\n $this->parser = $parser;\n }\n\n public function parse(string $data)\n {\n return $parser->parse($data);\n }\n}\n\ninterface ParserInterface\n{\n public function parse(string $data)\n}\n\nclass XmlParser implements ParserInterface\n{\n public function parse(string $data)\n {\n }\n}\n\nclass CsvParser implements ParserInterface\n{\n public function parse(string $data)\n {\n }\n}\n</code></pre>\n\n<p>Now this code looks a lot cleaner, and adheres, I hope, to the SOLID principles. Step 1 done. I left out all comments to shorten the code, but obviously you would add them in the real code.</p>\n\n<p>Now I didn't do much with the <code>FileHandler</code> class yet. That's because this is part of the next step: We should add a new file handler called <code>PriceFileHandler</code>. It would make sense to create a file handler interface and implement two handlers. Like this:</p>\n\n<pre><code>interface FileHandlerInterface\n{\n public function __construct(string $filename, ParserInterface $parser)\n public function parse(string $data)\n}\n\nclass FirstFileHandler implements FileHandlerInterface\n{\n public function __construct(string $filename, ParserInterface $parser)\n {\n $this->filename = $filename;\n $this->parser = parser;\n }\n\n public function parse(string $data)\n {\n return $parser->parse($data);\n }\n}\n\nclass PriceFileHandler implements FileHandlerInterface\n{\n public function __construct(string $filename, ParserInterface $parser)\n {\n $this->filename = $filename;\n $this->parser = parser;\n }\n\n public function parse(string $data)\n {\n return $parser->parse($data);\n }\n}\n</code></pre>\n\n<p>I agree that this looks boring, but then again, we have no idea yet, what to do with a file containing prices. This is abstract and incomplete code. There's only so much we can do before the code becomes completely unrecognizable. </p>\n\n<p>Finally we have to add 'supporting stream parsing to one parser implementation'. A stream in PHP is a resource object which exhibits streamable behavior. See: <a href=\"https://www.php.net/manual/en/intro.stream.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/intro.stream.php</a> So, given a stream, the parser class should parse it. Let's use the method <code>parseStream()</code> for this.</p>\n\n<pre><code>class XmlParser implements ParserInterface\n{\n public function parse(string $data)\n {\n }\n\n public function parseStream(string $filename)\n {\n $data = file_get_contents($filename);\n return $this->parse($data);\n }\n}\n</code></pre>\n\n<p>Is that all? Well, yeah. In the end, hidden inside PHP, streams are used by functions like <code>file_get_contents()</code>, so I used that. If the files get very big you would need to read the file in manageble chunks. That would require quite a bit more code than this question warrants. To be honest, I don't think this would be a good answer to the assignment.</p>\n\n<p>By now we should have notice that if we want to make use of the new <code>parseStream()</code> method we would have to extend a file handler, and probably the interfaces. It might make more sense to give a parser an abstract file handler, and let it parse that, than the other way around. That way we don't need a <code>parser()</code> method in the file handler at all, and it can do what it should be doing: handling a file. These classes would then better adhere to the Single Responsibility Principle (SRP). I think doing this here would be beyond the scope of this question. We have to work with what was given: Not much.</p>\n\n<p>I do realise that this answer doesn't answer all of your questions. It is how I would approach the code at hand. Correct coding requires deep knowledge of the domain it is applied to. Should the file handlers use a parser or should the parsers use a file handle? This depends on how the rest of the code will be structured. Normally it would be weird for file handlers to do the parsing, but what if that was the whole point of handling the files? In other words, there is no 100% correct solution to this assignment.</p>\n\n<p>The two follow up questions are difficult to answer, and they imply a certain solution to the first question. Perhaps the assignment is not a very good one?</p>\n\n<p>Priciples are often quite abstract, and therefore somewhat difficult to understand. Seeing refactoring, and my thought process, in action might help you. So instead of commenting on your code I made my own. I hope you find this helpful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-15T09:21:03.243",
"Id": "478784",
"Score": "0",
"body": "SRP and OCP are abstract. By contrast, LSP is very concrete and technical. So concrete that LSP violations could in many (all?) cases be found by an automatic checker."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:16:29.297",
"Id": "216713",
"ParentId": "216635",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:20:48.787",
"Id": "216635",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"design-patterns"
],
"Title": "SOLID principles breaking in interview task (file parser)"
} | 216635 |
<p>I have an assignment to solve this problem. However, I have exceeded the time limit required, can anyone suggest where to improve my code?</p>
<blockquote>
<p>Cats like to sit in high places. It is not uncommon to see cats
climbing trees or furniture in order to lie on the top-most area
within their feline reach. Rar the Cat is no exception. However, he
does not know how high is one area relative to another. </p>
<p>Height can be measured in centimeters (cm) above sea level but Rar the
Cat does not know the absolute height of any place. However, he knows
that area <strong>B_i</strong> will be higher than area <strong>A_i</strong> by
<strong>H_i</strong> centimetres because he needs to jump <strong>H_i</strong> to get from area <strong>A_i</strong> to <strong>B_i</strong> There will be <strong>N</strong> areas in total with <strong>N-1</strong> such descriptions. Areas are labelled from <strong>1</strong> to <strong>N</strong> and 0 < <strong>A,
B</strong> ≤ N where <strong>A ≠ B</strong>. Also, all <strong>H_i</strong> will satisfy the following
range 0 ≤ <strong>H_i</strong> ≤ 1,000,000. </p>
<p>Rar the Cat also has <strong>Q</strong> queries, each consisting 2 integers <strong>X</strong>
and <strong>Y</strong>. He wants to know the height of area Y with respect to area
X. Do note that 0 < <strong>X, Y</strong> ≤ <strong>N</strong> but <strong>X</strong> can be equal to <strong>Y</strong>.
In the event that area <strong>Y</strong> is lower than area <strong>X</strong>, please output a
negative number. Otherwise, output a positive number. </p>
<p>It is guaranteed that the relative heights of all pairs of areas can
be computed from the data provided in the input. To be precise, the
graph provided will be connected and has <strong>N-1</strong> edges connecting
<strong>N</strong> vertices in total. </p>
<p><strong>Input</strong></p>
<p>The first line of input will contain 1 integer, <strong>N</strong>.</p>
<p>The following <strong>N-1</strong> lines of input will contain 3 integers each,
with the i-th line containing <strong>A_i</strong>, <strong>B_i</strong> and <strong>H_i</strong>. The next
line will contain a single integer, <strong>Q</strong>.</p>
<p>The following <strong>Q</strong> lines will contain 2 integers each, <strong>X</strong> and
<strong>Y</strong>. </p>
<p><strong>Output</strong></p>
<p>For each line of query, you are supposed to output the relative
heights of area Y compared to area X, in centimeters, one line per
query.<br>
<strong>Limits</strong></p>
<p>• 0<<strong>N</strong>≤100,000 and 0 ≤<strong>Q</strong>≤100,000 </p>
<p><strong>Test Case 1</strong></p>
<pre><code>5
2 3 5
4 2 2
4 1 3
5 2 10
3
1 2
3 5
1 3
</code></pre>
<p><strong>Output</strong></p>
<pre><code>-1
-15
4
</code></pre>
<p>Explanation for Test Case Area 1 is 3 centimeters above Area 4 while
Area 2 is 2 centimeters above Area 4. Hence, Area 2 is 1 centimeters
below Area 1.</p>
<p>Area 2 is 10 centimeters above Area 5. Area 3 is 5 centimeters above
Area 2 and hence 15 centimeters above Area 5. As such, Area 5 is 15
centimeters below Area 3. </p>
<p>From the first query, Area 2 is 1 centimeters below Area 1. Area 3 is
5 centimeters above Area 2. As such, Area 3 is 4 centimeters above
Area 1.</p>
</blockquote>
<p><strong>My attempt</strong></p>
<pre><code>import java.util.*;
import java.util.stream.*;
public class Height {
private void run() {
Scanner sc = new Scanner(System.in);
int end = sc.nextInt();
String clear = sc.nextLine();
int count;
HashMap<Integer,HashMap<Integer,Integer>> map = new HashMap<>();
//searches the location of all edge using ends in O(1)
while (true) {//infinite loop because it seems to be waiting on a count command on the new line
String line = sc.nextLine();
String[] parts = line.split(" ");
if (parts.length==1) {//this is a count command to do bfs
count = Integer.parseInt(parts[0]);
break;
}
int src = Integer.parseInt(parts[0]);
int dst = Integer.parseInt(parts[1]);
int dist = Integer.parseInt(parts[2]);
map.putIfAbsent(src,new HashMap<>());
HashMap<Integer,Integer> accessed = map.get(src);
accessed.put(dst,dist);
map.putIfAbsent(dst,new HashMap<>());
accessed = map.get(dst);
accessed.put(src,-dist);
}
for (int i=0;i<count;i++) {
int src = sc.nextInt();
int dst = sc.nextInt();
bfs(map,src,dst);
}
}
public static void bfs(HashMap<Integer,HashMap<Integer,Integer>> map, int src, int dst) {
HashSet<Integer> visited = new HashSet<>();
visited.add(src);
Queue<Integer> frontier = new LinkedList<>();
frontier.add(src);
Queue<Integer> weights = new LinkedList<>();
weights.add(0);
while (!frontier.isEmpty()) {
src = frontier.poll();
int beforeMove = weights.poll();//get all weights accumulated so far
if (src==dst) {
System.out.println(beforeMove);
return;
}
for (int neighbour : new ArrayList<>(map.get(src).keySet())) {
if (!visited.contains(neighbour)) {//checks if node is travelled in O(1)
visited.add(neighbour);
frontier.add(neighbour);
weights.add(beforeMove+map.get(src).get(neighbour));
}
}
}
}
public static void main(String[] args) {
Height newHeight = new Height();
newHeight.run();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:52:46.873",
"Id": "419059",
"Score": "0",
"body": "From the restrictions given, you may be forced to do up to one hundred thousands searches across a one hundred thousands nodes graph. That doesn't look good. You should optimize your data. The input data defines a [partial order](https://en.wikipedia.org/wiki/Partially_ordered_set) on a set of levels. I think you could reconstruct a linear order on it with a [topological sorting](https://en.wikipedia.org/wiki/Topological_sorting). Then you should be able to quickly calculate all levels diffs, then every query would be answered immediately."
}
] | [
{
"body": "<p>Your biggest mistake is running the search for every query, a separate query phase almost always means you have to build an intermediate data structure, e.g. an array of height for this problem.</p>\n\n<p>When building a spanning tree, or doing an equivalent operation, use DFS.\nDo a depth first traversal, starting with node 1 and calculating relative heights as you go. Record these heights in an array. During the query phase look up heights from the array and return their difference.</p>\n\n<p>DFS to BFS is like quicksort to mergesort, don't use BFS unless you have a reason to. Even when traversing infinite graphs DFS with iterative deepening provides better performance.</p>\n\n<p>Note you should use a stack and not recursion for more than a few thousand (a few hundred really) nodes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T15:37:25.233",
"Id": "419094",
"Score": "0",
"body": "Thanks for your answer, I will try it out. Your point about using a Data Structure stack in preference of recursion interests me, as there was once I did recursion instead of a stack and I exceeded a time limit for one of my code. Would you mind explaining why that is the case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T15:58:46.753",
"Id": "419095",
"Score": "0",
"body": "Evaluation machines get stackoverflow error for about thousands of recursion depth (depending on their settings). You may also allocate more memory than needed for unused local variables etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:51:38.823",
"Id": "216658",
"ParentId": "216636",
"Score": "1"
}
},
{
"body": "<p>Code to the interface, not the implementation. It should be very rare to see <code>HashMap</code> or <code>HashSet</code> other than immediately following the keyword <code>new</code>.</p>\n\n<blockquote>\n<pre><code> Queue<Integer> frontier = new LinkedList<>();\n</code></pre>\n</blockquote>\n\n<p>is good.</p>\n\n<blockquote>\n<pre><code> HashMap<Integer,HashMap<Integer,Integer>> map = new HashMap<>();\n</code></pre>\n</blockquote>\n\n<p>should be changed to</p>\n\n<pre><code> Map<Integer,Map<Integer,Integer>> map = new HashMap<>();\n</code></pre>\n\n<hr>\n\n<p><code>run</code> is not static: <code>bfs</code> is static. Why?</p>\n\n<p>I would favour making the code more OO: make <code>map</code> a field of the class; add a method <code>addEdge</code> to do the updates to <code>map</code>; make <code>bfs</code> non-static and remove <code>map</code> from its parameters; and rename <code>bfs</code> to something which tells you <em>what</em> it does rather than <em>how</em> it does it, such as <code>processQuery</code>.</p>\n\n<hr>\n\n<p>The input parsing is quite ugly because it doesn't take into account the clear statement of the specification that there will be N-1 edges in the graph. With the refactors suggested in my previous point, it can be as simple as</p>\n\n<pre><code> private void run() {\n Scanner sc = new Scanner(System.in);\n\n int n = sc.nextInt();\n for (int i=0;i<n-1;i++) {\n int src = sc.nextInt();\n int dst = sc.nextInt();\n int dist = sc.nextInt();\n addEdge(src,dst,dist);\n }\n\n int count = sc.nextInt();\n for (int i=0;i<count;i++) {\n int src = sc.nextInt();\n int dst = sc.nextInt();\n processQuery(src,dst);\n }\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> Queue<Integer> frontier = new LinkedList<>();\n frontier.add(src);\n Queue<Integer> weights = new LinkedList<>();\n weights.add(0);\n</code></pre>\n</blockquote>\n\n<p>As far as I can see, this is a brittle implementation of</p>\n\n<pre><code>Queue<Pair<Integer,Integer>> frontierWithWeights = new LinkedList<>();\n</code></pre>\n\n<p>Implementing a pair class would be worthwhile for the improved clarity; even abusing <code>Map.Entry<Integer,Integer></code> would make the code easier to understand.</p>\n\n<p>But actually that's unnecessary. Provided that you store the number of vertices, <code>weights</code> could be an <code>int[]</code>.</p>\n\n<p><code>visited</code> is completely unnecessary because the spec guarantees that the edges form a spanning tree.</p>\n\n<hr>\n\n<p>An alternative approach, which would be faster for some use cases, would be to run the search to completion once such that each query can be processed in constant time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T10:53:30.553",
"Id": "219096",
"ParentId": "216636",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:31:51.967",
"Id": "216636",
"Score": "7",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded",
"graph"
],
"Title": "Heights of Cats"
} | 216636 |
<p>How to beautify this part of code? (I mean usage of promise in promise) I really have no clue how this could've look like.</p>
<pre><code> function zoom(projectId) {
Service.useZoomToProject(projectId).then(
function (useZoomToTask) {
if (useZoomToTask) {
CrmDataServices.getProjectTaskId(projectId).then(
function (taskId) {
zoomByTask(taskId);
});
} else {
zoomByComment(projectId);
}
}
);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:52:50.500",
"Id": "419054",
"Score": "0",
"body": "you may use async/await that looks more clean :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:13:12.730",
"Id": "419056",
"Score": "0",
"body": "Oh, you're right, unfortunately, it isn't supported on all browsers (e.g. internet explorer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:48:16.440",
"Id": "419058",
"Score": "0",
"body": "That is where transpilers use to help you better use one so you can enjoy full strength of new JS features :)\nNot that complex to setup with webpack"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:58:02.750",
"Id": "419060",
"Score": "0",
"body": "Take a look of following article and to know about polyfill used to add features to old browsers : https://zellwk.com/blog/older-browsers-js/"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:40:49.043",
"Id": "216637",
"Score": "1",
"Tags": [
"javascript",
"promise"
],
"Title": "Using promises to zoom to a project, then to a task or comment"
} | 216637 |
<p>I must to model Document class. I receive document as bytes array.
I can receive pdf, zip, text and xml documents. After few operation I must store documents. If document is in xml format I can get some nodes or transform it by xlst and then store.How can I improve my code? Is it good idea to use here builder or factory method patterns?</p>
<pre><code> class Program
{
static void Main(string[] args)
{
string document1 = "<document>Content</document>";
byte[] document2 = new byte[] { 80, 65, 78, 75, 65, 74 };
byte[] document3 = new byte[] { 8, 68, 78, 78, 60, 73 };
var document1Binary = Encoding.UTF8.GetBytes(document1);
var binaryDocumentDetails = new DocumentDetails(1, "DefaultXml.xml", DocFormat.Xml, DocType.External);
var documentXml = new XmlDocument(document1Binary, binaryDocumentDetails, "Test.xml");
var binaryDocumentDetails1 = new DocumentDetails(1, "DefaultBinary.bin", DocFormat.Bin, DocType.Inner);
var binaryDocument1 = new BinaryDocument(document2, Encoding.UTF8, binaryDocumentDetails1, "Test.bin");
var binaryDocumentDetails2 = new DocumentDetails(1, "DefaultPdf.pdf", DocFormat.Bin, DocType.Inner);
var binaryDocument2 = new BinaryDocument(document2, Encoding.UTF8, binaryDocumentDetails2, "TestDocument.pdf");
var documentRepository = new List<BinaryDocument>();
documentRepository.Add(documentXml);
documentRepository.Add(binaryDocument1);
documentRepository.Add(binaryDocument2);
}
}
public enum DocFormat { Bin, Xml }
public enum DocType { Inner, External }
public enum Compression { Gzip, Zip}
public class DocumentDetails
{
public byte DocTypeId { get; set; }
public string DefaultFileName { get; }
public string FileExtension { get; set; }
public DocFormat Format { get; set; }
public DocType FormType { get; set; }
public DocumentDetails(byte docTypeId, string defaultFileName, DocFormat format, DocType formType)
{
DocTypeId = docTypeId;
DefaultFileName = defaultFileName;
Format = format;
FormType = formType;
}
}
public abstract class Document
{
public byte[] Body { get; protected set; }
public string FileName { get; private set; }
public Encoding Encoding { get; protected set; }
protected Document(byte[] body, string fileName, Encoding encoding)
{
Body = body;
Encoding = encoding;
FileName = fileName;
}
public void ChangeContent(Document sourceDocument)
{
Body = sourceDocument.Body;
Encoding = sourceDocument.Encoding;
FileName = sourceDocument.FileName;
}
}
public class BinaryDocument : Document
{
public bool IsActive { get; set; }
public bool AllowOverwrite { get; set; }
public Compression Compression { get; set; }
public DocumentDetails DocumentDetails { get; set; }
public BinaryDocument(byte[] content, DocumentDetails documentDetails, string fileName) : this(content, Encoding.UTF8, documentDetails, fileName)
{
}
public BinaryDocument(byte[] content, Encoding encoding, DocumentDetails documentDetails, string fileName) : base(content, fileName, encoding)
{
IsActive = true;
DocumentDetails = documentDetails;
}
protected BinaryDocument(BinaryDocument binaryDocument) : base(binaryDocument.Body, binaryDocument.FileName, binaryDocument.Encoding)
{
IsActive = binaryDocument.IsActive;
AllowOverwrite = binaryDocument.AllowOverwrite;
Compression = binaryDocument.Compression;
DocumentDetails = binaryDocument.DocumentDetails;
}
public void UpdateCompression(Compression compression)
{
Compression = compression;
}
public void UpdateDocumentDetails(DocumentDetails documentDetails)
{
DocumentDetails = documentDetails;
}
public string GetContentAsString()
{
return Encoding.GetString(Body);
}
public void UpdateDocument(byte[] body, Encoding encoding)
{
Body = body;
Encoding = encoding;
}
}
public class XmlDocument : BinaryDocument
{
public XDocument LoadedXmlDocument { get; set; }
public XmlDocument(byte[] content, DocumentDetails documentForm, string fileName) : base(content, documentForm, fileName)
{
LoadedXmlDocument = Load();
}
public XmlDocument(byte[] content, Encoding encoding, DocumentDetails documentForm, string fileName) : base(content, encoding, documentForm, fileName)
{
LoadedXmlDocument = Load();
}
public XmlDocument(BinaryDocument documentPart)
: this(documentPart.Body, documentPart.Encoding, documentPart.DocumentDetails, documentPart.FileName)
{
}
private XDocument Load()
{
XDocument loadedXml;
using (var ms = new MemoryStream(Body))
{
using (var xr = XmlReader.Create(ms))
{
loadedXml = XDocument.Load(xr);
}
}
return loadedXml;
}
public static bool TryParse(BinaryDocument documentPart)
{
bool result = true;
var readerSettings = new XmlReaderSettings
{
ConformanceLevel = ConformanceLevel.Document,
CheckCharacters = true,
ValidationType = ValidationType.None
};
var stream = documentPart.GetContentAsString();
try
{
using (var reader = XmlReader.Create(stream, readerSettings))
{
while (reader.Read()) { }
}
}
catch
{
result = false;
}
return result;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T06:50:00.230",
"Id": "419176",
"Score": "0",
"body": "Do you have other document types than `BinaryDocument` that derives from `Document`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T07:02:59.583",
"Id": "419179",
"Score": "0",
"body": "No, It's only BinaryDocument class"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:06:39.843",
"Id": "419218",
"Score": "0",
"body": "It's a good question, but I think, your use case is poor. You write, that you receive the data as byte arrays, but you show `document1` as a string. It's also unclear from where you have or how you determine the metadata for each document. Could you provide an example that is a little more like the actual use?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T09:48:19.713",
"Id": "216638",
"Score": "3",
"Tags": [
"c#",
"beginner"
],
"Title": "Document class for various formats"
} | 216638 |
<p>I tried to solve a symmetric tree problem </p>
<blockquote>
<p>Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).</p>
<p>For example, this binary tree <code>[1,2,2,3,4,4,3]</code> is symmetric:</p>
<pre><code> 1
/ \
2 2
/ \ / \
3 4 4 3
</code></pre>
<p>But the following <code>[1,2,2,null,3,null,3]</code> is not:</p>
<pre><code> 1
/ \
2 2
\ \
3 3
</code></pre>
<p><strong>Note:</strong>
Bonus points if you could solve it both recursively and iteratively.</p>
</blockquote>
<p>My solution with recursion</p>
<pre><code># Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
if not root: return True #None is symmetic
return self.isMirror(root.left, root.right)
def isMirror(self, l, r):
if not l and not r: return True #base case 1
if not l or not r: return False #base case 2
if l.val != r.val: return False #base case 3
#recur case
left = self.isMirror(l.left, r.right)
right = self.isMirror(l.right, r.left)
return left and right
</code></pre>
<p>I assumed it as a decent solution to this problem but get a low score</p>
<blockquote>
<p>Runtime: 32 ms, faster than 24.42% of Python online submissions for Symmetric Tree.
Memory Usage: 12.2 MB, less than 5.08% of Python online submissions for Symmetric Tree.</p>
</blockquote>
<p>How could improve the my solution?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T11:33:37.967",
"Id": "419064",
"Score": "0",
"body": "You present input data both as a list and as a tree. Which one is the actual input form? If it is a list of integers, possibly you could do a recursive analysis just on that list and save the time needed for constructing a tree of linked `TreeNode` objects?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T12:46:16.750",
"Id": "419067",
"Score": "0",
"body": "You 'accepted' my answer, which should confirm my modification is correct and resolves your problem. If so, do you mind to share the scores your modified algorithm achieves?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:16:05.830",
"Id": "419074",
"Score": "0",
"body": "Where are you submitting these answers to get rankings like this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:37:10.273",
"Id": "419102",
"Score": "0",
"body": "@Shawson Possibly it's [Geeks for geeks](https://www.geeksforgeeks.org/symmetric-tree-tree-which-is-mirror-image-of-itself/)? Or may be the [LeetCode](https://leetcode.com/problems/symmetric-tree/)?"
}
] | [
{
"body": "<p>Possibly the most obvious part is here</p>\n\n<pre><code> left = self.isMirror(l.left, r.right)\n right = self.isMirror(l.right, r.left)\n return left and right\n</code></pre>\n\n<p>there's no need to perform the second test if the first one returns <code>False</code>:</p>\n\n<pre><code> if not self.isMirror(l.left, r.right): return False\n if not self.isMirror(l.right, r.left): return False\n\n return True\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T11:01:20.280",
"Id": "216642",
"ParentId": "216641",
"Score": "1"
}
},
{
"body": "<p>Appart from the optimization provided by <a href=\"https://codereview.stackexchange.com/a/216642/84718\">@CiaPan</a>, you could try using an inner function to reduce the need for attributes lookups and accelerate symbols resolution speed:</p>\n\n<pre><code>class Solution(object):\n def isSymmetric(self, root):\n if root is None:\n return True\n\n def isMirror(left, right):\n if left is None and right is None:\n return True\n elif left is None or right is None:\n return False\n elif left.val != right.val:\n return False\n else:\n return isMirror(left.left, right.right) and isMirror(left.right, right.left)\n\n return isMirror(root.left, root.right)\n</code></pre>\n\n<p>Alternatively, you could try the iterative approach which is usually implemented using a <code>deque</code> to perform a breadth first search:</p>\n\n<pre><code>from collections import deque\n\n\nclass Solution(object):\n def isSymmetric(self, root):\n if root is None:\n return True\n\n rights = deque([root.right])\n lefts = deque([root.left])\n while lefts:\n left = lefts.popleft()\n right = right.popleft()\n if left is None and right is None:\n pass\n elif left is None or right is None:\n return False\n elif left.val != right.val:\n return False\n else:\n lefts.append(left.left)\n lefts.append(left.right)\n rights.append(right.right)\n rights.append(right.left)\n\n return True\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:14:01.930",
"Id": "419970",
"Score": "0",
"body": "As it often happens, optimization needs to fit the actual data characteristics. With BSF one should remember that a full binary tree has \\$ 2^d \\$ items at the level of depth \\$d\\$ , so the queue can grow much faster (and larger) than a stack. On the other hand with DSF a stack can grow huge if the tree is degenerated to a list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:01:35.207",
"Id": "216665",
"ParentId": "216641",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216642",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T10:36:16.463",
"Id": "216641",
"Score": "5",
"Tags": [
"python",
"performance",
"algorithm",
"tree"
],
"Title": "A recursive solution to symmetirc tree"
} | 216641 |
<p>This is my rewrite of the program <a href="https://codereview.stackexchange.com/questions/216569/pure-bash-program-for-auto-filling-a-template-file-with-env-variables">posted here</a>, based on janos's comments. I also added the ability to read from stdin.</p>
<p>I've also included a test script. I wanted something lightweight I could easily re-run, but didn't want a dependency or full test framework like bats. Comments on the test script are also welcome.</p>
<h2>New Program</h2>
<pre><code>#!/bin/bash
set -euo pipefail
die() {
printf '%s\n' "$1" >&2
exit 1
}
show_help() {
>&2 echo "Usage:
$ $0 <filename>
The program will read from stdin if <filename> is not given.
Description:
Fills in template files with ENV variables. <filename> is assumed to be a
template file whose variables are enclosed in double braces like:
Some content with {{ MY_VAR1 }}
or {{ MY_VAR1 }} and {{ MY_VAR2 }}
where MY_VAR1 and MY_VAR2 and ENV variables. Assuming that the ENV variables
are set:
$ export MY_VAR1=value_1
$ export MY_VAR2=value_2
then executing this script on a file with the above content will output:
Some content with value_1
or value_1 and value_2
"
}
if [[ $# -gt 0 && ( $1 = '-h' || $1 = '--help' ) ]]; then
show_help
exit 0
fi
# If given, ensure arg is a file:
if [[ $# -gt 0 && ! -f $1 ]]; then
die "'$1' is not a file."
fi
# If we're reading from stdin, save its contents to a temp file
# This is because we need to read it twice: first to extract
# the required vars, then again to replace them.
if [[ $# -eq 0 ]]; then
# Read stdin into a temp file
tmpfile=$(mktemp)
cat /dev/stdin > "$tmpfile"
# Clean it up, saving to FDs to read from
exec 3< "$tmpfile"
exec 4< "$tmpfile"
rm "$tmpfile"
else
exec 3< "$1"
exec 4< "$1"
fi
# Gather all the required template variables
vars=()
while IFS= read -r line; do
vars+=( "$line" )
done < <( grep -Eo '\{\{ ([-_[:alnum:]]*) }}' <&3 | \
grep -Eo '([-_[:alnum:]]*)' | \
sort -u )
# Verify that all template variables exist
missing=()
for var in "${vars[@]}"; do
if [[ -z ${!var+x} ]]; then
missing+=( "$var" )
fi
done
if [[ ${#missing[@]} -gt 0 ]]; then
>&2 echo "The following required variables have not been exported:"
for var in "${missing[@]}"; do
>&2 echo "${var}"
done
exit 1
fi
# Dynamically construct the sed cmd to do the replacement
sed_cmd=
for var in "${vars[@]}"; do
# sanitize the user's input (ie, the var's value) by prepending a backslash
# to our sed delimiter (#) as well as to backslashes themselves, to prevent
# the input from being interpreted by sed as a special character like a
# backreference (\1) or a tab (\t), etc
escaped_val=$(printf "%s" "${!var}" | sed -E 's|([#\])|\\\1|g')
sed_cmd+="s#\\{\\{ ${var} }}#${escaped_val}#g;"
done
sed -E "${sed_cmd}" <&4
</code></pre>
<h2>Test Script</h2>
<pre><code>#!/bin/bash
# shellcheck disable=SC2030,SC2031
# disabling because we're modifying in a subshell by design
set -euo pipefail
# Do everything in a sub-process to keep parent process clean
(
new_test() {
echo "$1"
unset MY_VAR1
unset MY_VAR2
}
basic_tmpl='
hello there {{ MY_VAR1 }}
some other stuff
foo: {{ MY_VAR2 }}
line with both: {{ MY_VAR1 }} and {{ MY_VAR2 }}'
# Each test goes in a subshell too
(
new_test "Should error when tmpl variables are missing"
printf "%s" "$basic_tmpl" | ./fill_template 2>/dev/null \
&& echo 'FAIL' || echo 'PASS'
)
(
new_test "Should succeed when tmpl variables are set"
export MY_VAR1=val1
export MY_VAR2=val2
printf "%s" "$basic_tmpl" | ./fill_template >/dev/null 2>&1 \
&& echo 'PASS' || echo 'FAIL'
)
(
new_test "Basic template should produce expected output"
export MY_VAR1=val1
export MY_VAR2=val2
result=$(printf '%s' "$basic_tmpl" | ./fill_template 2> /dev/null)
expected='
hello there val1
some other stuff
foo: val2
line with both: val1 and val2'
[[ "$result" = "$expected" ]] && echo 'PASS' || echo 'FAIL'
)
(
new_test "Values with spaces/slashes/metachars still work"
export MY_VAR1='/some/path/and_\1_\t+\_'
export MY_VAR2='blah _\\_ baz'
result=$(printf '%s\n\n' "$basic_tmpl" | ./fill_template 2> /dev/null)
expected='
hello there /some/path/and_\1_\t+\_
some other stuff
foo: blah _\\_ baz
line with both: /some/path/and_\1_\t+\_ and blah _\\_ baz'
[[ "$result" = "$expected" ]] && echo 'PASS' || echo 'FAIL'
)
)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T08:56:13.807",
"Id": "419531",
"Score": "0",
"body": "Can you clarify what you mean by \"pure\" Bash? I assumed it meant using only builtins, but I see `grep`, `sed`, `mktemp`, `sort` and more. `sed` in particular, being a program interpreter, seems far from any definition of \"pure Bash\" than I can conceive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T13:45:19.867",
"Id": "419570",
"Score": "0",
"body": "sed, awk, etc are fine."
}
] | [
{
"body": "<p>The <code>grep</code> matches a lot of strings that can't be valid bash identifiers (\"<em>alphanumeric characters and underscores, beginning with an alphabetic character or an underscore</em>\"). There are some magical exceptions like <code>$*</code> and <code>$@</code> but I'm assuming you aren't trying to support those in your templates.</p>\n\n<p>Reading inputs twice is not necessary; a single-pass approach would remove a lot of complexity from your program, and make it possible to process infinitely large inputs on STDIN. The only real drawback is that it will exit on the first undefined value, instead of producing a list.</p>\n\n<p>And finally, everyone has their own definitions, but—to me—\"pure bash\" means \"without the use of external programs.\" Making your program meet this bar not only makes it faster, it removes even more complexity, because you don't need to filter values through an external program that might misunderstand them. It also means your template values need not be exported. They only need to be visible to the current shell.</p>\n\n<p>This version, implemented as a function, uses only bash builtins and passes your tests once <code>./fill_template</code> is replaced by <code>fill_template</code>:</p>\n\n<pre><code>fill_template() {\n (( ${#@} )) || set -- /dev/stdin\n local file line eof original name value\n for file; do\n while true; do\n read -r line\n eof=$?\n while [[ $line =~ \\{\\{\" \"*([a-zA-Z_][_a-zA-Z0-9]*)\" \"*\\}\\} ]]; do\n original=$BASH_REMATCH\n name=${BASH_REMATCH[1]}\n value=${!name?\"unset template variable: $name\"}\n line=${line//$original/$value}\n done\n printf -- %s \"$line\"\n (( eof )) && break || printf \"\\n\"\n done <$file\n done\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T01:06:50.160",
"Id": "419157",
"Score": "1",
"body": "Very nice. I do still like the idea of printing out all missing ENV vars (I think it will be an easy thing to forget when using the script) but I much prefer the simplicity of the single pass. I'm thinking a better design would be a single pass like your suggestion as the default (with die on first error), and then a separate option to list all missing vars."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T22:54:38.160",
"Id": "419390",
"Score": "0",
"body": "You could switch modes on error -- proceed normally until the first failure; on failure set a flag that suppresses normal template output and only prints the names of unset variables."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:35:10.363",
"Id": "216668",
"ParentId": "216644",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T11:19:42.717",
"Id": "216644",
"Score": "5",
"Tags": [
"bash"
],
"Title": "Pure bash program for auto-filling a template file (Part 2)"
} | 216644 |
<p>I would like to optimize the below <code>traceback</code> function. This function is part of an elementary step of the program and is called a lot...</p>
<pre><code>import numpy as np
def traceback(tuple_node, tuple_node_alt):
"""
Compute which value from tuple_node_alt comes from which value from tuple_node.
Return a dictionnary where the key are the values from tuple_node and the values are the idx at which
the value may be located in tuple_node_alt.
"""
# Compute the tolerances based on the node
tolerances = [0.1 if x <= 100 else 0.2 for x in tuple_node]
# Traceback
distance = dict()
alt_identification = dict()
for k, x in enumerate(tuple_node):
distance[k] = [abs(elt-1) for elt in [alt_x/x for alt_x in tuple_node_alt]]
alt_identification[x] = list(np.where([elt <= tolerances[k]+0.00001 for elt in distance[k]])[0])
# Controls the identification and corrects it
len_values = {key: len(val) for key, val in alt_identification.items()}
if all([x <= 1 for x in len_values.values()]):
return alt_identification
else:
for key, value in alt_identification.items():
if len(value) <= 1:
continue
else:
other_values = [val for k, val in alt_identification.items() if k != key]
if value in other_values:
continue
else:
for val in other_values:
set1 = set(value)
intersec = set1.intersection(set(val))
if len(intersec) == 0:
continue
else:
alt_identification[key] = [v for v in value if v not in intersec]
return alt_identification
</code></pre>
<p>The input is composed of 2 tuples which do not need to have the same size. e.g.</p>
<pre><code>tuple_node = (40, 50, 60, 80)
tuple_node_alt = (87, 48, 59, 39)
</code></pre>
<p>The goal is to figure out which value from <code>tuple_node_alt</code> may come from which value from <code>tuple_node</code>. If the value from <code>tuple_node_alt</code> is within a 10% margin from a value from <code>tuple_node</code>, it is considered that it comes from this value.</p>
<p>e.g. 39 is within a 10% margin of 40. It comes from 40.
This aprt is perform in the "Traceback" section, where a distance dictionnary is computed and where the idx are computed. With the example above, the output is:</p>
<pre><code>Out[67]: {40: [3], 50: [1], 60: [2], 80: [0]}
</code></pre>
<p>However, because of a potential overlapping of the tolerance band, 3 scenarios exists:</p>
<p><strong>Scenario 1</strong>: each value has been identified to one alternative value. That's the case above.</p>
<p><strong>Scenario 2:</strong> </p>
<pre><code>tuple_node = (40, 50, 60, 80)
tuple_node_alt = (42, 55, 54)
</code></pre>
<p>55 and 54 are both in the tolerance band of both 50 and 60. Thus, the output is:</p>
<pre><code>Out[66]: {40: [0], 50: [1, 2], 60: [1, 2], 80: []}
</code></pre>
<p><strong>Scenario 3:</strong> </p>
<pre><code>tuple_node = (40, 50, 60)
tuple_node_alt = (42, 55, 59)
</code></pre>
<p>This is when the control part comes in play. With this input, <code>alt_identification</code> becomes: <code>Out[66]: {40: [0], 50: [1], 60: [1, 2], 80: []}</code>. However, the 55 can not come from 60 since 50 only has one possibility: 55. Thus, this number being already taken, the correct output which is provided through the control & correct section is:</p>
<pre><code>Out[66]: {40: [0], 50: [1], 60: [2], 80: []}
</code></pre>
<p>I would really like to optimize this part and to make it a lot more quicker. At the moment, it takes:</p>
<pre><code># With an input which does not enter the control & correct part.
node = (40, 50, 60, 80)
node_alt = (39, 48, 59, 87)
%timeit traceback(node, node_alt)
22.6 µs ± 1.04 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
# With an input which need correction
node = (40, 50, 60, 100)
node_alt = (42, 55, 59, 89)
%timeit traceback(node, node_alt)
28.1 µs ± 1.88 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code></pre>
| [] | [
{
"body": "<p>A couple of low-hanging fruit inefficiencies:</p>\n\n<ol>\n<li><code>distance = dict()</code>. The <code>distance[k]</code> value is computed in a loop, and only every used in the next statement of the loop. It does not need to be stored in a dictionary.</li>\n<li><code>all([ ...list comprehension... ])</code>: You are using list comprehension to build up a list, which you immediately pass to <code>all(...)</code>. There is no need to actually create the list. Just use <code>all(...list comprehension...)</code>.</li>\n<li><code>set1 = set(value)</code>. This is inside a <code>for val in other_values:</code> loop, where <code>value</code> and <code>set1</code> are not changed. Move the statement out of the <code>for</code> loop, to avoid recreating the same set each iteration.</li>\n<li><p><code>len_values</code> is only used in the afore mentioned <code>all(...)</code>, and only the the values of <code>len_values</code> dictionary are used. As such, the <code>len_value</code> dictionary construction is also unnecessary, and the <code>if</code> statement can be written:</p>\n\n<pre><code>if all(len(val) <= 1 for val in alt_identification.values()):\n</code></pre></li>\n</ol>\n\n<hr>\n\n<p>Since you are returning <code>alt_identification</code> from the <code>if</code> statement, and after the <code>if...else</code> statement, you can invert the test, and remove one return statement:</p>\n\n<pre><code>if any(len(val) > 1 for val in alt_identification.values()):\n for key, value in alt_identification.items():\n # ... omitted for brevity ...\n\nreturn alt_identification\n</code></pre>\n\n<p>Similarly, the two <code>if condition: continue else:</code> could be re-written <code>if not condition:</code>. </p>\n\n<hr>\n\n<p>Other possible improvements:</p>\n\n<ul>\n<li><code>tolerances[k]</code> is only used in next <code>for k</code> loop. The list can be removed and the calculations move into the loop.</li>\n<li><code>numpy</code> is only used for a <code>list(np.where([...])[0])</code> operation, which is fairly obfuscated. A simple list comprehension can be used instead.</li>\n<li>The values of <code>alt_identification</code> are of type <code>list</code>, and converted (repeatedly) into a <code>set()</code> in the \"control & correct\" code. They could be stored as <code>set()</code> to avoid repeated conversions.</li>\n</ul>\n\n<p>Here is my rework of the code, with the changes based on above comments:</p>\n\n<pre><code>def traceback(tuple_node, tuple_node_alt):\n\n def close_alternates(x):\n tolerance = (0.1 if x <= 100 else 0.2) + 0.00001\n return set( k for k, alt_x in enumerate(tuple_node_alt)\n if abs(alt_x/x - 1) <= tolerance )\n\n alt_identification = { x: close_alternates(x) for x in tuple_node } \n\n if any(len(val) > 1 for val in alt_identification.values()):\n for key, values in alt_identification.items():\n if len(values) > 1:\n other_values = [val for k, val in alt_identification.items() if k != key]\n if values not in other_values:\n for other in other_values:\n alt_identification[key] -= other\n\n return alt_identification\n</code></pre>\n\n<p>I'm getting up to a 2.8x speedup with the above code, on your test data set that require correction.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:37:36.213",
"Id": "216670",
"ParentId": "216646",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216670",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T11:23:58.183",
"Id": "216646",
"Score": "2",
"Tags": [
"python",
"performance",
"numpy"
],
"Title": "Function figuring out which close-by value comes from which input value"
} | 216646 |
<p>The task:</p>
<blockquote>
<p>Given a list of elements, find the majority element, which appears
more than half the time (> floor(len(lst) / 2.0)).</p>
<p>You can assume that such element exists.</p>
<p>For example, given [1, 2, 1, 1, 3, 4, 0], return 1.</p>
</blockquote>
<p>My solution:</p>
<pre><code>const lst = [1, 2, 1, 1, 3, 4, 0];
const findMajorityElem = lst => lst.reduce((acc, x) => {
acc[x] = acc[x] ? acc[x] + 1 : 1;
// If I can assume that such an element exists, then it's sufficient to check which element occurs the most.
if (!acc.major || acc.major[1] < acc[x]) { acc.major = [x, acc[x]]; }
return acc;
}, {major: null}).major[0];
console.log(findMajorityElem(lst));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T16:47:03.987",
"Id": "419098",
"Score": "5",
"body": "In the example `[1, 2, 1, 1, 3, 4, 0]`, 1 appears 3 times, `floor(len(lst) / 2.0))` is 3, and since 3 is not more than 3, therefore 1 is *not* the majority element, and the example list doesn't have a majority element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T16:54:12.777",
"Id": "419099",
"Score": "0",
"body": "@janos the example is inaccurate. However it explicitly says I can assume that there exists a majority element"
}
] | [
{
"body": "<p>If it is known that a majority element exists, then the efficient algorithm to use is the <a href=\"https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm\" rel=\"noreferrer\">Boyer-Moore majority vote algorithm</a>, which requires only O(1) space.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:44:38.343",
"Id": "419139",
"Score": "2",
"body": "That's a little deceptive... it's $\\Omega(\\log n)$ space in terms of bit complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T01:18:06.930",
"Id": "419159",
"Score": "2",
"body": "@Charles Why would you want to break it down in terms of bits?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T01:59:26.837",
"Id": "419162",
"Score": "1",
"body": "I think the question should be, why hide the size of the space requirements? Calling O(1) is, IMO, deceptive: it makes it sound like a fixed amount of space suffices for arbitrarily large arrays, but the larger the array the larger the numbers you need to store, and the larger the numbers the larger the space they take up. Sure, only logarithmically so, but then let's call it logarithmic space, not constant space. It's only constant space in the sense that you use a constant number of _words_ when the words themselves grow logarithmically, but then you're being tricky and hiding the real size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T02:31:54.227",
"Id": "419163",
"Score": "1",
"body": "@Charles I don't understand why there's necessarily a correlation between the size of the array and the size of the values within it. To me those are completely orthogonal concerns. It also doesn't seem particularly relevant here anyway, since Javascript's numbers are fixed-size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:35:01.920",
"Id": "419188",
"Score": "0",
"body": "@Kyle I think he means the size of the counter. It could become as large as the length of the array, which can't be a problem for any array traversable in a realistic time though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T14:17:08.267",
"Id": "419238",
"Score": "1",
"body": "@Charles I don’t think that’s entirely fair. Unlike algorithms and structures that meaningfully depend on bit width (radix sort, van Emde Boas trees, ...), this one only has a dependence on it in that it needs to store an array index and an array element (an offline version can also get away with storing two indices instead). That is, it needs as much space as an array access, and you generally want to count this as O(1). Yes, that means you’re counting words, not bits, but that’s the standard cost model, and it makes perfect sense outside of specialized applications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:27:58.933",
"Id": "419246",
"Score": "0",
"body": "@AlexShpilkin I think the standard cost model is bits, but each to her/his own."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T12:38:57.907",
"Id": "216650",
"ParentId": "216648",
"Score": "14"
}
},
{
"body": "<p>@200_success's suggestion seems like the right play here.</p>\n\n<p>That said, I thought it was worth pointing out a couple small improvements to your approach:</p>\n\n<ul>\n<li><code>major</code> need only be the element itself (since you can look up its value in the accumulator)</li>\n<li>Since you tagged this <code>functional-programming</code>, you can use expressions everywhere, and avoid the <code>if</code> statement.</li>\n</ul>\n\n<p>Revised code:</p>\n\n<pre><code>const findMajorityElem = lst => lst.reduce((acc, x) => {\n acc[x] = acc[x] ? acc[x] + 1 : 1;\n const maxCnt = acc[acc.major] || 0\n acc.major = acc[x] <= maxCnt ? acc.major : x\n return acc\n}, {major: null}).major\n</code></pre>\n\n<p>And just for fun, again based on your tag, here's a single-expression solution in Ramda. Again, I don't recommend actually using this given that Boyer-Moore exists:</p>\n\n<pre><code>pipe(\n groupBy(identity), \n map(length), \n toPairs, \n converge( reduce(maxBy(last)), [head, identity] ),\n head, \n parseInt\n)(lst)\n</code></pre>\n\n<p>You can <a href=\"https://goo.gl/sNReAW\" rel=\"nofollow noreferrer\">try it here</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:03:08.130",
"Id": "216651",
"ParentId": "216648",
"Score": "3"
}
},
{
"body": "<p>If the number exists, it should be done like this and shorter.</p>\n\n<pre><code>let result =\n [2,3,4,5,1,1,1,2,2,22,2,2,2,2,2,2,2,2,1,1,33,3,2,1,1,1,1,2,2,2,2,2].reduce( (a ,b) => {\n console.log(a)\nreturn a.length == null ? ( a != b ? [] : a.concat(b)):\n a.length == 0 ? [b] :\n a[a.length-1] == b ? a.concat(b) :\n a.slice(0,a.length-2) ;\n })[0]\n\n console.log(result) //2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:42:50.183",
"Id": "419168",
"Score": "1",
"body": "Welcome to Code Review! `and shorter` is a bit short on what deserves improvement in the code in the question and why the way proposed is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T11:41:11.423",
"Id": "419215",
"Score": "0",
"body": "Shorter means in Javascript, you may write in a neater way. It’s an implementation of voter algorithm. Just compare the last element in result with a new element, if they are different, just cancel them. Then the final survived element will be the result. Time is o(n) and if in-place space is o(1)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T00:27:19.040",
"Id": "216689",
"ParentId": "216648",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216650",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T12:00:50.370",
"Id": "216648",
"Score": "10",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Find the majority element, which appears more than half the time"
} | 216648 |
<p>I have some code, that works fine. However, I know there is a lot of code duplication and C-style programming. In the code example there only is a <code>DeviceOneDispatcher</code>, in reality there are more child classes and case options. </p>
<p>The question is how to optimize/refactor this code best following c++11-c++17.
I believe a big part of the duplication, could be solved by using a template. But I am not sure how implement this. </p>
<pre><code>class BaseDispatcher
{
public:
BaseDispatcher() = default;
virtual ~BaseDispatcher() = default;
result_t Init(uint8_t idx)
{
msgHandler.Init(idx);
};
void Execute(MainControl &ctrl)
{
MsgInfo msg = { 0 };
if (msgHandler.RxMsg(msg))
{
switch (msg.msgID)
{
case REQ_PING:
HandlePing(msg);
break;
case REQ_VERSION:
HandleVersion(msg);
break;
default:
SpecificExecute(msg, ctrl);
}
};
protected:
void HandlePing(const MsgInfo &msg)
{
txMsg = msgHandler.ReserveMsg(msg.msgID, sizeof(DefaultMsg_t));
if (nullptr != txMsg.msgBuf)
{
auto *response = (DefaultMsg_t *)txMsg.msgBuf;
response->ack = htons(static_cast<uint16_t>(Reply::ACCEPTED));
msgHandler.SendMsg(txMsg);
mainCtrl->GetConsole().OutputEnable();
}
};
void HandleVersion(const MsgInfo &msg)
{
txMsg = msgHandler.ReserveMsg(msg.msgID, sizeof(VersionInfoMsg_t));
if (nullptr != txMsg.msgBuf)
{
auto *response = (VersionInfoMsg_t *)txMsg.msgBuf;
memset(response->name, 0, 32);
response->svnRevision = htons(svnRevision);
uint8_t sl = (uint8_t)strlen(sw);
memcpy(response->name, sw, sl <= 32 ? sl : 32);
msgHandler.SendMsg(txMsg);
}
};
void HandleUnknown(const MsgInfo &msg)
{
txMsg = msgHandler.ReserveMsg(msg.msgID, sizeof(DefaultMsg_t));
if (nullptr != txMsg.msgBuf)
{
auto *response = (DefaultMsg_t *)txMsg.msgBuf;
response->ack = htons(static_cast<uint16_t>(Reply::UNKNOWN_REQ));
msgHandler.SendMsg(txMsg);
}
};
virtual void SpecificExecute(const MsgInfo &msg, MainControl &ctrl);
MsgHandler &GetMsgHandler() { return msgHandler; }
protected:
MsgInfo txMsg;
MsgHandler msgHandler;
static const char* sw = "Embedded Test Program";
};
class DeviceOneDispatcher : public BaseDispatcher
{
public:
DeviceOneDispatcher () = default;
virtual ~DeviceOneDispatcher () = default;
void SpecificExecute(const MsgInfo &msg, MainControl &ctrl) override
{
switch (msg.msgID)
{
case INFO_TEMP:
HandleTemperature(msg, ctrl);
break;
default:
HandleUnknown(msg);
}
};
protected:
void HandleTemperature(const MsgInfo &msg, MainControl &ctrl)
{
float temperature = (float)ntohl(*(uint16_t*)msg.msgBuf) / 10;
ctrl.GetRFMonitor().SetTemperature(temperature);
};
};
class DeviceTwoDispatcher : public BaseDispatcher
{
public:
DeviceTwoDispatcher () = default;
virtual ~DeviceTwoDispatcher () = default;
void SpecificExecute(const MsgInfo &msg, MainControl &ctrl) override
{
switch (msg.msgID)
{
case INFO_TEMP:
HandleMotor(msg, ctrl);
break;
default:
HandleUnknown(msg);
}
};
protected:
void HandleMotor(const MsgInfo &msg, MainControl &ctrl)
{
//do something
};
};
Class MainController()
{
public:
Execute()
{
dispatcherOne.Execute(*this);
dispatcherTwo.Execute(*this);
}
DeviceOneDispatcher &GetDispatcherOne() { return dispatcherOne; }
DeviceTwoDispatcher &GetDispatcherTwo() { return dispatcherTwo; }
protected:
DeviceOneDispatcher dispatcherOne;
DeviceTwoDispatcher dispatcherTwo;
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T12:44:38.997",
"Id": "419066",
"Score": "0",
"body": "This code seems to be incomplete, there is no function HandleConsoleVerbosity()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:04:03.317",
"Id": "419069",
"Score": "0",
"body": "This code can't compile, the function `HandleVersion()` uses the variable sw which is never defined. Suggestion turn all of your C style casts into static casts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:13:12.273",
"Id": "419073",
"Score": "0",
"body": "The code does compile, however as this is only a snapshot of the program not everything is defined here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T17:42:57.690",
"Id": "419768",
"Score": "0",
"body": "@RForce Please include the rest as well to avoid such confusion. We need to see code in it's context, otherwise a review would be filled with guesswork. That helps nobody."
}
] | [
{
"body": "<p>it seems you just need a dispatcher and some msghanlders., not many dispatchers.\nthe codes can modify like this:</p>\n\n<pre><code>class BaseDispatcher\n{\npublic:\n BaseDispatcher() = default;\n virtual ~BaseDispatcher() = default;\n\n result_t Init(uint8_t idx)\n {\n //msgHandler.Init(idx);\n //to init pmsgHandlerVec\n };\n\n void Execute(MainControl &ctrl)\n {\n for (int i = 0; i < pmsgHandlerVec.size(); ++i)\n {\n BaseHandler* phandler = pmsgHandlerVec[i];\n bool res = phandler->handle_msg(txMsg, ctrl);\n if (res)\n {\n break;\n }\n }\n };\n\nprotected:\n MsgInfo txMsg;\n std::vector<BaseHandler*> pmsgHandlerVec;\n static const char* sw = \"Embedded Test Program\";\n};\n\nclass BaseHandler\n{\n public:\n virtual bol handle_msg(const MsgInfo &msg, MainControl &ctrl) = 0;\n}\n\nclass Handler1 : public BaseHandler\n{\n public:\n virtual bool handle_msg(const MsgInfo &msg, MainControl &ctrl)\n {\n switch (msg.msgID)\n {\n case REQ_PING:\n HandlePing(msg);\n break;\n case REQ_VERSION:\n HandleVersion(msg);\n break;\n default:\n return false;\n }\n return true;\n }\n}\n\nclass Handler2 : public BaseHandler\n{\n public:\n virtual bool handle_msg(const MsgInfo &msg, MainControl &ctrl)\n {\n switch (msg.msgID)\n {\n case INFO_TEMP:\n HandleTemperature(msg, ctrl);\n break;\n default:\n return false;\n }\n return true;\n }\n} \n\nClass MainController()\n{\n public:\n Execute()\n {\n dispatcher.Execute(*this);\n }\n protected:\n BaseDispatcher dispatcher;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:45:20.000",
"Id": "419169",
"Score": "0",
"body": "I dont think this is the best solution in this case. I would like to know which handle I am using. For example ```DeviceOneDispatcher.Execute()```. With a vector you dont know this. Besides I need to be able to use the device handle from other classes declared in ```MainControl``` as well. The switch case from Handler1 should be common for all the devices handlers and supplemented with the specific switch cases per device. I edited my code example for more clerification"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T06:05:48.497",
"Id": "419171",
"Score": "0",
"body": "(Welcome to *finally* posting on stack exchange!)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T04:04:17.603",
"Id": "216692",
"ParentId": "216649",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T12:22:33.083",
"Id": "216649",
"Score": "3",
"Tags": [
"c++",
"c++11"
],
"Title": "Effective message dispatching"
} | 216649 |
<p>This code that I wrote is supposed to read/write a pipe-delimited file line by line to a new file with some simple text manipulation. (It also adds two new columns) and publishes a "Status Update" ever 100,000 lines to keep me updated on how close it is to completion. </p>
<p>I previously posted this code on StackOverflow to get help with incrementing, and someone mentioned that it would be faster if I did not open the second text file, but being extremely new at Python, I do not understand how to do that without potentially breaking the code.</p>
<pre><code>counter=1
for line in open(r"C:\Path\name.txt"):
spline = line.split("|")
if counter==1:
with open(r"C:\PATH\2019.txt",'a') as NewFile:
spline.insert(23,"Column A")
spline.insert(23,"Column B")
s="|"
newline=s.join(spline)
NewFile.write(newline)
elif counter > 1 and not spline[22]=="0.00":
spline.insert(23,"")
spline.insert(23,"")
gl=spline[0]
gl=gl.strip()
if gl[0]=="-": gl="000" + gl
gl=gl.upper()
spline[0]=gl
if gl[:3]=="000": spline[24]="Incorrect"
s="|"
newline=s.join(spline)
with open(r"C:\PATH\PythonWrittenData.txt",'a') as NewFile:
NewFile.write(newline)
counter+=1
if counter%100000==0: print("Status Update: \n", "{:,}".format(counter))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:28:24.287",
"Id": "419086",
"Score": "0",
"body": "Can you edit your question to explain what the loop is supposed to do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:56:58.193",
"Id": "419091",
"Score": "0",
"body": "@DavidWhite Added. For quick reference: It reads one text file line by line, performs string manipulation, and then writes it into a new file line by line."
}
] | [
{
"body": "<p>A nice trick you can use in python is to open two (or more) files at once in one line. This is done with something like:</p>\n\n<pre><code>with open('file_one.txt', 'r') as file_one, open('file_two.txt', 'r') as file_two:\n for line in file_one:\n ...\n for line in file_two:\n ...\n</code></pre>\n\n<p>This is a very common way of reading from one file and writing to another without continually opening and closing one of them.</p>\n\n<p>Currently, you're opening and closing the files with each iteration of the loop. Your program loops through the lines in <code>name.txt</code>, checks an <code>if</code> / <code>elif</code> condition, then if either are satisfied, a file is opened, written to, then closed again <em>with every iteration of the loop</em>.</p>\n\n<p>Simply by opening both files at the same time you can stop opening and closing them repeatedly.</p>\n\n<p>For more info on the <code>with</code> statement and other context managers, see <a href=\"https://book.pythontips.com/en/latest/context_managers.html\" rel=\"noreferrer\">here</a>.</p>\n\n<hr>\n\n<p>Another small improvement can be made. At the moment, you check the first <code>if</code> condition every time, but you know it will only actually evaluate to <code>True</code> once. it would be better to remove that check and just always perform that block once. Assign counter <em>after</em> the first block (after where <code>if counter == 1</code> currently is) then replace the <code>elif</code> statement with a <code>while</code> loop.</p>\n\n<hr>\n\n<p>It would be worth getting familiar with <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a> if you're going to use Python a lot in the future. It's a standard style guide and will help with the readability of your code (for you and others). Just small stuff like new lines after colons or spaces either side of variable declarations / comparisons.</p>\n\n<hr>\n\n<p>If you include an example file and desired output, there may be more I can help with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T21:07:56.143",
"Id": "419141",
"Score": "0",
"body": "I decided to accept this answer as it has the information most pertinent to my skill level and it worked. (I couldn't get the iterative answer to produce the expected results). Thank you very much. I am modifying my code so that it will be PEP8 compliant."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T15:20:35.423",
"Id": "216661",
"ParentId": "216653",
"Score": "7"
}
},
{
"body": "<p>Here is another way to organize your code. Instead of an <code>if</code> within the loop, use iterators more explicitly. Concretely:</p>\n\n<pre><code>with open(r\"C:\\Path\\name.txt\") as source:\n lines = iter(source)\n\n # first line\n first_line = next(lines)\n with open(r\"C:\\PATH\\2019.txt\") as summary:\n # ... omitted ...\n\n # remaining lines\n with open(r\"C:\\PATH\\PythonWrittenData.txt\", 'a') as dest:\n for counter, line in enumerate(lines, start=1):\n # ... omitted ...\n\n</code></pre>\n\n<p>I have also used <code>enumerate</code> to update <code>counter</code> and <code>line</code> simultaneously.</p>\n\n<p>The other answer has some more tips on writing good python code. But as far as structuring the opening and closing of files, as well as the main loop, this approach should get you started.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:22:23.653",
"Id": "419108",
"Score": "0",
"body": "I'm not sure I understand the reasoning behind `first_line=next(lines)` could you explain how it should be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:11:19.810",
"Id": "419122",
"Score": "0",
"body": "@EmilyAlden Why accept an answer when you don’t understand why that answer works?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:36:43.513",
"Id": "419129",
"Score": "0",
"body": "@DavidWhite: Honestly I bounced between which answer to accept. I understand the use of `iter` and `enumerate` here which are the main parts of the answer. The line I do not understand applies only once and I believe I can write around that line and get the results I want. (Still working on it though)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:48:50.830",
"Id": "419132",
"Score": "1",
"body": "@EmilyAlden `first_line = next(iterator)` is equivalent to `for first_line in iterator: break`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:50:26.657",
"Id": "419133",
"Score": "0",
"body": "@wizzwizz4 Thank you."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T15:39:13.337",
"Id": "216662",
"ParentId": "216653",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "216661",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:23:25.247",
"Id": "216653",
"Score": "10",
"Tags": [
"python",
"beginner",
"python-3.x",
"file",
"csv"
],
"Title": "Read/write a pipe-delimited file line by line with some simple text manipulation"
} | 216653 |
<p>I'm new to Python and I just finished a school assignment where I had to make a tictactoe game with focus on OOP. I would love to get some pointers on how I can clean up my code (especially my Tictactoe class) as it's pretty messy right now.</p>
<p>What I've done so far is comment as much as possible to make it understandable, but I feel like my tictactoe class is a mess and I would like to get some pointers on how I can optimize it.</p>
<p>The class below enforces the rules and draws the board:</p>
<pre><code>import os
class Board:
board = [0,1,2,3,4,5,6,7,8,9]
win_combinations = [
(1,2,3),
(4,5,6),
(7,8,9),
(1,5,9),
(3,5,7),
(1,4,7),
(2,5,8),
(3,6,9),
]
GameOver = False
#Draws the board
def drawboard(self):
print('=========')
print(self.board[7], '|', self.board[8], '|', self.board[9])
print(self.board[4], '|', self.board[5], '|', self.board[6])
print(self.board[1], '|', self.board[2], '|', self.board[3])
print('=========')
#Checks if the move the player just made, made him/she win the game
def checkIfWon(self, choice):
for a, b, c in self.win_combinations:
if self.board[a] == self.board[b] == self.board[c]:
print('Game over, player ' + choice + ' won the game')
self.GameOver = True
#Update the current board
def update(self, input, choice):
self.board[input] = choice
os.system('clear')
self.drawboard()
self.checkIfWon(choice)
#Resets the board
def resetBoard(self):
self.board = [0,1,2,3,4,5,6,7,8,9]
#Stops the game if tie
def tie(self):
list = []
for x in self.board:
if type(x) != int:
list.append(x)
if len(list) == 9:
return True
</code></pre>
<p>The class below contains the runGame method which starts the game:</p>
<pre><code>import os
from board import Board
class Tictactoe():
b = Board()
choicePlayer1 = ''
choucePlayer2 = ''
corretChoice = False
correctPlayer1 = False
correctPlayer2 = False
def runGame(self):
os.system('clear')
#Resets the game when a new game is started
#Is necessary if the players wish to play more than 1 game
resetGame(self)
#Makes sure the game only starts if player1 picks X or O
while self.corretChoice == False:
self.choicePlayer1 = input('Do you want to play X or O? ')
print()
if self.choicePlayer1 == 'X':
self.choicePlayer2 = 'O'
self.corretChoice = True
print('Starting player selected X')
elif self.choicePlayer1 == 'O':
self.choicePlayer2 = 'X'
self.corretChoice = True
print('Starting player selected O')
else:
print('ERROR - input has to be either X or O!')
continue
os.system('clear')
self.b.drawboard()
while self.b.GameOver == False:
self.correctPlayer1 = False
self.correctPlayer2 = False
#For player1
while self.correctPlayer1 == False:
while True:
try:
x = int(input(self.choicePlayer1 + ' Where do you want to place your piece? '))
break
except:
print('Input has to be a number, try again')
if x > 0 and x < 10 and type(self.b.board[x]) != str:
self.b.update(x, self.choicePlayer1)
self.correctPlayer1 = True
elif x == 10:
quit()
else:
print('Spot is taken, try again: ')
if self.b.GameOver == True:
self.correctPlayer2 = True
if self.b.tie() == True:
self.correctPlayer2 = True
self.b.GameOver = True
print('Game is a tie')
#For player2
while self.correctPlayer2 == False:
while True:
try:
x = int(input(self.choicePlayer2 + ' Where do you want to place your piece? '))
break
except:
print('Input has to be a number, try again')
if x > 0 and x < 10 and type(self.b.board[x]) != str:
self.b.update(x, self.choicePlayer2)
self.correctPlayer2 = True
elif x == 10:
quit()
else:
print('Spot is taken, try again: ')
if self.b.tie() == True:
self.b.gameOver = True
print('Game is a tie')
#Resets the game if the players wishes to play again
def resetGame(self):
self.b = Board()
self.choicePlayer1 = ''
self.choucePlayer2 = ''
self.corretChoice = False
self.correctPlayer1 = False
self.correctPlayer2 = False
self.b.resetBoard()
</code></pre>
<p>The script i run to start the game:</p>
<pre><code>from tictac import Tictactoe
run = Tictactoe()
while True:
run.runGame()
if input("Play again? (y/n)") == "n":
quit()
</code></pre>
| [] | [
{
"body": "<p>Now, as has been said before: this is more of a codereview than a question. Nevertheless:</p>\n\n<ol>\n<li>You're defining <code>class Board:</code> without parantheses and <code>class Tictactoe()</code> with. No big deal reall, but a bit of inconsistency. I personally just put parens on every declaration. Rids you of having to think about it.</li>\n<li>The variables <code>board</code>, <code>win_combinations</code> and <code>GameOver</code> are defined as class variables since they're declared in the body of the class definition itself. This means that should you for some reason instantiate two games at once they'll mess with each other. It would be better to put them into a constructor <code>__init__(self)</code> (the actual constructor is <code>__new__</code> but you hardly need to edit that so init is generally refered to as constructor). That way every instance has their own instances of these variables.</li>\n<li>The names of the variables and general format doesn't conform to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. Some things here are: Docstrings for classes to describe what they do etc.; variables named snake_case (except for globals/constants) and classes CamelCase; two lines between top level classes, functions etc.; double quotes rather than single quotes. Also the variables probably aren't supposed to be manipulated from outside the class so you could tell other programmers so by prefixing them with an underscore \"_\".</li>\n<li>Maybe add some additional abstraction. The board in your case isn't only a board but also includes gamelogic like checking for a win etc.</li>\n<li>You're using + for string concatenation/interpolation which is deprecated <code>print('Game over, player ' + choice + ' won the game')</code>. The more modern and also more efficient way would be to use an f-string f\"Game over, player {choice} won the game\".</li>\n<li><p>The block</p>\n\n<pre><code>def tie(self):\n list = []\n for x in self.board:\n if type(x) != int:\n list.append(x)\n</code></pre>\n\n<p>could be written as a list comprehension or generator expression: <code>list = [x for x in self.board if type(x) != int]</code>. Or using the <code>filter</code>method: <code>list = list(filter(lambda x: type(x) != int, self.board))</code>. You should also rename <code>list</code> to <code>list_</code> or an actual expressive name saying what it represents here. And in the same function you could just <code>return len(list) == 9</code> since that already is a boolean expression.</p></li>\n</ol>\n\n<p>That's it for the board class. Most of the stuff like format, not using class variables etc also applies to the TicTacToe class.</p>\n\n<ol>\n<li><code>resetGame(self)</code> should probably be a method on the class so you can do <code>self.reset_game()</code> or similar.</li>\n<li>Typo in <code>corretChoice</code> -> <code>correct_choice</code>.</li>\n<li><code>b</code> is a really inexpressive variable name for the board. Why don't you name it <code>board</code>? Especially if it's used across the whole class (rather than being just a local variable) that would make the code a lot clearer.</li>\n<li><p>You're catching everything here:</p>\n\n<pre><code>try:\n x = int(input(self.choicePlayer1 + ' Where do you want to place your piece? '))\n break\nexcept:\n print('Input has to be a number, try again')\n</code></pre>\n\n<p>which is really bad style. It will for example also catch stuff like keyboard interrupts. Since you want to catch errors in the conversion what you probably want is <code>except ValueError:</code>.</p></li>\n</ol>\n\n<p>And lastly not really an error but: if the user inputs anything other than <code>n</code> on the \"play again?\"-prompt it'll restart.</p>\n\n<p>I also feel like the runGame method is way too large - I'll see if I can come up with a clearer solution and post it up here if I can.</p>\n\n<p>EDIT:\nI've tried my hand at refactoring you're code:</p>\n\n<pre><code>import os\n\nclass Board():\n \"\"\"Represents the game-board\"\"\"\n def __init__(self):\n self.board = [i for i in range(10)]\n self._win_combinations = [\n (1, 2, 3),\n (4, 5, 6),\n (7, 8, 9),\n (1, 5, 9),\n (3, 5, 7),\n (1, 4, 7),\n (2, 5, 8),\n (3, 6, 9)]\n self.game_over = False\n\n def draw_board(self):\n \"\"\"Draws the board to the terminal\"\"\"\n print(\"=========\")\n print(self.board[7], \"|\", self.board[8], \"|\", self.board[9])\n print(self.board[4], \"|\", self.board[5], \"|\", self.board[6])\n print(self.board[1], \"|\", self.board[2], \"|\", self.board[3])\n print(\"=========\")\n\n def check_if_won(self, player):\n \"\"\"Checks if the move the player just made, made him/her win the game\"\"\"\n for a, b, c in self._win_combinations:\n if self.board[a] == self.board[b] == self.board[c]:\n print(f\"Game over, player {player} won the game\")\n self.game_over = True\n\n def update(self, input, choice):\n \"\"\"Update the current board\"\"\"\n self.board[input] = choice\n os.system(\"clear\")\n self.draw_board()\n self.check_if_won(choice)\n\n def reset_board(self):\n \"\"\"Resets the board\"\"\"\n self.board = [i for i in range(10)]\n\n def tie(self):\n \"\"\"Stops the game if tie\"\"\"\n list_ = list(filter(lambda x: type(x) != int, self.board))\n return len(list_) == 9\n\n\nclass TicTacToe():\n def __init__(self):\n os.system(\"clear\")\n self.board = Board()\n self.player_1_char = \"\"\n self.player_2_char = \"\"\n self.corret_choice = False\n self.get_player_char()\n\n def reset(self):\n \"\"\"Resets the internal state to prepare for a new game\"\"\"\n self.player_1_char = \"\"\n self.player_2_char = \"\"\n self.board.reset_board()\n\n def get_player_char(self):\n \"\"\"Ask the player what character he wants to use and verify choice\"\"\"\n while True:\n player_1_char = input(\"Do you want to play X or O? \")\n print()\n if player_1_char == \"X\":\n self.player_1_char = \"X\"\n self.player_2_char = \"O\"\n print(\"Starting player selected X\")\n break\n elif player_1_char == \"O\":\n self.player_1_char = \"O\"\n self.player_2_char = \"X\"\n print(\"Starting player selected O\")\n break\n else:\n print(\"ERROR - input has to be either X or O!\")\n os.system(\"clear\")\n\n def get_player_input(self, player_char):\n while True:\n while True:\n x = input(f\"{player_char} Where do you want to place your piece?\")\n if x.isdigit():\n x = int(x)\n break\n else:\n print(\"Input has to be a number, try again\")\n\n if x > 0 and x < 10 and type(self.board.board[x]) != str:\n self.board.update(x, player_char)\n break\n elif x == 10:\n quit()\n else: \n print(\"Spot is taken, try again: \")\n\n def check_tie(self):\n if self.board.tie():\n self.board.game_over = True\n print(\"Game is a tie\")\n return True\n return False\n\n def run(self):\n self.board.draw_board()\n\n while not self.board.game_over:\n self.correct_player_1 = False\n self.correct_player_2 = False\n\n self.get_player_input(self.player_1_char)\n if self.board.game_over:\n break\n if self.check_tie():\n break\n\n self.get_player_input(self.player_2_char)\n if self.board.game_over:\n break\n if self.check_tie():\n break\n\n\nwhile True:\n TicTacToe().run()\n\n user_input = \"a\"\n while user_input not in \"ny\":\n user_input = input(\"Play again? (y/n)\").lower()\n\n if user_input == \"y\":\n continue\n else:\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:58:30.607",
"Id": "419079",
"Score": "1",
"body": "\"`class Board:` is Python 2 syntax\" - nope. It's just Python. Parens are optional in either version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:04:05.893",
"Id": "419081",
"Score": "0",
"body": "whoops, sorry. Don't know why I had that in mind like this. Still: He defines one class with and one without parens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:05:57.260",
"Id": "419082",
"Score": "0",
"body": "It's OK; edit your question to suit and I'll upvote it. Everything else looks good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:25:22.193",
"Id": "419083",
"Score": "1",
"body": "@SV-97 Thank you for writing such a detailed response. Really helpful. I didn't know about PEP8, was a nice read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:42:54.987",
"Id": "419089",
"Score": "1",
"body": "No problem - I generally enjoy code reviews and profit from them too :D I've just added my version of your code if you want to have a look though I'd of course encourage you to try implementing some of the mentioned things yourself beforehand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:56:57.113",
"Id": "419090",
"Score": "0",
"body": "@SV-97 Just saw your edit, really appreciate it!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:45:05.887",
"Id": "216656",
"ParentId": "216654",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216656",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:32:12.117",
"Id": "216654",
"Score": "3",
"Tags": [
"python",
"homework",
"tic-tac-toe"
],
"Title": "Small terminal Tic Tac Toe game"
} | 216654 |
<p>I'm trying to find the local maxima in a 3D numpy array, but I can't seem to find an easy way to do that using numpy, scipy, or anything else.</p>
<p>For now I implemented it using <code>scipy.signal.argrelexrema</code>. But it's very long to process large arrays, and only works on separated axes.</p>
<pre><code>import numpy as np
from scipy.signal import argrelextrema
def local_maxima_3D(data, order=1):
"""Detects local maxima in a 3D array
Parameters
---------
data : 3d ndarray
order : int
How many points on each side to use for the comparison
Returns
-------
coordinates : ndarray
coordinates of the local maxima
values : ndarray
values of the local maxima
"""
# Coordinates of local maxima along each axis
peaks0 = np.array(argrelextrema(data, np.greater, axis=0, order=order))
peaks1 = np.array(argrelextrema(data, np.greater, axis=1, order=order))
peaks2 = np.array(argrelextrema(data, np.greater, axis=2, order=order))
# Stack all coordinates
stacked = np.vstack((peaks0.transpose(), peaks1.transpose(),
peaks2.transpose()))
# We keep coordinates that appear three times (once for each axis)
elements, counts = np.unique(stacked, axis=0, return_counts=True)
coords = elements[np.where(counts == 3)[0]]
# Compute values at filtered coordinates
values = data[coords[:, 0], coords[:, 1], coords[:, 2]]
return coords, values
</code></pre>
<p>I know this solution is far from optimal and only works with order=1. Is there any better way to find local maxima in a 3D array in Python?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:54:15.843",
"Id": "419078",
"Score": "3",
"body": "Do you know anything about the data? If they're determined by a formula, then you should consider getting an analytical answer. Otherwise, the data being continuous, derivable and/or single-maximum would allow for your use of an optimizer, especially if you can provide a gradient function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T14:28:46.977",
"Id": "419087",
"Score": "0",
"body": "As opposed to `unique(stacked(...))[where(counts==3)]`, have you tried set intersection, like `set(peaks0) & set(peaks1) & set(peaks2)`. Of course, the `peaks#` coordinates would need to be converted into something hashable (tuples) in order to create the sets. I don’t know if this would be faster, so this is an experiment not an answer ..."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:35:08.850",
"Id": "216655",
"Score": "3",
"Tags": [
"python",
"numpy",
"scipy"
],
"Title": "Local maxima 3D array python"
} | 216655 |
<p>I've recently answered a question about <a href="https://stackoverflow.com/questions/55447469/">reading elements from an array of arrays</a>. A way it could be interpreted is that the OP wanted to read a range that could span over multiple subarrays of the 2D array like so :</p>
<pre><code>let a = [["5", "3", ".", ".", "7", "."],
["6", ".", ".", "1", "9", "5"]]
a.lazy.flatMap{$0}[1..<7] ["3", ".", ".", "7", ".", "6"]
</code></pre>
<p>This way of reading a range would need to at least <code>flatMap</code> all the previous arrays to the lower bound of the range. Which would be wasteful.</p>
<p>A more <em>natural</em> way would be to only read the needed elements from the original array:</p>
<pre><code>func get<T>(_ range: Range<Int>, from array2d: [[T]]) -> [T]? {
var result: [T] = []
result.reserveCapacity(range.upperBound - range.lowerBound)
var count1 = 0
//Get the index of the first element
guard var low = array2d
.firstIndex(where: {
count1 += $0.count
return range.lowerBound < count1 }),
count1 != 0
else { return nil }
let before = count1 - array2d[low].count
var count2 = before
//Get the index of the last element in the range
guard let high = array2d[low..<array2d.endIndex]
.firstIndex(where: {
count2 += $0.count
return range.upperBound <= count2
}),
count2 != 0
else { return nil }
//Append the elements in the array with the low index
for i in (range.lowerBound - before)..<min(range.upperBound - before, array2d[low].count) {
result.append(array2d[low][i])
}
//If the range spans over multiple arrays
if count1 < count2 {
low += 1
//Append the elements in the arrays with an index between low and high
while low < high {
result.append(contentsOf: array2d[low])
low += 1
}
//Append the elements in the array with the high index
for i in 0..<(range.upperBound - count2 + array2d[high].count) {
result.append(array2d[high][i])
}
}
return result
}
</code></pre>
<p>Which could be used like so :</p>
<pre><code>let a = [["0", "1", "2", "3", "4", "5"], ["6", "7"], [], ["8","9","10","11", "12"], ["13","14", "15"]]
get(5..<11, from: a) //Optional(["5", "6", "7", "8", "9", "10"])
get(7..<9, from: a) //Optional(["7", "8"])
</code></pre>
<p>To me, the above code feels.. on the border of sanity/maintainability...</p>
<p>What I'd like to do is to make it more generic, maybe as an extension to <code>RandomAccessCollection</code>, and making the flattening process recursive for arrays/collections of arbitrary dimensions. I'm stuck here and not sure if this is the appropriate network to ask such a question.</p>
<p>Feedback on all aspects of the code is welcome, such as (but not limited to):</p>
<ul>
<li>Efficiency,</li>
<li>Readability,</li>
<li>Naming.</li>
</ul>
| [] | [
{
"body": "<p>I gather that your intent was to write a method that iterates through an array of arrays (but avoiding functional patterns), flattening the results in the process such that given...</p>\n\n<pre><code>let a = [[\"0\", \"1\", \"2\", \"3\", \"4\", \"5\"], [\"6\", \"7\"], [], [\"8\",\"9\",\"10\",\"11\", \"12\"], [\"13\",\"14\", \"15\"]]\n</code></pre>\n\n<p>... that result for <code>5..<10</code> would be <code>[\"5\", \"6\", \"7\", \"8\", \"9\"]</code></p>\n\n<p>Assuming that’s what you were trying to do, I think you can simplify it:</p>\n\n<pre><code>extension Array {\n func flattened<T>(range: Range<Int>) -> [T]? where Element == Array<T> {\n var result: [T] = []\n\n var offset = range.startIndex\n var length = range.upperBound - range.lowerBound\n\n result.reserveCapacity(length)\n\n for subarray in self {\n let subarrayCount = subarray.count\n if offset < subarrayCount {\n if length > subarrayCount - offset {\n result += subarray[offset...]\n length -= subarrayCount - offset\n } else {\n return result + subarray[offset..<offset + length]\n }\n }\n offset = Swift.max(0, offset - subarrayCount)\n }\n\n return nil\n }\n}\n</code></pre>\n\n<p>In terms of observations on your code:</p>\n\n<ul>\n<li><p>I wouldn’t advise <code>get</code> method name. It’s not very meaningful name and only conjures up confusion with getters. I’d go with something that captured the “flattening” nature of the routine.</p></li>\n<li><p>As a general rule, we should avoid closures with side-effects in functional programming patterns. Even though you’ve written an “iterative” rendition of the OP’s code, you’re using a functional method, <code>firstIndex</code>, and you are updating variables outside the closure. It’s technically allowed but is contrary to the spirit of functional programming patterns and is dependent upon the implementation details of <code>firstIndex</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T08:40:01.993",
"Id": "419316",
"Score": "0",
"body": "FYI, the above is a simple refactoring of the code snippet in the question, but does not attempt to tackle the question of what changes are needed to handle arbitrary depth in the subarrays."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T19:00:07.430",
"Id": "216743",
"ParentId": "216657",
"Score": "3"
}
},
{
"body": "<h1>Extensibility</h1>\n\n<p>The following is meant as an addendum to Rob's answer. It is built upon their approach and extends it to work for arrays with arbitrary <em>depth</em>.</p>\n\n<pre><code>extension Array {\n func flattened(range: Range<Int>) -> [Any]? {\n return helper(range).result?.count == range.upperBound - range.lowerBound ?\n helper(range).result :\n nil\n }\n\n private func helper(_ range: Range<Int>) -> (result: [Any]?, offset: Int) {\n var result: [Any] = []\n\n var offset = range.startIndex\n let length = range.upperBound - range.lowerBound\n\n result.reserveCapacity(length)\n\n for i in self.indices {\n let element = self[i]\n\n if let sub_a: [Any] = element as? [Any] {\n let tempo = sub_a.helper(offset..<offset + length - result.count)\n if let res = tempo.result {\n result += res\n offset = tempo.offset\n } else {\n return (result: nil, offset: offset)\n }\n } else {\n if offset == 0 {\n result.append(element)\n }\n offset = Swift.max(0, offset - 1)\n }\n\n if result.count == length {\n return (result: result, offset: offset)\n }\n }\n\n return (result: result, offset: offset)\n }\n}\n</code></pre>\n\n<p>It has been tested with all of these arrays :</p>\n\n<pre><code>let a: [Any] = [[[\"0\", \"1\", \"2\", \"3\", \"4\", \"5\"], [\"6\", \"7\"], []],\n [[\"8\", \"9\", \"10\", \"11\", \"12\"], [\"13\", \"14\", \"15\"]]]\n\nlet b: [Any] = [[[\"0\", \"1\"], [\"2\", \"3\", \"4\"]],\n [[]],\n [[\"5\"], [\"6\", \"7\", \"8\", \"9\"]],\n [[\"10\", \"11\", \"12\"], [\"13\", \"14\", \"15\"]]]\n\nlet c: [Any] = [[\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", [\"6\", \"7\", [\"8\", \"9\", \"10\", \"11\", \"12\"]]], [], [\"13\", \"14\", \"15\"]]\n</code></pre>\n\n<p>The output of all three :</p>\n\n<pre><code>print(a.flattened(range: 3..<15))\nprint(b.flattened(range: 3..<15))\nprint(c.flattened(range: 3..<15))\n</code></pre>\n\n<p>is </p>\n\n<blockquote>\n <p><code>Optional([\"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\"])</code></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T15:32:02.160",
"Id": "216873",
"ParentId": "216657",
"Score": "0"
}
},
{
"body": "<p><strong>Functional approach:</strong></p>\n<p><strong>Observation</strong>: The code presented is a bit complex to read, and could be more reusable.\nMy approach would be to separate the two tasks. First flatten the 3d array with a reusable 3d array flattening method and then get the range from the 1d array. The performance of this approach vs more integrated methods is out of the scope at this moment. But something one should of course take in to account if performance is needed.</p>\n<pre><code>extension Collection {\n /**\n * Multidimensional-flat-map...because flatMap only works on "2d arrays". This is for "3d array's"\n * - Note: A 3d array is an array structure that can have nested arrays within nested arrays infinite addendum\n * - Note: Alternate names for this method as suggest by @defrenz and @timvermeulen on slack swift-lang #random: `recursiveFlatten` or `recursiveJoined`\n * ## Examples:\n * let arr:[Any] = [[[1],[2,3]],[[4,5],[6]]] 3d array (3 depths deep)\n * let x2:[Int] = arr.recursiveFlatmap()\n * Swift.print(x2)//[1,2,3,4,5,6]\n */\n public func recursiveFlatmap<T>() -> [T] {\n var results = [T]()\n for element in self {\n if let sublist = element as? [Self.Iterator.Element] { // Array\n results += sublist.recursiveFlatmap()\n } else if let element = element as? T { // Item\n results.append(element)\n }\n }\n return results\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T19:32:21.250",
"Id": "264028",
"ParentId": "216657",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216743",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T13:47:01.790",
"Id": "216657",
"Score": "3",
"Tags": [
"performance",
"array",
"swift",
"collections"
],
"Title": "Efficient way of flat mapping a range of a multidimensional random access collection"
} | 216657 |
<p>I have an ASP.NET Core controller I am creating. The controller endpoint looks something like this right now:</p>
<pre class="lang-cs prettyprint-override"><code>[HttpPost("")]
public async Task<ActionResult<Thing>> AddThing([FromBody] string otherThingId)
{
// First I perform some validation here (null check, proper ID, etc).
// Next I get OtherThing to make a Thing out of it
// _getOtherThing is at the heart of what I'm trying to understand
var sample = await _getOtherThing(otherThingId);
// Finally I do some work to convert it to a Thing and send it back
return newThing;
}
</code></pre>
<p><code>_getOtherThing</code> is a method that performs a very specific concrete call to another API to get the data I needed. It's a method that takes a string and returns a <code>Task<OtherThing></code>. There are issues with this method as it is though, such as testing, sharing it in the code base, and swapping implementations later on. </p>
<p>To me, it seems like it's an external dependency. So it would make sense to pass it into the controller. The controller class does with the Repository it uses via DI like so: </p>
<pre class="lang-cs prettyprint-override"><code>public ThingController(IThingRepository thingRepo)
{
_thingRepo = thingRepo;
}
</code></pre>
<p>The interface and its concrete implementation are then supplied for injection in the <code>Startup.cs</code> file:</p>
<pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IThingRepository, ThingRepository>();
}
</code></pre>
<p>So I end up with two questions:</p>
<ol>
<li>What is the most common/expected way to extract this function and then supply it to the controller? </li>
<li>If I did want to just supply a function, what is the most reasonable way to do it? </li>
</ol>
<p>With respect to the first question - Here are two strategies I could think of. Are there others?</p>
<ol>
<li><strong>Supply the function directly to the class.</strong> What I came up with looks like this:</li>
</ol>
<pre class="lang-cs prettyprint-override"><code>public ThingController(IThingRepository thingRepo, Func<string, Task<OtherThing>> getOtherThing)
{
_thingRepo = thingRepo;
_getOtherThing = getOtherThing;
}
</code></pre>
<p>And then during <code>Startup.cs</code>:</p>
<pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IThingRepository, ThingRepository>();
services.AddSingleton<Func<string, Task<OtherThing>>>(
OtherThingUtils.GetOtherThing
);
}
</code></pre>
<ol start="2">
<li><strong>Convert the function into an interface/class pair and inject that</strong>:</li>
</ol>
<pre class="lang-cs prettyprint-override"><code>interface IOtherThingProvider {
Task<OtherThing> getOtherThing(string id);
}
class OtherThingProvider : IOtherThingProvider {
public async Task<OtherThing> getOtherThing(string id)
{
// original code here
}
}
</code></pre>
<p>And then in the <code>Startup.cs</code> file:</p>
<pre class="lang-cs prettyprint-override"><code>public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IThingRepository, ThingRepository>();
services.AddSingleton<IOtherThingProvider, OtherThingProvider>();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:56:38.617",
"Id": "419121",
"Score": "0",
"body": "Also if this is the wrong context to post this in, or if the post is missing something for Cod Review, let me know and I'll correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:33:04.877",
"Id": "419138",
"Score": "0",
"body": "(This looks *solution looking for a problem* - can you sketch a use case?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:33:28.907",
"Id": "419224",
"Score": "0",
"body": "Thanks. My main question was around typical practices in C#. Is it unusual to pass a function directly to a class like this? I will try and clarify!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:10:18.960",
"Id": "419226",
"Score": "0",
"body": "I took some time to edit the question to hopefully be more fitting. I left the solutions could think of because they are at least one aspect of my question. Hopefully this helps. Thanks again for the feedback @greybeard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:26:12.673",
"Id": "419233",
"Score": "0",
"body": "Also I see I misunderstood what the point of this StackExchange is. Is there a better one to post my question? It might fit fine on StackOverflow now."
}
] | [
{
"body": "<p>You basically butcher the entire reason to dependency inject here.\nSome IoCs let you deffer injection by doing <code>public MyConstructor(Func<IMyInterface> factory)</code>. This is fine, because IMyInterface is an interface and the concrete implementation will be invoked through the standard pipeline and it can have its own dependencies. </p>\n\n<p>But your solution cuts off the DI pipeline half way through and the <code>OverThingUtils.GetOtherThing</code> can not benefit from DI at all. And the special <code>Func<string, IType></code> construct is dangerously close to service locator pattern.</p>\n\n<p>I would create an interface, </p>\n\n<pre><code>interface IOtherThingProvider \n{\n Task<OtherThing> GetOtherThing(string id);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:30:42.283",
"Id": "419222",
"Score": "0",
"body": "So what you're saying is instead of using a function and defining the type in the constructor, I should build an interface/class and use that in the constructor? At that point the DI framework will do the work of creating an instance of the class when needed. Is that right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:01:59.530",
"Id": "419225",
"Score": "0",
"body": "Exactly,and the concrete type can benefit from DI and have its own dependencies. Etc, etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:11:07.857",
"Id": "419227",
"Score": "0",
"body": "Cool, thanks for answering! I also rewrote the question to hopefully be better than it was originally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:15:56.000",
"Id": "419229",
"Score": "0",
"body": "Just be careful with singleton scope. Anything injected into its constructor will be singleton."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:18:46.270",
"Id": "419231",
"Score": "0",
"body": "You can Create a scope but for that you need to i have dependency to IServiceCollection and then you are again danger close to service locator pattern. Its fine for a few framework specific things. But you should be careful spreading depedency to the iOC. If need alot of scoped life times deep down in your domain. Its better to abstract the scope. I did this for one of my projects. https://andersmalmgren.com/2015/06/23/abstract-di-container-scopes/"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T11:33:13.733",
"Id": "216721",
"ParentId": "216667",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216721",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:34:40.040",
"Id": "216667",
"Score": "-2",
"Tags": [
"c#",
"asp.net-core",
".net-core"
],
"Title": "AspNetCore - Injecting a Func<T>"
} | 216667 |
<p>This is a first version of an implementation of <code>std::optional</code> it is supposed to compile under C++14. The public interface of the class is complete, but there are still quite a few things missing. Only a few of the constructor availability traits are checked, none of the noexcept clauses are implemented, no non-member functions are implemented. Also I saw that most implementations that are out there split the storage and the public interface into two separate classes, or inherit from a base class. I wanted to get a baseline implementation working and tested and then move forward with maybe better abstractions internally.</p>
<p>What is there has been unit tested for most code-paths, or manually checked, some of the constraints are hard to verify. E.g. how to verify that a destructor was <em>not</em> called when the object is trivially destructable. </p>
<p>I am also still puzzling about a few of the signatures e.g. </p>
<pre><code> constexpr const T&& operator*() const&& noexcept { return std::move(*reinterpret_cast<const T*>(&storage_)); }
</code></pre>
<p>This seems to silently discard <code>const</code> by letting the user move the content out of the optional (if it is an rvalue). </p>
<p>The current code, including tests is available at (<a href="https://github.com/HarryDC/optional/tree/c05ee37a6fd480dd27741ca28273006f8402c9a8" rel="nofollow noreferrer">https://github.com/HarryDC/optional</a>), I'm reinventing the wheel here for educational purposes, this touches a lot of areas that just don't come up in my normal use of C++. This was developed under Visual Studio, and spot checked on compiler explorer under different compilers.</p>
<pre><code>#include <exception>
#include <initializer_list>
#include <utility>
namespace hs
{
// Missing from C++14
template< class From, class To >
constexpr bool is_convertible_v = std::is_convertible<From, To>::value;
template<class A, class B>
constexpr bool is_same_v = std::is_same<A, B>::value;
// Internals
namespace detail
{
template < typename T, typename std::enable_if_t<std::is_trivially_destructible<T>::value, int> = 0>
void destruct(T*) {}
template < typename T, typename std::enable_if_t < !std::is_trivially_destructible<T>::value, int > = 0 >
void destruct(T* t)
{
t->~T();
}
} // namespace detail
// Optional types
class bad_optional_access : public std::exception {};
struct nullopt_t
{
explicit nullopt_t() = default;
};
constexpr nullopt_t nullopt{};
struct in_place_t
{
explicit in_place_t() = default;
};
constexpr in_place_t in_place{};
// Public Class
template <class T>
class optional
{
public:
using value_type = T;
// Constructors
constexpr optional() noexcept = default;
constexpr optional(nullopt_t) noexcept {}
constexpr optional(const optional& other)
{
if (!other.has_value_) return;
new (&storage_) T(*other);
has_value_ = true;
}
constexpr optional(optional&& other)
{
if (!other.has_value_) return;
new (&storage_) T(std::move(*other));
has_value_ = true;
}
template < class U >
optional(const optional<U>& other)
{
if (!other.has_value()) return;
new (&storage_) T(*other);
has_value_ = true;
}
template < class U >
optional(optional<U>&& other)
{
if (!other.has_value()) return;
new (&storage_) T(std::move(*other));
has_value_ = true;
}
template< class... Args >
constexpr explicit optional(in_place_t, Args&& ... args)
{
new (&storage_) T(std::forward<Args>(args)...);
has_value_ = true;
}
template< class U, class... Args >
constexpr explicit optional(hs::in_place_t,
std::initializer_list<U> ilist,
Args&& ... args)
{
new (&storage_) T(std::forward<std::initializer_list<U>>(ilist), std::forward<Args>(args)...);
has_value_ = true;
}
template < class U = value_type,
typename std::enable_if_t < is_convertible_v<U, T>&&
!is_same_v<std::decay_t<U>, optional<T>>, int > = 0
>
constexpr optional(U && val)
{
new (&storage_) T(std::forward<U>(val));
has_value_ = true;
}
// Destructor
~optional()
{
if (has_value_) detail::destruct<T>(reinterpret_cast<T*>(&storage_));
}
// Operator =
optional& operator=(nullopt_t) noexcept
{
reset();
return *this;
}
// Don't know why the following two overloads (2/3) are separate from copy-op 5/6
constexpr optional& operator=(const optional& other)
{
if (other.has_value_)
{
if (has_value_)
{
**this = *other;
}
else
{
new (&storage_) T(*other);
has_value_ = true;
}
}
else
{
reset();
}
return *this;
}
constexpr optional& operator=(optional&& other) noexcept
{
if (other.has_value_)
{
if (has_value_)
{
**this = std::move(*other);
}
else
{
new (&storage_) T(std::move(*other));
has_value_ = true;
}
}
else
{
reset();
}
return *this;
}
template < class U = value_type,
typename std::enable_if_t < is_convertible_v<U, T>&&
!is_same_v<std::decay_t<U>, optional<T>>, int > = 0
>
optional & operator=(U && value)
{
if (has_value_)
{
**this = std::forward<U>(value);
}
else
{
new (&storage_) T(std::forward<U>(value));
has_value_ = true;
}
return *this;
}
template< class U >
optional& operator=(const optional<U>& other)
{
if (other.has_value())
{
if (has_value_)
{
**this = *other;
}
else
{
new (&storage_) T(*other);
has_value_ = true;
}
}
else
{
reset();
}
return *this;
}
template< class U >
optional& operator=(optional<U>&& other)
{
if (other.has_value())
{
if (has_value_)
{
**this = std::move(*other);
}
else
{
new (&storage_) T(std::move(*other));
has_value_ = true;
}
}
else
{
reset();
}
return *this;
}
// Operator ->, *
// TODO unit test ->
constexpr T* operator->() noexcept { return reinterpret_cast<T*>(&storage_); }
constexpr const T* operator->() const noexcept { return reinterpret_cast<const T*>(&storage_); }
constexpr T& operator*()& noexcept { return *reinterpret_cast<T*>(&storage_); }
constexpr const T& operator*()const& noexcept { return *reinterpret_cast<const T*>(&storage_); }
constexpr T&& operator*()&& noexcept { return std::move(*reinterpret_cast<T*>(&storage_)); }
// What does const in this context mean ??? How to test this
constexpr const T&& operator*() const&& noexcept { return std::move(*reinterpret_cast<const T*>(&storage_)); }
// operator bool, has_value()
constexpr operator bool() const noexcept { return has_value_; }
constexpr bool has_value() const noexcept { return has_value_; }
// value()
constexpr T& value()&
{
if (has_value_) return *reinterpret_cast<T*>(&storage_);
else throw bad_optional_access();
}
constexpr const T& value() const&
{
if (has_value_) return *reinterpret_cast<const T*>(&storage_);
else throw bad_optional_access();
}
// This is on an r-value Do we need to do anything different here ???
constexpr T&& value()&&
{
if (has_value_) return std::move(*reinterpret_cast<T*>(&storage_));
else throw bad_optional_access();
}
// This is on an r-value Do we need to do anything different here ???
// TODO unittest (HOW ???)
constexpr const T&& value() const&&
{
if (has_value_) return std::move(*reinterpret_cast<T*>(&storage_));
else throw bad_optional_access();
}
// value_or()
template <class U>
constexpr T value_or(U&& default_value) const&
{
return (has_value_) ? (**this) : static_cast<T>(std::forward<U>(default_value));
}
template <class U>
constexpr T value_or(U&& default_value)&&
{
return (has_value_) ? std::move(**this) : static_cast<T>(std::forward<U>(default_value));
}
// swap
void swap(optional& other)
{
if (has_value_ && other)
{
std::swap(**this, *other);
}
else if (has_value_)
{
other = std::move(*this);
reset();
}
else if (other)
{
*this = std::move(*other);
other.reset();
}
}
// reset
void reset() noexcept
{
if (has_value_) detail::destruct<T>(reinterpret_cast<T*>(&storage_));
has_value_ = false;
}
// emplace
template< class... Args >
T& emplace(Args&& ... args)
{
new (&storage_) T(std::forward<Args>(args)...);
has_value_ = true;
return **this;
}
template< class U, class... Args >
T& emplace(std::initializer_list<U> ilist, Args&& ... args)
{
new (&storage_) T(std::forward<std::initializer_list<U>>(ilist), std::forward<Args>(args)...);
has_value_ = true;
return **this;
}
private:
bool has_value_{ false };
typename std::aligned_storage<sizeof(T), alignof(T)>::type storage_;
};
// TBD ...
// Non-member func
// comparators
// make_optional
// std::swap
// Helper Class
// std::hash
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T02:51:16.733",
"Id": "419164",
"Score": "0",
"body": "\"This seems to silently discard `const` by letting the user move the content out of the optional (if it is an rvalue).\" Can you explain your reasoning for why this silently discards `const`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:24:17.383",
"Id": "419220",
"Score": "0",
"body": "I think i'm basically just confused about the overall signature and its semantics (i.e. learning experience), its a `const` function, called on an rvalue reference. It returns a forwarding reference (not an rvalue reference) to the value contained inside the (if I am getting the nomenclature right here). By returning the value of the optional using `std::move` it is marked as an rvalue. I think i'm missing the purpose of this signature. Maybe the comment thread here is not the right place to discuss this either ..."
}
] | [
{
"body": "<blockquote>\n <p>See my <a href=\"https://codereview.stackexchange.com/q/225642\">A standard-conforming C++17 std::optional implementation</a>, partly inspired by this post.</p>\n</blockquote>\n\n<hr>\n\n<p>(Note: C++17-only features like <code>inline</code> variables are ignored in this answer.)</p>\n\n<h1>The cryptic <code>const &&</code> signature</h1>\n\n<p>First, let me answer your question:</p>\n\n<blockquote>\n <p>I am also still puzzling about a few of the signatures e.g.</p>\n\n<pre><code>constexpr const T&& operator*() const&& noexcept { return std::move(*reinterpret_cast<const T*>(&storage_)); }\n</code></pre>\n \n <p>This seems to silently discard const by letting the user move the\n content out of the optional (if it is an rvalue).</p>\n</blockquote>\n\n<p>Good question. Your implementation is correct. <code>optional</code> is designed to be completely transparent with regard to value category, so that calling <code>*</code> on an rvalue <code>optional</code> returns an rvalue. Given that we allow <code>&</code>, <code>const &</code>, and <code>&&</code> work correctly, there is not a reason to treat <code>const &&</code> unfairly. A <code>const &&</code> cannot actually be moved from.</p>\n\n<p>I would implement it as</p>\n\n<pre><code>constexpr const T&& operator*() const&& noexcept\n{\n return std::move(**this);\n}\n</code></pre>\n\n<p>to reduce code duplication. Here, <code>**this</code> calls the <code>const &</code> overload because <code>*this</code> is always considered an lvalue expression. I have yet to see a practical use of this overload.</p>\n\n<p>You can test it like this:</p>\n\n<pre><code>const optional<int> x{42};\nstatic_assert(std::is_same<decltype(*std::move(x)), const int&&>::value);\n</code></pre>\n\n<p>Same for <code>value()</code>.</p>\n\n<h1><code>constexpr</code> friendliness</h1>\n\n<p>Your implementation is not <code>constexpr</code> friendly. Something as basic as:</p>\n\n<pre><code>constexpr hs::optional<int> x{42};\n</code></pre>\n\n<p>fails because your <code>optional</code> has a non-trivial destructor. Let's look up the definition of <em>trivial destructor</em> in C++14: (<a href=\"https://timsong-cpp.github.io/cppwp/n4140/class.dtor#5\" rel=\"nofollow noreferrer\">[class.dtor]/5</a>, emphasis mine)</p>\n\n<blockquote>\n <p>[...]</p>\n \n <p>A destructor is trivial if <strong>it is not user-provided</strong> and if:</p>\n \n <ul>\n <li><p>the destructor is not <code>virtual</code>,</p></li>\n <li><p>all of the direct base classes of its class have trivial destructors, and</p></li>\n <li><p>for all of the non-static data members of its class that are of class type (or array thereof), each such class has a trivial\n destructor. </p></li>\n </ul>\n \n <p>Otherwise, the destructor is <em>non-trivial</em>.</p>\n</blockquote>\n\n<p>Your destructor is user-provided, hence non-trivial.</p>\n\n<p>The only way to properly implement a <code>constexpr</code> friendly <code>optional</code>, I suppose, is to use a union. That's how <code>constexpr</code> machinery work under the hood. And that also explains the connection between the <code>constexpr</code>-ness of the copy / move operations on <code>optional</code> and the trivially of the corresponding operations on the value type as specified in the standard.</p>\n\n<h1><code>destruct</code></h1>\n\n<p>(The verb is formally called \"destroy\" in C++, not \"destruct\", although the nouns are \"destructor\" and \"destruction\" and the adjective is \"destructible\".)</p>\n\n<p>The <code>destruct</code> function exists to optimize out trivial destructor calls. However, a competent compiler should be able to optimize such calls on itself. Therefore, I suggest removing the function altogether.</p>\n\n<h1><code>nullopt_t</code></h1>\n\n<p>Per <a href=\"https://timsong-cpp.github.io/cppwp/n4659/optional.nullopt#2\" rel=\"nofollow noreferrer\">[optional.nullopt]/2</a>:</p>\n\n<blockquote>\n <p>Type <code>nullopt_t</code> shall not have a default constructor or an\n initializer-list constructor, and shall not be an aggregate.</p>\n</blockquote>\n\n<p>Your <code>nullopt_t</code> is default constructible. Simple fix:</p>\n\n<pre><code>struct nullopt_t {\n explicit constexpr nullopt_t(int) {}\n};\nconstexpr nullopt_t nullopt{42};\n</code></pre>\n\n<h1>Constructors</h1>\n\n<p>The copy constructor is not defined as deleted when it should. The move constructor is missing noexcept specification and participates in overload resolution when it shouldn't. Implementing the special member functions (copy/move constructor/assignment) correctly requires the use of base classes and template specialization (you don't want to duplicate the whole class just to dispatch on <code>is_move_constructible</code>).</p>\n\n<p>(You may ask: can't we use SFINAE? For constructors, we can add default arguments; for assignment operators, we can play with the return type. The answer is no. SFINAE only with templates (member functions in a class template are not automatically templates), and the special member functions cannot be templates. If you write a templates as an attempt to implement them, the default (wrong) versions will still be generated and take precedence over the templates.)</p>\n\n<p>This also affects the other constructors / constructor templates and their <code>explicit</code>ness. They are easier to implement because SFINAE can be used. Usually, the way to implement conditional <code>explicit</code> before C++20 is to declare two constructors and use SFINAE to ensure that they do not participate in overload resolution at the same time.</p>\n\n<p>Incidentally, your constructors repeat a lot of code. I suggest extracting a separate function to deal with construction: (note that you are not supposed to forward <code>initializer_list</code>s)</p>\n\n<pre><code>private:\n template <typename... Args>\n void construct(Args&&... args)\n {\n assert(!has_value);\n new (&storage_) T(std::forward<Args>(args)...);\n has_value_ = true;\n }\n\n template <typename U, typename... Args>\n void construct(std::initializer_list<U> init, Args&&... args)\n {\n assert(!has_value);\n new (&storage_) T(init, std::forward<Args>(args)...);\n has_value_ = true;\n }\n</code></pre>\n\n<p>and use it to simplify the constructors:</p>\n\n<pre><code>optional(const optional& other)\n{\n if (!other)\n construct(*other);\n}\n\noptional(optional&& other)\n{\n if (!other)\n construct(std::move(*other));\n}\n\n// etc.\n</code></pre>\n\n<h1>Assignment</h1>\n\n<p>The copy/move assignment operators should also be defined as deleted / excluded from overload resolution as required by the standard. Similar for other assignment operators. See the previous point about copy/move constructors and other constructors.</p>\n\n<pre><code>// Don't know why the following two overloads (2/3) are separate from copy-op 5/6\n</code></pre>\n\n<p>Because the default versions of the copy assignment operator and move assignment operator automatically generate (as deleted) and take precedence over the templates if you don't implement them.</p>\n\n<p>The logic of the assignment operators can probably be unified / simplified somehow. Something like:</p>\n\n<pre><code>template <typename U>\nvoid construct_or_assign(U&& val)\n{\n if (*this)\n **this = std::forward<U>(val);\n else\n construct(std::forward<U>(val));\n}\n</code></pre>\n\n<p>(with apologies to Thomas Köppe [<a href=\"https://wg21.link/n4279\" rel=\"nofollow noreferrer\">1</a>] for stealing the name.)</p>\n\n<h1>Observers</h1>\n\n<p>The dereference operators look nice.</p>\n\n<p><code>operator bool</code> should be <code>explicit</code>.</p>\n\n<pre><code>// This is on an r-value Do we need to do anything different here ???\n</code></pre>\n\n<p>No, I think you are doing fine.</p>\n\n<h1>Emplace</h1>\n\n<p><code>emplace</code> should call <code>reset()</code> before constructing the new element, or the original element will not be properly destroyed.</p>\n\n<h1>Miscellaneous</h1>\n\n<p>You are missing a few <code>#include</code>s (<code><type_traits></code>, <code><typeindex></code> for <code>std::hash</code>, etc.).</p>\n\n<p>The <code>typename</code> before <code>enable_if_t</code> is redundant:</p>\n\n<pre><code>template <typename T, /*typename*/ std::enable_if_t<std::is_trivially_destructible<T>::value, int> = 0>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-02T14:47:23.640",
"Id": "437683",
"Score": "0",
"body": "Thanks for the comments, I haven't done much work on this but it seems the only solution to enabling the correct traits, like trivially constructable, and some of the overloads is building a chain of classes that will inherit the correct traits. Every implementation i've seen in the wild is doing that. Any other ways of accomplishing this ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-03T03:38:57.897",
"Id": "437727",
"Score": "0",
"body": "@HaraldScheirich I'm afraid not. The real problem is that the special member functions cannot be templates, and so SFINAE is not applicable. I cannot really think of another way to implement this other than to use base class template + template specialization. Maybe I am not creative enough, though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-01T09:03:20.447",
"Id": "225331",
"ParentId": "216669",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "225331",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:37:11.503",
"Id": "216669",
"Score": "2",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++14",
"optional"
],
"Title": "`std::optional` under C++14 v1"
} | 216669 |
<p>I found some months ago that I could generate Hamming multiples of 3 and 5 multiples (3^x & 5^x) in one list comprehension. There are many fewer 3 and 5 Hamming multiples in a Hamming sequence. I did not have to be concerned with duplicate multiples as it is 2 disparate lists.</p>
<p>All I needed to do was add the Hamming 2 multiples.</p>
<p>When I did, it was chaos. Multiples of the 3 and 5 multiples with the 2^x produced clean Hamming numbers but left even more at the end of the list that had missing Hamming numbers between them.</p>
<p>The problem was the Cartesian product of the 2 multiples and the 3&5 multiples.</p>
<p>I had used the 3^x times 5^x’s in another algorithm successfully. I had limited the list with some involved calculation. </p>
<p>Then, I encountered the same problem working with primes. I wanted a list to subtract from a wheel but the list contained much excess. It was another huge Cartesian product of values.</p>
<p>I didn’t know which elements to eliminate from either list and I thought them intermixed.</p>
<p>Then it dawned on me. I tried it with the primes and it worked. Then with the Hamming 2s and it worked. </p>
<p>First I rewrote the 3 & 5 multiples list comprehension with the much simpler logic and way less calculation.</p>
<p>What was the solution? All it is, is using the end value of the generated first list to limit values of subsequent lists. List comprehensions take the first value of the first list and apply it to all values in the second list thus making a list. It is the first list end value that is the limit of each subsequent list. These limited lists do not generate any excess at the end of any list</p>
<p>The prime’s composite list to subtract is top and bottom diagonal to form a rouge triangle. In it x and y are identical. The Hammings lists are bottom, irregular diagonal only. The x and y are different.</p>
<p>My problem, now, is how to specify how many Hammings I want instead of the<code>x</code> in <code>2^x</code> as the parameter. Is it just practical to use <code>take</code> with some derived value of <code>x</code> (in <code>2^x</code>) to get the number of Hammings wanted? How can <code>x</code> be derived from specified <code>n</code> number of Hamming wanted? The second thing is how fast is this compared to the fastest Hamming list generators?</p>
<p>Thanks for any help you can offer.</p>
<p>The Hamming functions follow</p>
<pre><code>gnf n f = scanl (*) 1 $ replicate f n
mk35 n = (\c-> [m| t<- gnf 3 n, f<- gnf 5 n, m<- [t*f], m<= c]) (2^(n+1))
mkHams n = (\c-> sort [m| t<- mk35 n, f<- gnf 2 (n+1), m<- [t*f], m<= c]) (2^(n+1))
</code></pre>
<p><code>last $ mkHams 50</code></p>
<p>2251799813685248</p>
<p>(0.03 secs, 12,869,000 bytes)</p>
<p><code>2^51</code></p>
<p>2251799813685248</p>
<p><strong>5/6/2019</strong></p>
<p>Well, I tried limiting differently but always come back to what is simplest.
I am opting for the least memory usage as also the fastest.
I also opted to use <code>map</code> with an implicit parameter.
I also found that <code>mergeAll</code> from <code>Data.List.Ordered</code> is faster that <code>sort</code> or <code>sort</code> and <code>concat</code>. I also like when sublists are created so I can analyze the data much easier.
Then, because of @Wil Ness on SO switched to <code>iterate</code> instead of <code>scanl</code> making much cleaner code. Also because of @Wil Ness I stopped using last of of 2s list and switched to one value determining all lengths. </p>
<p>Just separating the function into two doesn't make a difference so the 3 and 5 multiples would be</p>
<pre><code>m35 lim = mergeAll $
map (takeWhile (<=lim).iterate (*3)) $
takeWhile (<=lim).iterate (*5) $ 1
</code></pre>
<p>And the 2s each multiplied by the product of 3s and 5s </p>
<pre><code>ham n = mergeAll $
map (takeWhile (<=lim).iterate (*2)) $ m35 lim
where lim= 2^n
</code></pre>
<p>After editing the function I ran it</p>
<p><code>last $ ham 50</code></p>
<p>1125899906842624</p>
<p>(0.00 secs, 7,029,728 bytes)</p>
<p>then</p>
<p><code>last $ ham 100</code></p>
<p>1267650600228229401496703205376</p>
<p>(0.03 secs, 64,395,928 bytes)</p>
<p>It is probably better to use <code>10^n</code> but for comparison I again used `2^n.</p>
<p><strong>5/11/2019</strong></p>
<p>Because I so prefer infinite and recursive lists I became a bit obsessed with making these infinite.</p>
<p>I was so impressed and inspired with @Daniel Wagner and his <code>Data.Universe.Helpers</code> I started using <code>+*+</code> and <code>+++</code> but then added my own infinite list. I had to <code>mergeAll</code> my list to work but then realized the infinite 3 and 5 multiples were exactly what they should be. So, I added the 2s and <code>mergeAll</code>d everything and they came out. Before, I stupidly thought <code>mergeAll</code> would not handle infinite list but it does most marvelously.</p>
<p>When a list is infinite in Haskell, Haskell calculates just what is needed, that is, is lazy. The adjunct is that it does calculate from, the start.</p>
<p>Now, since Haskell multiples until the limit of what is wanted, no limit is needed in the function, that is, no more <code>takeWhile</code>. The speed up is incredible and the memory lowered too,</p>
<p>The following is on my slow home PC with 3GB of RAM.</p>
<pre><code>tia = mergeAll.map (iterate (*2)) $
mergeAll.map (iterate (*3)) $ iterate (*5) 1
</code></pre>
<p><code>last $ take 10000 tia</code></p>
<p>288325195312500000</p>
<p>(0.02 secs, 5,861,656 bytes)</p>
<p><strong>6.5.2019</strong></p>
<p>I learned how to <code>gch -O2</code>. The following is for 50,000 Hammings to 2.38E+30.
The only change from rerunning this is MUT is .016 and GC is .031 and total is .047 or like this one GC is .047 and total is the same.</p>
<pre><code>INIT time 0.000s ( 0.000s elapsed)
MUT time 0.000s ( 0.916s elapsed)
GC time 0.047s ( 0.041s elapsed)
EXIT time 0.000s ( 0.005s elapsed)
Total time 0.047s ( 0.962s elapsed)
Alloc rate 0 bytes per MUT second
Productivity 0.0% of total user, 95.8% of total elapsed
</code></pre>
<p><strong>6.13.2019</strong></p>
<p>@Will Ness rawks. He provided a clean and elegant revision of <code>tia</code> above and it proved to be five times as fast in <code>GHCi</code>. When I <code>ghc -O2 +RTS -s</code> his against mine, mine was several times faster. There had to be a compromise.</p>
<p>So, I started reading about fusion that I had encountered in R. bird's Thinking Functionally with Haskell and almost immediately tried this.</p>
<pre><code>mai n = mergeAll.map (iterate (*n))
mai 2 $ mai 3 $ iterate (*5) 1
</code></pre>
<p>It matched Will's at <code>0.08</code> for 100K Hammings in <code>GHCi</code> but what really surprised me is (also for 100K Hammings.) The elapsed is really what gets me.</p>
<pre><code> TASKS: 3 (1 bound, 2 peak workers (2 total), using -N1)
SPARKS: 0 (0 converted, 0 overflowed, 0 dud, 0 GC'd, 0 fizzled)
INIT time 0.000s ( 0.000s elapsed)
MUT time 0.000s ( 0.002s elapsed)
GC time 0.000s ( 0.000s elapsed)
EXIT time 0.000s ( 0.000s elapsed)
Total time 0.000s ( 0.002s elapsed)
Alloc rate 0 bytes per MUT second
Productivity 100.0% of total user, 90.2% of total elapsed
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:48:23.723",
"Id": "419351",
"Score": "1",
"body": "What are \"*Hamming multiples of 3 and 5 multiples*\"? What is \"*a Hamming sequence*\"? There's a lot of explanation here of your path to the current version of the code, but I can't find an intelligible explanation of the problem it's trying to solve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:09:38.373",
"Id": "419358",
"Score": "0",
"body": "`mkHams 50` will generate 6911 Hamming #s in sequence. Here is a link to the well understood Hamming sequence generation http://rosettacode.org/wiki/Hamming_numbers#Haskell The entry \"Direct calculation through triples enumeration\" is what this is trying to solve but in a more direct & simpler way. There is a Wiki, too. They are also known as ugly or regular numbers. I first was using involved calculation like the code in Rosetta Code but then I found the value of the end point of the first list of a Cartesian product as a limit of all other list values. `c` This could be `2^i * 3^j * 5^k"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:44:23.687",
"Id": "419361",
"Score": "0",
"body": "Also, at bottom, this is a solution in limiting the values in a Cartesian product. Normally, the Hamming sequence is expressed like 2^i * 3^j * 5^k as somehow being completely all Hamming numbers. It may be but is is also missing a lot. Limiting it is what makes it work. The same problem exists in primes. To subtract a list of composites from a mixed list requires limiting the composites list like this but with a top diagonal as well as bottom. Doing that with composites for primes is how I found this. I was agonizing on how to limit a Cartesian product. They contain just way too many values"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:18:39.897",
"Id": "419366",
"Score": "1",
"body": "It's slow as you need to screen or filter in each subStep. When you calculate the fold of 3 and all those larger than 2^(n+1) needed to be removed. same for the 5 .same for the 3*5 , you did it but maybe too late. The final steps also has such problems. you need to early stop guard. How about add a where clause some where to do it. Actually both questions has one answer. Build a queue with [1,2,3,5], every popped one multiple(2, 3, 5) and then insert back to the queue but keep unique value for the queue. The result is all popped ones. It is countable without extra number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:32:25.853",
"Id": "419369",
"Score": "0",
"body": "I think what you are saying, and made me realize, is that the predicate `m<=c` is applied to every value excluded or not. That is, a whole lot of values. It needs to stop as soon as one value in a list exceeds `c` Is that right? I can put the first clause in the result and use `takeWhile` for the predicate but I get nested lists. `concat`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:37:48.860",
"Id": "419371",
"Score": "1",
"body": "Yes. Still it's slow. try the queue one should be 100 times fast than this one as you have to visit many unnecessary big numbers. In order to get it faster, you may cache three positions and then insert from there respectively, which will be very attractive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:50:36.720",
"Id": "419372",
"Score": "0",
"body": "I tried a quick and dirty test using the `takeWhile` short circuit with a version that was much slower but it sped up a whole lot with the `takeWhile` . It is `sort $ concat [ takeWhile (<=2^21) [ a*b | b<- [ n*m | m<- gnf 5 20], a <- gnf 2 21 ] | n<- gnf 3 20 ]` But now I will try more. Thanks a whole lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:52:48.023",
"Id": "419374",
"Score": "1",
"body": "It is great to hear that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T22:59:12.873",
"Id": "419635",
"Score": "0",
"body": "If you seriously want a high speed, you have to know 1+1 = 2, 1 + 2 =3 and 2 + 3 =5. You may skip a lot of hassles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T01:05:08.507",
"Id": "419640",
"Score": "0",
"body": "Just what sequence would that be: `[1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T02:06:48.243",
"Id": "419647",
"Score": "0",
"body": "Well, it’s not that sequence but a dp solver algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T16:40:30.640",
"Id": "419692",
"Score": "0",
"body": "I read somewhere that DP in Haskell was just recursion so your sequence would be `fib a b = b:fib b (a+b)`. I started work on a recursive version of my Hamming function this morning among other things. It looks like mutual recursive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T19:00:09.863",
"Id": "419704",
"Score": "0",
"body": "The bottleneck of this question here is how to get fastest sort. if you don’t see the relationship you didn’t get it."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T17:57:12.207",
"Id": "216671",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Fast Hamming sequence generation in Haskell"
} | 216671 |
<p>I am trying to come up with a UIState system that works well with Java UI. Before I show it I know I could add enums to help distinguish the states but I've left that out for simplicity. Here is what I have so far. What updates would you suggest?</p>
<pre><code>public class UIStateFrame extends JFrame{
class actionListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
System.out.println("click: "+e.getActionCommand());
UIStateFrame.instance.setCurrent(current.getNext(e.getActionCommand()));
}
}
public static UIStateFrame instance;
public static UIState current;
public void setCurrent(UIState newState)
{
System.out.println("New State: "+newState);
current = newState;
this.getContentPane().removeAll();
add(current.display);
this.validate();
this.repaint();
}
public static void main(String[] args)
{
new UIStateFrame();
//This would be custom UIPanels created elsewhere, here is just a demonstration
JPanel red = new JPanel();
red.setBackground(Color.red);
JButton toBlue = new JButton("toBlue");
toBlue.setActionCommand("Blue");
toBlue.addActionListener(instance.new actionListener());
red.add(toBlue);
UIState redState = new UIState(red);
JPanel Blue = new JPanel();
Blue.setBackground(Color.blue);
JButton button2 = new JButton("toRed");
button2.setActionCommand("Red");
button2.addActionListener(instance.new actionListener());
Blue.add(button2);
JButton button = new JButton("toGreen");
button.setActionCommand("Green");
button.addActionListener(instance.new actionListener());
Blue.add(button);
UIState blueState = new UIState(Blue);
JPanel Green = new JPanel();
Green.setBackground(Color.green);
JButton toRed = new JButton("toRed");
toRed.setActionCommand("Red");
toRed.addActionListener(instance.new actionListener());
Green.add(toRed);
UIState greenState = new UIState(Green);
//transitions
redState.addNext("Blue", blueState);
blueState.addNext("Red", redState);
blueState.addNext("Green", greenState);
greenState.addNext("Red", redState);
UIStateFrame.instance.setCurrent(redState);
}
public UIStateFrame()
{
instance = this;
this.setSize(500,500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
/*
* Dynamic Panel control to manage states within the system
* note: going back is also considered going next
*/
class UIState
{
public static List<UIState> allStates = new ArrayList<>();
JPanel display;
Map<String,UIState> next = new TreeMap<>();
public UIState(JPanel pan)
{
display = pan;
allStates.add(this);
}
public void addNext(String key, UIState state)
{
next.put(key, state);
}
public UIState getNext(String key)
{
return next.get(key);
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:35:11.117",
"Id": "216677",
"Score": "1",
"Tags": [
"java",
"gui",
"state-machine"
],
"Title": "Java UIState System"
} | 216677 |
<p>I have a large multi-window GUI program (implemented with MFC) that controls a variety of physics experiment apparatus. When the user starts the main function of the program (the "experiment" run), a large worker thread starts which needs references various singleton objects (generally one per piece of apparatus) to do it's work - in particular programming a variety of machines. These objects are in general managed by the windows which contain the GUI elements relative to those objects, and because they are tied to the GUI windows, they will always exist as long as the program is running. I'm struggling to figure out the best way to handle the references to these objects. What I've done in the past is just use raw pointers to these objects, but this seems like bad style so I'm looking at improvements.</p>
<p>My current scheme is having class structures like this:</p>
<pre><code>#include "RF_Generator.h"
#include "AnalogOutputs.h"
struct MasterThreadInput
{
MasterThreadInput(RfWindow& rfWin, AnalogOutputWindow& aoWin) :
objA(winA.getObjA()),
objB(winB.getObjB())
{ }
RfGenerator& rfSys;
AnalogOutputs& aoSys;
}
class RfWindow : public CDialog
{
public:
RfGenerator& getRfSys();
private:
RfGenerator rfSys;
}
class AnalogOutputWindow : public CDialog
{
public:
AnalogOutputs& getAoSys();
private:
AnalogOutputs aoSys;
}
</code></pre>
<p>This then gets filled and used like this:</p>
<pre><code>void startThread(RfWindow& rfWin, AnalogOutputWindow& aoWin)
{
MasterThreadInput* input = new MasterThreadInput(rfWin, aoWin);
// other checks on the input
_beginthreadex( NULL, NULL, &MainExperimentThreadProcedure, input, NULL, NULL );
}
unsigned int __stdcall MainExperimentThreadProcedure( void* voidInput )
{
MasterThreadInput* input = (MasterThreadInput*)voidInput;
try
{
// And then do work.
input->rfSys.programRfGeneration();
input->aoSys.programAnalogOutputs();
// etc.
}
catch (...)
{
// handle errors
}
delete input;
return 0;
}
</code></pre>
<p>This example code should be very representative of the real thing, except that in the real thing there are 5 windows, many more objects to fill (about 15 in total), and a much more complicated thread procedure - it's a big worker thread. I thought about using smart pointers instead of references considering the seemingly awkward constructor needed to initialize the references, and since I was using raw pointers before these references. However, considering that I don't actually need the worker thread to manage the memory for these objects (the objects will exist as long as the windows do, and the windows will exist for the entire program), it seems that I should just try to avoid pointers all-together. Does this code follow best practices regarding managing memory and shared access in multitheaded c++ applications? Are there ways to improve on this organization? It's a very important part of the control system, so I'd like to get it right.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:41:14.327",
"Id": "216678",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"memory-management"
],
"Title": "Initializing and managing many references in multithreaded control application"
} | 216678 |
<p>I have a set of classes that have similar funcionality but very different interfaces. I created two interface classes with polymorphic methods so I can operate over then. When creating calling the methods, I have to pass a set of parameters, in this case a JSON file, that is also different for each class. Is there a way to create a generic interface without having to do ifs to select which parameter to pass to each class?</p>
<pre><code>import library_A
import library_B
import json
class ApproachA():
def __init__(self, params):
self.params = params
self.entity = library_A.Model(self.params)
def run(self, data):
return self.entity(data)
class ApproachB():
def __init__(self, params):
self.params = parse_params(params)
self.entity = library_B.Model(self.params)
def run(self, data):
real_data = do_something(data)
return self.entity(data)
if __name__ == "__main__":
with open('params.json') as f:
params = json.loads(f)
entity_list = []
# here lies the problem
for key, param in params.items():
if key == "model_a":
entity_list.append(Approach_A(param))
elif key == "model_b":
entity_list.append(Approach_B(param))
</code></pre>
<p>while the JSON parameter file is as follows:</p>
<pre><code>{
"model_a": {"param_1":10, "param_2":22},
"model_b": {"thing":"strudel", "param_cc": 102, "talk":False}
}
</code></pre>
<p>I definitely want to avoid these ifs sequences and couplings, as things similar to these tests have to be done in several places in the code. I also would like to avoid an abstract base class. I´m trying to keep things as functional as possible, without heavy OO concepts.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T00:30:21.847",
"Id": "419153",
"Score": "1",
"body": "It looks like you're calling `transpose` on a dict. I'm confused - why is this expected to work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T00:51:23.280",
"Id": "419156",
"Score": "0",
"body": "Does the JSON file contain both model_a and model_b data always? Or are you combining the data further up/earlier in the procedure?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:06:04.497",
"Id": "419217",
"Score": "0",
"body": "I´ll be combining the data further, this is just a demonstration of my process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:06:48.690",
"Id": "419219",
"Score": "0",
"body": "`transpose` here was supposed to represent an operation done on the data, to show that the two interface classes are distinct. I´ll edit the code to be more realistic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:51:14.713",
"Id": "419235",
"Score": "0",
"body": "Why don't you simply define `params = {ApproachA: {\"param_1\": 10, …}, …}`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T14:07:33.210",
"Id": "419237",
"Score": "0",
"body": "Usually the parameter dict here is a external JSON file and i would need to do an eval, right?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T18:46:07.353",
"Id": "216679",
"Score": "2",
"Tags": [
"python",
"object-oriented",
"functional-programming"
],
"Title": "Dispatch different parameters to different classes with single interface"
} | 216679 |
<p>This is just a little number guessing game. I know it's simple but I am a newbie in C and I think such a little example can be enough for finding simple design flaws that can than be eliminated.</p>
<p>If you know how parts of the code can be written more beautiful and more safe, please let me know!</p>
<pre><code>/*
* In this program the user has to guess a number between 1 and 99.
* He has six tries.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generate_random_number(int lower_range, int upper_range)
{
srand(time(0));
return (rand() % (upper_range - lower_range + 1)) + lower_range;
}
// this function stops the program until useless input is entered
void pause()
{
int useless;
scanf("%i", &useless);
}
int main()
{
// generate random number
const int lower_range = 1;
const int upper_range = 99;
const int random_number = generate_random_number(lower_range, upper_range);
// start of game
printf("You have to guess a number between 1 and 99.\n");
printf("You have six tries.\n");
const int tries = 6;
for (int i = 0; i < tries; i++)
{
printf("> ");
int guess;
scanf("%i", &guess);
if (guess > random_number)
{
printf("The secret number is smaller.\n");
}
else if (guess < random_number)
{
printf("The secret number is higher\n");
}
else if (guess == random_number)
{
printf("You found the secret number!\n");
pause();
return 0;
}
}
printf("You haven't found the secret number.\n");
printf("The secret number was %i.\n", random_number);
pause();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:37:54.197",
"Id": "419194",
"Score": "1",
"body": "This is a great exercise btw. In trying to get as few guesses as possible, you as a human will (hopefully) end up using what's known as \"binary search\", splitting the range of possible candidate numbers in 2 over and over until finding the number. This happens to be the most efficient way of searching and you'll encounter this again when studying algorithm theory later on. This example helps one understand why it is the most efficient."
}
] | [
{
"body": "<p>This looks quite good code. You've avoided many of the common mistakes.</p>\n\n<p>Here are the things I spotted as I walked through. Most of them are quite minor; the only serious issue is the handling of invalid user input.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>srand(time(0));\n</code></pre>\n</blockquote>\n\n<p>Don't do this every time you want a random number - a random number generator is intended to be seeded just once. So move the <code>srand()</code> call to the beginning of `main().</p>\n\n<p>(Yes, I know this program calls <code>generate_random_number()</code> only once. But we shouldn't need to have that knowledge, and we might want to change that behaviour, or to re-use this function in another program.)</p>\n\n<hr>\n\n<blockquote>\n<pre><code>// this function stops the program until useless input is entered\n</code></pre>\n</blockquote>\n\n<p>What's the point? That just annoys the user, who would naturally expect to be returned to their shell after executing a program. This just makes it look like the program is not responding. Also, the <code>useless</code> variable is unnecessary - add the <code>*</code> modifier to the <code>%i</code> conversion to inhibit assignment.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>int main()\n</code></pre>\n</blockquote>\n\n<p>This says that <code>main()</code> can be called with an <em>unspecified</em> number of arguments. Instead, prefer to explicitly declare that it takes <em>no</em> arguments:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>printf(\"You have to guess a number between 1 and 99.\\n\");\n</code></pre>\n</blockquote>\n\n<p>When the output is a fixed string ending in newline, we can use <code>puts()</code> instead of <code>printf()</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> int guess;\n scanf(\"%i\", &guess);\n</code></pre>\n</blockquote>\n\n<p>If something that's not a number is entered, then <code>scanf()</code> will fail and <code>guess</code> will be uninitialized (that's Undefined Behaviour, which is Not A Good Thing). We really, really need to check that <code>scanf()</code> successfully converts 1 input, and take some recovery action if not:</p>\n\n<pre><code>int status;\nwhile ((status == scanf(\"%i\", &guess)) != 1) {\n if (status == EOF) {\n fprintf(stderr, \"Read error!\\n\");\n exit 1;\n }\n scanf(\"%*[^\\n]\"); // discard input\n printf(\"? >\");\n}\n</code></pre>\n\n<p>Correctly handling input (and, in particular, unexpected input) is difficult in C!</p>\n\n<hr>\n\n<blockquote>\n<pre><code> else if (guess == random_number)\n</code></pre>\n</blockquote>\n\n<p>The <code>if</code> is redundant here, as we've eliminated all other possibilities. So that can be simply <code>else</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:00:53.463",
"Id": "216710",
"ParentId": "216681",
"Score": "1"
}
},
{
"body": "<p>Overall pretty decent beginner-level program. It is good that you use <code>const</code> variables for numeric constants instead of just \"hard-coding\" them into the source.</p>\n\n<ul>\n<li><code>void pause()</code> and <code>int main()</code> etc with empty parenthesis is obsolete style. In C this means \"take any parameter\" (unlike C++ where it is equivalent to <code>(void)</code>). Never use this form in C, use <code>void pause(void)</code>.</li>\n<li>Your pause function should take accept any keystroke and not just integers. Just replace it with <code>getchar()</code>.</li>\n<li>In general you should only call <code>srand</code> once from your program. That's ok in this case, but for the future, be careful not to hide it inside a function that is called repetively. See <a href=\"https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once\">https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once</a>.</li>\n<li>Multiple returns from a program can be hard to read, especially when done from inner blocks. Consider just breaking the loop, then handle the results separately and return only once, at the end of main(). Example below.</li>\n</ul>\n\n<hr>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <stdbool.h>\n\nint generate_random_number(int lower_range, int upper_range) \n{\n srand(time(0));\n return (rand() % (upper_range - lower_range + 1)) + lower_range; \n}\n\n\nint main (void)\n{ \n // generate random number\n const int lower_range = 1;\n const int upper_range = 99;\n const int random_number = generate_random_number(lower_range, upper_range);\n\n // start of game\n printf(\"You have to guess a number between 1 and 99.\\n\");\n printf(\"You have six tries.\\n\");\n const int tries = 6;\n bool found=false;\n for (int i = 0; i < tries; i++)\n {\n printf(\"> \");\n int guess;\n scanf(\"%i\", &guess);\n\n if (guess > random_number)\n {\n printf(\"The secret number is smaller.\\n\");\n }\n else if (guess < random_number)\n {\n printf(\"The secret number is higher\\n\");\n }\n else if (guess == random_number)\n {\n found = true;\n break;\n }\n }\n\n if(found)\n {\n printf(\"You found the secret number!\\n\");\n }\n else\n {\n printf(\"You haven't found the secret number.\\n\");\n }\n printf(\"The secret number was %i.\\n\", random_number);\n getchar();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:35:48.310",
"Id": "216715",
"ParentId": "216681",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216710",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T19:25:33.740",
"Id": "216681",
"Score": "3",
"Tags": [
"beginner",
"c",
"random",
"console",
"number-guessing-game"
],
"Title": "Number guessing game in C"
} | 216681 |
<p><strong>This is a problem I find a lot!!</strong> Can I achieve this goal without consuming so much time? </p>
<p>My code below achieves what I want it to achieve. However, I believe it could be a lot more efficient and Pythonic.</p>
<p><strong>PROBLEM:</strong>
I want to extract summary data from a larger dataset and I only know how to do so utilizing nested For loops. For example, I have a large dataset containing golf data, and I would like to extract summary statistics for the individual golf holes. </p>
<p>This code creates a scoring distribution and mean score for each Season-Hole-Round-Score vs. Par combination (48 rows in total).</p>
<pre><code>import numpy as np
import pandas as pd
import itertools
seasons = [2001,2001,2001,2001,2002,2002,2002,2002]
holes = [1,1,2,2,1,1,2,2]
rounds = [3,4,3,4,3,4,3,4]
scores = [1,-1,0,0,0,1,-1,1] # actual scores vs. par
df = pd.DataFrame({'season' : seasons, 'hole': holes, 'round':rounds, 'score': scores})
all_seasons = set(seasons); all_holes = set(holes); all_scores = [-1,0,1]
all_rounds = ["R3","R4","Weekend"] #some averages combine rounds
round_iter = np.arange(0,4) #position of rounds list
round_ids = [[3],[4],[3,4]] # weekend incldues rounds 3 and 4
hold_list = [] #blank list
for season,round,hole in itertools.product(all_seasons,round_iter,all_holes):
hold_data = df[((df['season'] == season) & (df['hole'] == hole))
& (df['round'].isin(round_ids[round-1]))]
mean_score = hold_data['score'].mean()
vspar_distro = hold_data['score'].value_counts().to_dict()
for score in all_scores:
count_score = 0
if score in vspar_distro:
count_score = vspar_distro[score]
hold_list.append([season,all_rounds[round-1]
,hole,mean_score,score,count_score])
historical_df = pd.DataFrame(hold_list,columns
= ['season','round','hole','mean_score','vspar_score','count'])
</code></pre>
<p>This produces the df that I desire (here are the first 5 rows), but applying this to a file with 100k+ records takes a long time and I believe there is a more efficient way. Thanks!</p>
<pre class="lang-none prettyprint-override"><code> season round hole mean_score vspar_score count
0 2001 Weekend 1 0.0 -1 1
1 2001 Weekend 1 0.0 0 0
2 2001 Weekend 1 0.0 1 1
3 2001 Weekend 2 0.0 -1 0
4 2001 Weekend 2 0.0 0 2
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:14:46.593",
"Id": "216684",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Iteratively Build a Summary Dataset in an Effective Way"
} | 216684 |
<p>A user wrote an issue asking if inside the bio (or any arbitrary tag), any tagged accounts can be automatically linked like on Github.</p>
<p>I gave them this function:</p>
<pre class="lang-js prettyprint-override"><code> <script>
let bio = "The coolest company to work for is @github! There is also @aws and @microsoft.";
let linkedBio = "";
let found = false;
let link = "";
for (let i = 0; i < bio.length; i++) {
let currentChar = bio[i];
if (currentChar.startsWith("@")) {
link += currentChar;
found = true;
continue // we don't need to look at other chars until next iterations
}
if (found) {
if (/[^A-Za-z0-9]/.test(currentChar)) { // we found the end of the link (you can add more special chars to this)
let tag = "<a href=https://github.com/" + link.substr(1) + ">" + link + "</a>"
linkedBio += tag + currentChar // we add the special char at the end of the tag so that it actually appears, otherwise it does not
link = "";
found = false;
} else {
link += currentChar;
}
} else {
linkedBio += currentChar;
}
}
if (link.length > 0) { // means we need to add a link that is the last possible thing without anything after it
let tag = "<a href=https://github.com/" + link.substr(1) + ">" + link + "</a>"
linkedBio += tag
}
document.getElementById("bio").innerHTML = linkedBio
</script>
</code></pre>
<p>I was going to use <code>string.split(" ")</code>, but then I realized that if I did that I would destroy the specific formatting of the text if I used <code>array.join(" ")</code> after all of the formatting changes.</p>
<p>Ex:
Original: "I work for the coolest companies: @aws, @microsoft, and @apple"</p>
<p>Joined: "I work for the coolest companies: @aws , @microsoft , and @apple"</p>
<p>The commas are messed up.</p>
<p>Is there a way to slim it down and/or simplify it? JS isn't my strongest language.</p>
| [] | [
{
"body": "<p>The function you want is <code>replace</code>:</p>\n\n<pre><code>function link_ats(text) { \n return text.replace( /@(\\w+)/g, '<a href=https://github.com/$1>@$1</a>' ) \n}\n\ndocument.getElementById(\"bio\").innerHTML = link_ats(\"The coolest company to work for is @github! There is also @aws and @microsoft.\", \"bio\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T22:13:24.733",
"Id": "216687",
"ParentId": "216685",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216687",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T20:30:35.973",
"Id": "216685",
"Score": "3",
"Tags": [
"javascript",
"dom"
],
"Title": "Replacing GitHub usernames with links"
} | 216685 |
<p>I'm setting up new API to Setup LocalAccounts and need your advice on how to design the API with CQS</p>
<p>some background :
<code>LocalAccount</code> Is Account that related to private customer or corporate customer and contain Debit or credit Account details with one or more cards (plastic and 1 virtual )
Example of <code>LocalAccounts</code> : <code>PrivateDebitLocalAccount</code> , <code>CorpoeateCreditLocalAccount</code>, <code>PrivateCreditLocalAccount</code> ...</p>
<p>I want to use CQS to expose command for the Action on those entity : <code>AddNewLocalAccountCommand</code>, <code>UpadteLocalAccountCommand</code> and so on ..</p>
<p>My client doesn't want to work with lots of commands for the same action : 4 command to <code>AddNew</code> for <code>PrivatedebitLocalAccount</code>, <code>CorpoeateCreditLocalAccount</code>,
<code>CorpoeateDebitLocalAccount</code>, <code>PrivateCreditLocalAccount</code> and then use 4 command to update and 4 Delete commands ...and so on</p>
<p>So I decided to Expose one Command for create all 4 types of localAccount <code>AddNewLocalAccount</code> that will get flat object with all fields and in the WebAPI inside I map the request to my command (I Do this for Backward comparability on the Contract changes for My command ) and send it to Handler using MediatR library By Jimmy Bogard.
In The handler I Call <code>AggrigateLocalAccountServices</code> with 2 dependencies of <code>ServiceFactories</code> to get back the Domain object i need : <code>AccountServiceFactory</code> and <code>CustomerServiceFact</code>, this will help to get the relevant domain object from the command : <code>Customer</code> (private or customer) and <code>Account</code> based on <code>AccountType</code> in the command (credit or debit)</p>
<p>Example of <code>AddNewCorporateLocalAccountRequest</code></p>
<pre><code>var LocalAccountData = new LocalAccountData(Guid.NewGuid())
{
CustomerType = CustomerTypes.Corporate,
AccountTypes = AccountTypes.Credit,
CreditLimit = 200,
Deposit = 100,
CompanyId = "43545",
MonthlyLimit = 50,
FirstName = "ddd",
LastName = "deee",
};
</code></pre>
<p>In My Controller WebApi I Maped the Request to command even it is mixed fields from Debit and credit ..</p>
<pre><code>var command = new AddNewLocalAccountCommand(LocalAccountData.Id ==
Guid.Empty ? Guid.NewGuid() : LocalAccountData.Id)
{
CompanyId = LocalAccountData.CompanyId, //Corporate field
CustomerType = LocalAccountData.CustomerType, //define the
CustomerType (private/Corporate) for LocalAccountFactory (customer)
AccountTypes = LocalAccountData.AccountTypes,//define the
AccountType(debit/credit) for AccountFactory (customer)
CreditLimit = LocalAccountData.CreditLimit, //Credit data
};
//send to commandHandler using Mediatr :
var x = new AddNewLocalAccountCommandHandler(
new LocalAccountAggregator(
localAccountServiceFactory, accountFactoryService));
var result = mediatR.Send(command);
</code></pre>
<p>In my commandHandler method</p>
<pre><code>public void Handle(AddNewLocalAccountCommand command){
// map again all data to local account DTO so i can ask the factories in AggRoot to extract the domain i need
var localAccountData = new LocalAccountData(command.Id)
{
CustomerType = command.CustomerType,
AccountTypes = command.AccountTypes,
Balance = command.Balance,
....
};
var customerAccontId =
this._localAccountAggregator
.AddNewLocalAccount(localAccountData);
};
</code></pre>
<p>My Agg root class I expose interface for adding the localAccount and this is how is the implementation </p>
<pre><code>public virtual Guid AddNewLocalAccount(ILocalAccountData data)
{
var localAccount = CreateLocalAccount(data);
var vc = CreateVirtualCard();
localAccount.Accounts.Cards.Add(vc);
// now I need to decide where to map from localAccount to my EF
// object, here or should it be inside the Service that know the
// right type of tables to be mapped
customerDto = Mapper.Map<localAccount, Customer>(request);
_context.Customers.Add(customerDto);
_context.SaveChanges();
return Guid.NewGuid();
}
private ILocalAccount CreateLocalAccount (ILocalAccountData data)
{
var accountService =
_accountFactoryService.GetService(data.AccountTypes);
var localAccountFactoryService =
_localAccountFactoryService.GetService(data);
//create method will be call from the right LocalAccountService
that get the right domain object.
return localAccountFactoryService.Create(data);
}
</code></pre>
<p>Here is one of the service that can create the right localAccount Type based on the data from client :</p>
<pre><code>public class CorporateLocalAccountService : ILocalAccountService
{
private IAccountService _account;
public CorporateLocalAccountService(IAccountService account)
{
_account = account;
}
public ILocalAccount CreateData(ILocalAccountData data)
{
return new CorporateLocalAccount(new Entity(data.Id))
{
Account = _account.Create(data),
Contact = new Person { LastName = data.LastName, FirstName = data.FirstName, MobilePhoneNumber = data.MobilePhone },
CompanyId = data.CompanyId,
CompanyName = data.CompanyName,
};
}
}
</code></pre>
<p>}</p>
<p>I have some question about this design :</p>
<ol>
<li><p>My Client Doesn't know my internal Domain so they can do mistake and send fields of debit account in Credit Account request as i Use one container object , Beside sending JSON example of possible valid contract Or Change from Flat fields to object Inside my <code>LocalAccountData</code> : <code>DebitAccountData</code>, <code>CreditAccountData</code>, <code>PrivateData</code>, <code>CorporateData</code>. How can i tell my client not do do mistake in the request? Should I change my API request ?</p></li>
<li><p>In my <code>CorporateLocalAccountService</code> I return the domain object to the aggregate , should this class create the data in DB using EF or just return domain model and Aggregate will create it ?</p></li>
<li><p>I'm Working with the Command Query and in <code>CommandHander</code> I call the <code>Aggregate</code> Object that need to create localAccount (insert data to 4-5 tables and create virtual Card as a result of creating the <code>LocalAccount</code> and send it back to client ) How Do I work with my EntityFramework ? I mean do I need repositories or should i call the <code>DBContext</code> and use the EF objects inside the Aggregate directly and avoid Repositories ? //
I warp the commandHandler with <code>TransactionCommandHandler</code> so Do I need the transaction scope in the Aggregate class or i can use the transaction scope from my commandHandler decorator ?</p></li>
</ol>
<p>Thanks</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T00:35:32.887",
"Id": "419154",
"Score": "3",
"body": "is this how the indentation looks in your editor? If not can you edit the question to reflect your actual indentation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:01:42.363",
"Id": "419186",
"Score": "0",
"body": "Not sure I understand what is missing , i Just paste part of the code that relevant to my question ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:31:47.727",
"Id": "419234",
"Score": "0",
"body": "The indentation consists of the spaces to the left, at the beginning of the lines. It is important, because it makes it easier to find matching braces and to understand the syntactical structure of the code. Your indentation was wrong - I corrected it."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-01T22:18:20.603",
"Id": "216688",
"Score": "1",
"Tags": [
"c#",
"asp.net-web-api",
"ddd"
],
"Title": "Design Web API with Command Handler"
} | 216688 |
<p>One of my friends was creating an app with following requirements and having been someone with slightly more coding experience, I wanted to help:</p>
<blockquote>
<p>Create a calculator that does one arithmetic operation at a time and
prints the result to the screen.</p>
<ul>
<li>Prompt the user for a number.</li>
<li>Prompt the user for an operation (+ - / *).</li>
<li>Prompt the user for another number.</li>
<li>Perform the operation.</li>
<li>Print the result to the screen.</li>
<li>Repeat until the user types in “quit” at any of the prompts.</li>
</ul>
</blockquote>
<pre><code>using System;
namespace Calc
{
class Program
{
static void Main(string[] args)
{
// We are creating the strings and integers we need beforehand.
// These will be updated according to the user input.
string firstInput = "";
string secondInput = "";
string operand = "";
double x = 0;
double y = 0;
while (true)
{
Console.WriteLine("You can quit any time by typing \"quit\".");
Console.WriteLine("Please enter the first number:");
First:
firstInput = Console.ReadLine();
try
{
if (firstInput.ToLower() != "quit")
{
x = double.Parse(firstInput);
}
else
{
break;
}
}
catch
{
// If we are here, that means erroneous input was given.
Console.WriteLine("Invalid input. Please enter an integer.");
goto First;
}
Console.WriteLine("Please enter an operand (+, -, *, /):");
Second:
operand = Console.ReadLine();
//We need to make sure user has entered a proper operator.
if (operand.ToLower() == "quit")
{
break;
}
else if (!((operand == "+") || (operand == "-") || (operand == "*") || (operand == "/")))
{
Console.WriteLine("Invalid input. Please enter one of the following: +, - , *, /.");
goto Second;
}
else
{
// No problem. Keep going.
}
Console.WriteLine("Please enter the second number:");
Third:
secondInput = Console.ReadLine();
try
{
if (secondInput.ToLower() != "quit")
{
y = double.Parse(secondInput);
}
else
{
break;
}
}
catch
{
// If we are here, that means erroneous input was given.
Console.WriteLine("Invalid input. Please enter an integer.");
goto Third;
}
// We have all we need if program has run up until this line.
// We can now check which operand is entered to determine the result.
if (operand == "+")
{
Console.WriteLine($"{firstInput} + {secondInput} = {x + y}");
}
else if (operand == "-")
{
Console.WriteLine($"{firstInput} - {secondInput} = {x - y}");
}
else if (operand == "*")
{
Console.WriteLine($"{firstInput} * {secondInput} = {x * y}");
}
else if (operand == "/")
{
Console.WriteLine($"{firstInput} / {secondInput} = {x / y}");
}
else
{
Console.WriteLine("Error! You must have entered invalid input.");
}
Console.WriteLine("Press any key to throw me away like a Kleenex.");
Console.ReadKey();
break;
}
}
}
}
</code></pre>
<p>Couple things I've attempted/found out so far:</p>
<ul>
<li><p>Instead of checking whether "quit" has been entered every time, I
tried to use following with no success: <code>while (!((firstInput.ToLower() == "quit") || (secondInput.ToLower() == "quit") || (operand.ToLower() == "quit")))</code></p></li>
<li><p>Apparently C# has "String Interpolation" too, like in JS (I guess with ES6) which was considered as a good practice among my colleagues if nothing else, for readability.</p></li>
<li><p>I know usage of "goto" is not considered well usually. Though it seemed quite practical with the labels. Priorly, I had thought it was only used in switch cases.</p></li>
<li><p>About exception handling, I haven't had much use before when I messed around in Java, but I suppose it's one of the most fundamental features of higher level languages to keep program more prune to run-time errors. This one particularly came to my head when I realized user could potentially enter some input that can't be parsed properly.</p></li>
<li><p>I don't know, there's not much to do given that problem and implementation is quite simple, but I still think it's a good opportunity to develop good practices if I were to somewhat get involved with gaming development, for example (Unity etc.).</p></li>
</ul>
<p>I've been recently coding Haskell, Python, JavaScript and I have C/C++ background but this is the first time I laid my hands on an .NET/C# app.
I have tinkered with Java before, but I don't really have much experience with higher level languages. Anyways, long story short, I'd like to see what could have been done better and what are the things that are considered as good/bad practice that could be particularly viewed in this small code snippet.</p>
<p><strong>P.S</strong>: I'm a bit aware that comments are a bit overly-done, but it's intentional for obvious reasons. Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:32:38.930",
"Id": "419223",
"Score": "0",
"body": "I would use \"TryParse\" instead of Parse, maybe even int.TryParse (you are looking for an integer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T12:52:55.263",
"Id": "425960",
"Score": "0",
"body": "There is a very similar question that might interest you: https://codereview.stackexchange.com/questions/217792/two-integers-one-line-calculator/"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T02:18:22.370",
"Id": "216691",
"Score": "1",
"Tags": [
"c#",
"beginner",
".net"
],
"Title": "An arithmetic operation app in C#"
} | 216691 |
<p>Given a dictionary where 1:a , 2:b ... 26:z. I need to find all the possible letter combinations that can be formed from the three digits.</p>
<p>Either each digit should translate to a letter individually or you can combine adjacent digits to check for a letter. You can't change the order of the digits. For example -</p>
<p>121 translates to aba, au, la;</p>
<p>151 translates to aea, oa;</p>
<p>101 translates to ja; </p>
<p>I was able to get this working but I feel my code is not very "pythonic". I am trying to figure out a more efficient & python-like solution for this problem.</p>
<pre><code># creating the dict that has keys as digits and values as letters
root_dict = {}
for num in range(0,26):
root_dict[str(num+1)] = string.ascii_lowercase[num]
# asking user for a three digit number
sequence_to_convert = raw_input('Enter three digit number \n')
# storing all possible permutations from the three digit number
first_permutation = sequence_to_convert[0]
second_permutation = sequence_to_convert[1]
third_permutation = sequence_to_convert[2]
fourth_permutation = sequence_to_convert[0]+sequence_to_convert[1]
fifth_permutation = sequence_to_convert[1]+sequence_to_convert[2]
# checking if the permutations exist in the dict, if so print corresponding letters
if first_permutation in root_dict and second_permutation in root_dict and third_permutation in root_dict:
print root_dict[first_permutation]+root_dict[second_permutation]+root_dict[third_permutation]
if first_permutation in root_dict and fifth_permutation in root_dict:
print root_dict[first_permutation]+root_dict[fifth_permutation]
if fourth_permutation in root_dict and third_permutation in root_dict:
print root_dict[fourth_permutation]+root_dict[third_permutation]
</code></pre>
| [] | [
{
"body": "<p>First, <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">Python 2 is going to be no longer supported in less than a year</a>. If you are starting to learn Python now, learn Python 3. In your code the only differences are that <code>print</code> is a function now and no longer an expression (so you need <code>()</code>) and that <code>raw_input</code> was renamed <code>input</code> (and the Python 2 <code>input</code> basically no longer exists).</p>\n\n<p>Your building of the root dictionary can be simplified a bit using a dictionary comprehension:</p>\n\n<pre><code>from string import ascii_lowercase\n\nnum_to_letter = {str(i): c for i, c in enumerate(ascii_lowercase, 1)}\n</code></pre>\n\n<p>For the first three different permutations you can use tuple unpacking:</p>\n\n<pre><code>first, second, third = sequence_to_convert\n</code></pre>\n\n<p>Note that you are currently not validating if the user entered a valid string. The minimum you probably want is this:</p>\n\n<pre><code>from string import digits\ndigits = set(digits)\n\nsequence_to_convert = input('Enter three digit number \\n')\nif len(sequence_to_convert) != 3:\n raise ValueError(\"Entered sequence not the right length (3)\")\nif not all(x in digits for x in sequence_to_convert):\n raise ValueError(\"Invalid characters in input (only digits allowed)\")\n</code></pre>\n\n<p>(A previous version of this answer used <code>str.isdigit</code>, but that unfortunately returns true for digitlike strings such as <code>\"¹\"</code>...)</p>\n\n<p>Your testing and printing can also be made a bit easier by putting the possible permutations into a list and iterating over it:</p>\n\n<pre><code>permutations = [(first, second, third), (first, fifth), (fourth, third)]\nfor permutation in permutations:\n if all(x in num_to_letter for x in permutation):\n print(\"\".join(map(num_to_letter.get, permutation)))\n</code></pre>\n\n<p>However, in the end you would probably want to make this more extendable (especially to strings longer than three). For that you would need a way to get all possible one or two letter combinations, and that is hard. It is probably doable with an algorithm similar to <a href=\"https://stackoverflow.com/a/30134039/4042267\">this one</a>, but it might be worth it to ask a question on <a href=\"https://stackoverflow.com/\">Stack Overflow</a> about this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:53:24.607",
"Id": "419247",
"Score": "0",
"body": "There is a `pairwise` generator in the [Itertools recipes.](https://docs.python.org/3/library/itertools.html#itertools-recipes)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:54:27.717",
"Id": "419248",
"Score": "0",
"body": "@AustinHastings: I'm aware. But here you would need all partitions of a string into groups of one *or* two characters, not just the current and the following character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:56:09.617",
"Id": "419249",
"Score": "0",
"body": "`itertools.chain(a_string, pairwise(a_string))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:58:10.490",
"Id": "419250",
"Score": "1",
"body": "@AustinHastings: While this does work for the example with three characters (and so might be worth it to put it into an answer), it fails for more characters. For `1234`, it is missing e.g. `12,3,4`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T16:01:02.750",
"Id": "419252",
"Score": "0",
"body": "Ah, you're right. I was focused on pairing, and neglecting the \"whole word\" thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T16:02:27.317",
"Id": "419253",
"Score": "0",
"body": "@AustinHastings: It does, however, give you all possible building blocks of the permutations, but building the permutations from it is the real work..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T18:48:40.417",
"Id": "421087",
"Score": "0",
"body": "Thanks a ton guys! This has ben a huge help :) I see the errors in my ways and will work on improving !!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T03:58:33.767",
"Id": "424997",
"Score": "0",
"body": "thanks again @Graipher this is so great, I was reviewing your solution again today to understand the thought process. It is so fundamentally different than I am processing code in my head. Are there any practice questions or material you can recommend that will help me develop similar skills? I suspect it will come with MORE practice but wondering if the right study/practice material can help get me there more quickly !"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:38:54.603",
"Id": "216706",
"ParentId": "216693",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216706",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T04:30:19.987",
"Id": "216693",
"Score": "2",
"Tags": [
"python"
],
"Title": "Pythonic code to convert 3 digit number into all possible letter combinations"
} | 216693 |
<p>It is my first use of classes in Python. I wanted to create something useful and try some new things as I learn this cool language: strategy pattern, testing with nanoseconds precision, curve/poly fitting, and making a graphic presentation. The budget was 150 lines of code: 50 for five Fibonacci number calculations, 50 for testing and checking the results, 50 for presentation. PyCharm was my mentor and strict format enforcer: 22 blank lines. I made it in 149
lines and then added one comment line. Could be a better “curve fit” and “poly fit” string formulas, but it will force me to go over 150 lines.</p>
<p>Here is what this program does:</p>
<ol>
<li>Calculates Fibonacci numbers from 2 to 30 by five different methods. Tests if all methods produce the same results and keep the shortest runtime from 10 tries.</li>
<li>Plots all best times in nanoseconds at four subplots: regular axes, log Y, zoom to 30000 nSec, and zoom+ to 3000 nSec.</li>
<li>It uses curve_fit from scipy and polyfit from numpy to find the best parameters for math formulas describing the time complexity of these Fibonacci algorithms.</li>
</ol>
<p>I was happy to see the recursion as (446 * 1.62 ** n) just after the first tests and bug fixing - that is a theoretical O(φ**n) or 1.6180339887… </p>
<p>Critique and suggestion on how to write a better code are welcome.</p>
<p>Should I put all <strong>import</strong> statement at the top?</p>
<p>Here is the code: </p>
<pre><code>from abc import ABCMeta, abstractmethod
from cachetools import cached, TTLCache
class Fibonacci(metaclass=ABCMeta): # Abstract prototype ######################
def fibonacci(self, n):
if isinstance(n, int) and n >= 0:
return self._fibonacci(n) if n >= 2 else [0, 1][n]
raise ValueError
@abstractmethod
def _fibonacci(self, n):
pass
class FibonacciRecursion(Fibonacci): # 1. Classic and also naive computation ##
def _fibonacci(self, n):
return self.fibonacci(n - 1) + self.fibonacci(n - 2)
class FibonacciCacheTools(Fibonacci): # 2. The cache fixes bad algorithm choice
cache = TTLCache(maxsize=1500, ttl=3600)
@cached(cache)
def _fibonacci(self, n):
return self.fibonacci(n - 1) + self.fibonacci(n - 2)
class FibonacciAddition(Fibonacci): # 3. It is O(n), not O(2**n) as before ####
def _fibonacci(self, n):
f0, f1 = 0, 1
for _ in range(1, n):
f0, f1 = f1, f0 + f1
return f1
class FibonacciAdditionPlus(FibonacciAddition): # 4. Exploiting the test: O(1)
def __init__(self):
self._n = 2
self._f0 = 1
self._f1 = 1
def _fibonacci(self, n):
if n == self._n:
return self._f1
if n < self._n:
self.__init__()
for _ in range(self._n, n):
self._f0, self._f1 = self._f1, self._f0 + self._f1
self._n = n
return self._f1
class FibonacciFormula(Fibonacci): # 5. Formula of Binet, Moivre, and Bernoulli
# Exact integer until Fibonacci(71)
# Float error at Fibonacci(1475) OverflowError: (34, 'Result too large')
S5 = 5.0 ** 0.5 # Square root of 5
def _fibonacci(self, n):
phi = (1.0 + FibonacciFormula.S5) / 2.0 # φ Python speaks greek!
psi = (1.0 - FibonacciFormula.S5) / 2.0 # ψ PyCharm doesn't like it ;-(
return int((phi ** n - psi ** n) / FibonacciFormula.S5)
if __name__ == '__main__': # Testing ... ######################################
import platform
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
def func1(x, a, b): # function to fit exponential Fibonacci
return '%f * %f**x' % (a, np.exp(b)) if x is None else a*np.exp(b*x)
def func2(x, a, b, c): # function to fit with cubic curve
return '%f + %f*x + %f*x**2' % (a, b, c) if x is None else a+x*(b+c*x)
def first_test(fibonacci_max, repeat): # Collect times, curve fit, and plot
methods = [ # Function to test, color, poly fit, curve fit
[FibonacciRecursion(), 'blue', 2, func1],
[FibonacciCacheTools(), 'orange', 1, func2],
[FibonacciAddition(), 'green', 1, func2],
[FibonacciAdditionPlus(), 'red', 1, func2],
[FibonacciFormula(), 'purple', 1, func2],
]
print('Number,Fibonacci,Times for all methods in nanoseconds')
n_max = fibonacci_max - 1 # we start from n=2 (0, 1 - the same time)
y = [[0 for _ in range(n_max)] for _ in methods]
for j in range(n_max): # Run tests and collect times in array y #######
n = j + 2
old = None
for i, method in enumerate(methods):
best = None
for k in range(repeat):
start = time.perf_counter_ns()
result = method[0].fibonacci(n)
stop = time.perf_counter_ns()
duration = stop - start
if best is None or duration < best:
best = duration
if old is None:
old = result
elif result != old:
print(
'Error: different results %d and %d for function %s'
' F(%d) in call # %d,' %
(old, result, method[0].fibonacci.__name__, n, k+1))
exit(1)
if i == 0:
print(n, ',', old, sep='', end='')
print(',', best, sep='', end='')
y[i][j] = best
print()
plt.figure(1) # Start plotting ########################################
plt.suptitle('Time(n) Complexity of Fibonacci Algorithms. n = 2,3,...,'
'%d,%d' % (n_max, fibonacci_max))
x = np.array([i + 2 for i in range(n_max)])
plt.subplots_adjust(hspace=0.3)
for i in range(4):
plt.subplot(221 + i)
for j, m in enumerate(methods):
s = str(m[0].__class__.__name__)[len('Fibonacci'):]
plt.plot(x, y[j], 'tab:' + m[1], label=s)
plt.title(['time in nanoseconds', 'log(Time)', 'zoom', 'zoom+'][i])
plt.grid(True)
if i == 0:
plt.legend()
elif i == 1:
plt.semilogy()
else:
x_min, x_max, _, _ = plt.axis()
plt.axis([x_min, x_max, 0.0, 30000.0 if i == 2 else 3000.0])
for i, m in enumerate(methods): # Curve and poly fitting ##############
plt.figure(2 + i)
name = str(m[0].__class__.__name__)[len('Fibonacci'):]
plt.plot(x, y[i], 'ko', label=name)
c, _ = curve_fit(m[3], x, y[i])
c_name = 'curve fit:' + m[3](None, *c)
plt.plot(x, m[3](x, *c), 'y-', label=c_name)
p = np.poly1d(np.polyfit(x, y[i], m[2]))
p_name = 'poly fit: ' + str(p)
plt.plot(x, p(x), m[1], label=p_name)
plt.legend()
print('%s\n%s\n%s\n' % (name, c_name, p_name))
plt.show()
print('Python version :', platform.python_version())
print(' build :', platform.python_build())
print(' compiler :\n', platform.python_compiler())
first_test(fibonacci_max=30, repeat=10)
</code></pre>
<p>The output:</p>
<pre class="lang-none prettyprint-override"><code>$ python fibonacci.py
Python version : 3.7.3
build : ('v3.7.3:ef4ec6ed12', 'Mar 25 2019 16:52:21')
compiler :
Clang 6.0 (clang-600.0.57)
Number,Fibonacci,Times for all methods in nanoseconds
2,1,1027,2598,731,526,874
3,2,1638,2516,769,523,956
4,3,2818,2470,806,532,904
5,5,4592,2413,840,526,902
6,8,7571,2531,936,562,955
7,13,12376,2490,909,538,999
8,21,20528,2588,972,551,973
9,34,33349,2628,1074,581,1037
10,55,60107,2782,1116,581,997
11,89,85465,2421,1056,534,939
12,144,137395,2429,1101,534,942
13,233,222623,2411,1136,539,955
14,377,360054,2476,1216,551,938
15,610,600066,2736,1332,563,1006
16,987,971239,2529,1323,541,937
17,1597,1575092,2479,1359,552,937
18,2584,2565900,2632,1464,563,962
19,4181,4071666,2583,1485,555,953
20,6765,6630634,2503,1481,532,914
21,10946,10843455,2527,1571,522,930
22,17711,18277770,2617,1646,548,952
23,28657,28838223,2620,1739,573,967
24,46368,47167582,2481,1713,543,932
25,75025,77326177,2481,1709,531,909
26,121393,126154837,2587,1799,546,944
27,196418,205083621,2527,1857,548,942
28,317811,329818895,2444,1822,531,952
29,514229,533409650,2493,1932,551,946
30,832040,866064386,2509,1967,553,947
Recursion
curve fit:448.753271 * 1.619991**x
poly fit: 2
1.751e+06 x - 4.225e+07 x + 1.829e+08
CacheTools
curve fit:2492.458456 + 7.778994*x + -0.252776*x**2
poly fit:
-0.3099 x + 2539
Addition
curve fit:636.162562 + 42.475661*x + 0.074421*x**2
poly fit:
44.86 x + 622.3
AdditionPlus
curve fit:528.372414 + 2.642894*x + -0.076063*x**2
poly fit:
0.2089 x + 542.5
Formula
curve fit:920.230213 + 5.076194*x + -0.163003*x**2
poly fit:
-0.1399 x + 950.5
</code></pre>
<p>Graphics: <a href="https://i.stack.imgur.com/8Reb9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8Reb9.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/oSgBg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oSgBg.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:58:43.047",
"Id": "419170",
"Score": "0",
"body": "Welcome to Code Review! Well done on presenting intent and constraints upfront. One thing nagging me: why not choose an argument range to try and push the limits of integer representations (somehow managing run time of the plain recursive approach (and checking for deviation of \"the formula result\"))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:51:30.233",
"Id": "419189",
"Score": "0",
"body": "Thank you for the welcome and the comment. Actually, I did comment the line with \"[FibonacciRecursion(), 'blue', 2, func1],\" and \"elif result != old:\" in order to push the limit and see what will happen next: they stay steady flat O(1) except Addition O(n). Also started to write another test program to see the error in \"the formula result\" and a possibility to compensate it: the absolute error starts almost as another Fibonacci from 72 with F(n-71) range, but the relative error has a linear grow from 2.0e-15 at F(72) to 4.4e-14 at F(1314)."
}
] | [
{
"body": "<p>I'm not really sure why you used classes for your Fibonacci functions. In python it is generally better style to just use a function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T22:52:08.953",
"Id": "419282",
"Score": "0",
"body": "I started with functions but soon realized that they will benefit from common class if I want to maintain, share this project, and others contribute to it. I had the questions:\n\nHow I can enforce all functions have the same interface?\nSome of the function can benefit from initialization and storing the temporary variables between calls. How this can be done uniformly? \n How I just write a code to check the argument once and reuse for all?\nHow do I compare the performance of the same function with different parameters (cache size)? \n\nThe classes had all the answers to these my questions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T18:07:43.647",
"Id": "216739",
"ParentId": "216694",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:16:32.687",
"Id": "216694",
"Score": "4",
"Tags": [
"python",
"algorithm",
"comparative-review",
"complexity",
"fibonacci-sequence"
],
"Title": "Time(n) Complexity of Fibonacci Algorithms"
} | 216694 |
<p>I wrote a solution to the <a href="https://open.kattis.com/problems/mali" rel="nofollow noreferrer">Mali problem on Kattis</a>:</p>
<blockquote>
<p>Given inputs <em>a</em><sub>1</sub>, <em>a</em><sub>2</sub>, <em>a</em><sub>3</sub>, …, <em>a<sub>n</sub></em> and <em>b</em><sub>1</sub>, <em>b</em><sub>2</sub>, <em>b</em><sub>3</sub>, …, <em>b<sub>n</sub></em>, determine <em>n</em> pairings (<em>a<sub>i</sub></em>, <em>b<sub>j</sub></em>) such that each number in the <em>A</em> sequence is used in exactly one pairing, each number in the <em>B</em> sequence is used in exactly one pairing, and the maximum of all sums <em>a<sub>i</sub></em> + <em>b<sub>j</sub></em> is minimal.</p>
<h3>Input</h3>
<p>The first line of input contains a single integer <em>N</em> (1 ≤ <em>N</em> ≤ 100000), the number of rounds.</p>
<p>The next <em>N</em> lines contain two integers <em>A</em> and <em>B</em> (1 ≤ <em>A</em>, <em>B</em> ≤ 100), the numbers given in that round.</p>
<h3>Output</h3>
<p>The output consists of <em>N</em> lines, one for each round. Each line should contain the smallest maximal sum for that round.</p>
</blockquote>
<p>I'm fairly sure I can get the right answer 100% of the time, but the code exceeds the time limit of one second. I was wondering if you could help me optimize my code to help it run in time, or if you could explain why my code is inefficient.</p>
<pre><code>#include <iostream>
#include <vector>
int main() {
int x, c = 0, big = 0;
std::cin >> x;
std::vector<int> as, bs;
for (int i = 0; i < x; i++) {
bool founda = false, foundb = false;
int a, b;
std::cin >> a >> b;
c++;
if (c == 1) {
as.push_back(a);
bs.push_back(b);
}
else {
for (int i = 0; i < c; i++) {
if (as[i] < a || i == c-1) {
as.insert(as.begin()+i, a);
founda = true;
}
if (bs[i] < b || i == c-1) {
bs.insert(bs.begin()+i, b);
foundb = true;
}
if (founda == true && foundb == true)
break;
}
}
for (int i = 0; i < c; i++) {
if (as[i] + bs[c-1-i] > big)
big = as[i] + bs[c-1-i];
}
std::cout << big << std::endl;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T06:21:10.150",
"Id": "419172",
"Score": "0",
"body": "(Programming challenges with \"online judges\" are carefully crafted with one good solution in mind that can be coded in, say, one hour. Problem parameters (*size*) are chosen such that asymptotically inferior approaches don't complete within the time limit. The implementation platform (language) is figured in: you need to find a solution that re-uses information \"between sums/pairs\".)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T06:27:46.667",
"Id": "419173",
"Score": "0",
"body": "(For lack of code comments, I didn't try to understand your approach upfront. Integrating input and both preparatory sorts is thinking out-of-the-box!)"
}
] | [
{
"body": "<p>You are storing all of the <em>A</em> and <em>B</em> inputs in sorted vectors, basically doing an insertion sort. A few observations (two minor, one major):</p>\n\n<ol>\n<li>The <code>if (c == 1)</code> special case should be eliminated.</li>\n<li>Flag variables (<code>founda</code> and <code>foundb</code>) suck. You would be better off writing two separate <code>for</code> loops.</li>\n<li><p>Each time you insert a value, all values beyond the insertion point need to be shifted over to make room for the insertion. That means that constructing <code>as</code> and <code>bs</code> takes O(<em>N</em><sup>2</sup>) time altogether — which is unacceptable, since <em>N</em> can be very large.</p>\n\n<p>However, there are only 100 possible values of <em>A</em> and <em>B</em>. So, do a <a href=\"https://en.wikipedia.org/wiki/Counting_sort\" rel=\"nofollow noreferrer\">counting sort</a> instead, building a histogram with 100 buckets. That would be a much more efficient way to represent the same information, using O(<em>N</em>) time and a fixed amount of space.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T06:52:55.577",
"Id": "419178",
"Score": "0",
"body": "Usually a stickler for detail, I commend giving neither more nor less than the principle of (the crucial part of) a good solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:59:46.300",
"Id": "216697",
"ParentId": "216695",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216697",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:21:03.413",
"Id": "216695",
"Score": "2",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Kattis Problem 'Mali'"
} | 216695 |
<p>I am trying to solve this question:</p>
<ul>
<li>Given a list of integers, verifies if any two numbers from this list add up to another number in the same list. </li>
</ul>
<p>I came up with:</p>
<pre><code>def func(l):
sum_set = set() # using a set to store sums of two numbers.
for index in range(len(l)-1):
counter = 1
while counter + index < len(l):
sum = l[index] + l[index+counter]
sum_set.add(sum)
counter += 1
for number in l:
if number in sum_set:
return True
return False
print(func([1,2,3,4]))
print(func([1,2,1,4]))
print(func([1,1,1]))
print(func([1]))
print(func([1,2,5,9]))
print(func([2,1,1]))
print(func([1,-1,0]))
</code></pre>
<p>From the tests I ran above, my function is working. But there is at least one way I can think of my approach is lacking of:</p>
<ul>
<li>I should filter the original list to get rid of duplicate numbers. If a number appears more than 2 times, its rest of appearance should be disregarded. E.g. <code>l = [1,1,1,1,2]</code> should be optimised to <code>l = [1,1,2]</code></li>
</ul>
<p>Is there any other aspect that I can improve my code snippet on to make it more Pythonic / more efficient?</p>
| [] | [
{
"body": "<p>The thing to be concerned with when writing functions like this is the size of the data it's going to be processing. If you're only ever going to be dealing with small sets of data (less than say 100 items) then there really isn't an issue with the way this is written. At the scale of maybe tens of thousands of items this starts to be a problem. </p>\n\n<p>I'm not a data scientist or anything, I'm just a web developer and I very rarely delve into trying to optimise code, so any advice I'm giving is based on my personal experience + uni, and doesn't utilize math libraries in Python like <code>numpy</code> which you might want to look into depending on what this code is for. Another answerer could likely help more with this specific circumstance, my answer is going to be a bit more general; assuming you're going to be dealing with large amounts of data (or otherwise prematurely optimising is sometimes considered the <a href=\"https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil\">root of all evil</a>):</p>\n\n<hr>\n\n<p><strong>EDIT</strong>: <em>I just noticed that one of your examples included negative numbers, so the example code below will need to be adapted with that in mind since it affects the movement of <code>i</code> and <code>j</code>; sorry about that, but the code provided can still be run as an example with positive numbers.</em></p>\n\n<p>Ignoring data types used for the most part & how pythonic the code is, I see probably two areas for improvement. The first I'll touch on at the end in a code example & may depend a bit on your particular data-set as to how helpful it will be, but presently, the code has no chance of finishing early (assuming random inputs that'd give you an substantial speedup especially if your data is likely to find a match in the early items of the list). </p>\n\n<p>However, the primary areas for improvement can be determined through analysing your code via Big-O / Big(O) notation. I'd suggest a read of the concept if you're unfamiliar, but according to Wikipedia:</p>\n\n<blockquote>\n <p>big O notation is used to classify algorithms according to how their running time or space requirements grow as the input size grows</p>\n</blockquote>\n\n<p>Given the following section of your code:</p>\n\n<pre><code>for index in range(len(l)-1): # (1) \n ...\n while counter + index < len(l): # (2) \n ...\n sum_set.add(sum) # (3)\n ...\nfor number in l: # (4)\n</code></pre>\n\n<p>If we look at, for instance, a 100,000 element array containing the numbers between 1 and 100,000, if we run your code as it's written, we will end up running the <code>sum_set.add(sum)</code> statement (3) about 4.99 billion times. At just 10,000 elements, on my machine, the code as written takes multiple seconds to finish.</p>\n\n<p>Looking at (1), we see this statement runs through all elements in the list, therefore O(N); the time taken for the outer loop depends on a linear relationship to the input, e.g. O(N) means an input array of 200 elements, ignoring any constant time overhead, should take ~roughly~ 200x longer than an array with 1 element. Line (2) passes through N-1 elements on the first loop, then N-2, ... finally 1 item in last loop; averaging out at half as many loops as the outer index, but is still O(N) as it's linearly related to the amount of items included in the list. As you have an O(N) loop within an O(N), <a href=\"https://stackoverflow.com/questions/3179338/big-o-notation-for-triangular-numbers\">this gives it the overall O(N^2) performance. </a></p>\n\n<p>(4) is tricky to estimate, as it depends on the passed in data. Iterating through the list <code>l</code> is O(N) again, and if we assume worst case, each element in <code>sum_set</code> could be unique, i.e. if the passed in array was something like [1, 11, 111, ...], which would mean there are ~N^2 terms in <code>sum_set</code>, actually causing this loop to degrade to O(N^3) performance. Best case, the <code>sum_set</code> is very small, but even assuming only 1 item, that would still be O(N) as we need to touch each element in <code>l</code>. Additionally, <code>sum_set</code> could potentially become very large, causing the loop not only to be expensive in time but also possibly memory (although as you are using a set there aren't going to be any duplicates, so it will totally depend on the input data. E.g. 100,000 elements, but the values range between 0 & 100, so <code>sum_set</code> ranges between 0 & 200).</p>\n\n<p>I'd say your suggestion of pre-filtering to remove duplicates is a good idea, ideally something O(N) like the following (though there are likely more optimal approaches):</p>\n\n<pre><code>>>> input_list = [1,1,1,1,2,2,2,3,3,3]\n>>> filtering_dict = collections.defaultdict(int)\n>>> for item in input_list:\n... filtering_dict[item] += 1\n...\n>>> newList = []\n>>> for key, value in filtering_dict.items():\n... newList.append(key)\n... if value > 1:\n... newList.append(key)\n...\n>>> newList\n... [1, 1, 2, 2, 3, 3]\n</code></pre>\n\n<p>I'd then try and take advantage of sorting the array using an O(Nlog(N)) sort like Mergesort / Quicksort, or depending on your data an O(N) sort like Counting Sort. If you know your data is going to be ordered, you can skip this step. With sorted data, we don't have to use the <code>sum_set</code> set; we can instead pick an index in the array & determine whether it is the total of two other elements. We know that any index we suspect to be our <code>sum</code> will have to be made up of elements that are lower indexes than it in the list, i.e. <code>[1, 2, 3, 4, 5]</code> -> If we start looking at 3, we know we don't need to consider elements 4 & 5, as they will be larger than 3, so couldn't possibly sum to it. Finally, the halfway point for a number is also relevant, I.e. [1, 3, 5, 7, 9, 11, 99, 117] if we're looking at 99, we first look to add the next lowest index & the first index; however, since 11 < 99/2 we know we won't be able to find a match that adds to 99; on average this should be another speedup assuming the data isn't perfectly uniform.</p>\n\n<p>Finally, since we aren't pushing results into <code>sum_set</code> & only checking once for each total, this will cause some repetition in our search. However, since we can return immediately upon finding a match, our best/average case just got a lot better. </p>\n\n<pre><code>def func2(l):\n # l = filter_inputs(l)\n # l.sort()\n for index in range(2, len(l)):\n i = 0\n j = index - 1\n half_val = l[index] / 2;\n while ( i < j and l[i] <= half_val and l[j] >= half_val ):\n if l[index] > l[i] + l[j]:\n i = i + 1 \n elif l[index] < l[i] + l[j]:\n j = j - 1\n else:\n print(str(l[i]) + \" + \" + str(l[j]) + \" = \" + str(l[index]))\n return True\n return False\n</code></pre>\n\n<p>Using timeit, and comparing func & func2, using code like the following: </p>\n\n<pre><code>from timeit import timeit\ntimeit('func2(<TEST ARRAY>)', setup=\"from __main__ import func2; import random\", number=20)\n# Use the function that's been predefined in the python interpreter, \n# pass the array, repeat the test 20 times, and output how many seconds taken\n\n# All times listed are in seconds for 20 repeats\n\n# list of all positive odd numbers up to 9,999 == [x for x in range(1,100000) if x % 2 is 1]\n# (absolute worst-case condition for func2, behaves nearly identically to your original function)\n# (this is because i, j, and half_val achieve 0% improvement & every value is checked)\n# func2 # func \n>>> 73.89 >>> 73.86 \n\n\n# all integers between 1 & 9,999 == [x for x in range(1,10000)]\n# func2 # func \n>>> 0.02 >>> 297.54\n\n# 9,999 random integers between 1 & 10,000 == [random.randint(0,10000) for x in range (1,10000)]\n# Re-ran this one about 5 times for func2 since it was so quick, \n# with 20 loops its lowest was 0.25 & highest 0.32 seconds taken\n# You'll also need to sort 'l' for this one to work with func2\n# func2 # func\n>>> ~0.3 >>> 312.83\n\n</code></pre>\n\n<p>Again, with a low number of entries in <code>l</code>, the cost of removing duplicates & sorting the array would probably cause my function to run slower than yours. None of these speedups change the fact that the overall operation is worst-case O(N^2); however, they should drastically improve the best/average-case scenarios. Additionally, getting a large average speedup with an O(N^2) operation is huge when it comes to a big dataset, as it will be the limiting factor: </p>\n\n<pre><code>I.e. 100,000 items:\n\nFiltering = ~2x O(N) = ~200,000 ops\nMergesort = O(NLog(N)) = ~1.6 million ops\nMain Loop = 1/2 O(N^2) = ~5 billion ops\n</code></pre>\n\n<p>If you can come up with a better way to take advantage of the data such that you can get O(N^2) down to O(Nlog(N)) or similar, I think that'd be key here for optimizing the worst-case scenario. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T10:49:19.063",
"Id": "419328",
"Score": "0",
"body": "Thank you so much for your huge effort. Much appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:31:12.777",
"Id": "216728",
"ParentId": "216696",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216728",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:45:16.160",
"Id": "216696",
"Score": "2",
"Tags": [
"python"
],
"Title": "Verify two numbers from a list will add up to a number in the same list using Python"
} | 216696 |
<p>I was given this problem in a mock interview. I would appreciate a review of my implementation.</p>
<hr>
<blockquote>
<p>Shortest Cell Path In a given grid of 0s and 1s, we have some starting
row and column sr, sc and a target row and column tr, tc. Return the
length of the shortest path from sr, sc to tr, tc that walks along 1
values only.</p>
<p>Each location in the path, including the start and the end, must be a
1. Each subsequent location in the path must be 4-directionally adjacent to the previous location.</p>
<p>It is guaranteed that grid[sr][sc] = grid[tr][tc] = 1, and the
starting and target positions are different.</p>
<p>If the task is impossible, return -1.</p>
<p>Examples:</p>
<p>input: grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 1, 1, 1]] sr = 0, sc =
0, tr = 2, tc = 0 output: 8 (The lines below represent this grid:)
1111 0001 1111</p>
<p>grid = [[1, 1, 1, 1], [0, 0, 0, 1], [1, 0, 1, 1]] sr = 0, sc = 0, tr =
2, tc = 0 output: -1 (The lines below represent this grid:) 1111 0001
1011</p>
</blockquote>
<hr>
<pre><code>def shortestCellPath(grid, sr, sc, tr, tc):
"""
@param grid: int[][]
@param sr: int
@param sc: int
@param tr: int
@param tc: int
@return: int
"""
path_lengths = []
shortestCellPathHelper(grid, sr, sc, tr, tc, 0, path_lengths)
return -1 if len(path_lengths) == 0 else min(path_lengths)
def shortestCellPathHelper(grid, r, c, tr, tc, path_len, path_lengths):
if r < 0 or r >= len(grid) or c < 0 or c >= len(grid[0]):
return
if grid[r][c] != 1:
return
if r == tr and c == tc:
path_lengths.append(path_len)
return
grid[r][c] = -1
#4 directions
shortestCellPathHelper(grid, r, c - 1, tr, tc, path_len + 1, path_lengths)
shortestCellPathHelper(grid, r, c + 1, tr, tc, path_len + 1, path_lengths)
shortestCellPathHelper(grid, r - 1, c, tr, tc, path_len + 1, path_lengths)
shortestCellPathHelper(grid, r + 1, c, tr, tc, path_len + 1, path_lengths)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T06:40:31.593",
"Id": "216699",
"Score": "3",
"Tags": [
"python",
"algorithm",
"recursion",
"pathfinding"
],
"Title": "Shortest Cell Path In a given grid"
} | 216699 |
<p>I am trying to consume a REST endpoint by using the RestTemplate Library provided by the spring framework.
The endpoint also demands a Bearer Access Token as its authorization header, which is only obtained as the response from a user authentication endpoint, which in turn expects an encoded Basic Auth in its Header.</p>
<p>This is the high-level implementation that I have done thus far.</p>
<pre><code>HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setBearerAuth(fetchAccessToken());
HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
ResponseEntity<?> result = this.restClient.exchange(urlToConsume, HttpMethod.GET, entity, String.class);
</code></pre>
<p>The 'fetchAccessToken' Method is implemented as follows</p>
<pre><code>HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setBasicAuth(externalDestination.getClientId(),
externalDestination.getClientSecret());
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<?> result = restClient.exchange(authUrl, HttpMethod.GET, entity, String.class);
//And Thereby fetching 'access_token' from the successful fetch.
</code></pre>
<p>I Want to know whether there is any cleaner way to replicate the above task of dealing with multiple Rest calls to accomplish a single task.
Also, I want to know whether I am missing out any essential validations from a security point of view.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T17:26:31.057",
"Id": "419257",
"Score": "1",
"body": "Do you need to fetch the bearer token every time? Isn't it valid for some time after issuing, so you can cache it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T18:20:31.267",
"Id": "419258",
"Score": "0",
"body": "@TomG Presently, the function determines whether or not call the Token Endpoint by checking whether the previous token has passed its expiry time."
}
] | [
{
"body": "<p>You can have an <code>interceptor</code> on <code>RestTemplate</code>. It will be called for each request. You can have the access token logic within the interceptor. You can also implementing caching so that you do not fire two requests for each task. In case the token expires (401 response), you can regenerate the token</p>\n\n<pre><code>@Component\nclass MyInterceptor implements ClientHttpRequestInterceptor {\n @Override\n public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution){\n HttpHeaders headers = request.getHeaders();\n headers.setBearerAuth(someCachedService.getBearerToken());\n ... response = execution.execute(request, body);\n // handle unauthorized request\n\n }\n}\n\n@Bean\nRestTemplate restTemplate(MyInterceptor interceptor){\n RestTemplate restTemplate = new RestTemplate();\n restTemplate.setInterceptors(Arrays.asList(interceptor));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T04:55:18.343",
"Id": "216764",
"ParentId": "216700",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T07:07:36.210",
"Id": "216700",
"Score": "3",
"Tags": [
"java",
"security",
"rest",
"spring",
"spring-mvc"
],
"Title": "Effective & Secure Method to populate Access Token for authorization header in Rest Template"
} | 216700 |
<p>I have this algorithm that generates waypoints to fly over a specified area.
I would like to get some feedback to the coding inside the method, not about the structure of interfaces, I think this is pretty good here.
Despite any feedback is appreciated:) </p>
<pre><code>public class RectangleWaypointGenerator implements WaypointGenerationAlgorithm {
public List<waypoints.Waypoint> addAutoGeneratedWaypoints(List<Waypoint> polygon_waypoints) {
List<Waypoint> waypoints = new ArrayList<>();
AreaTester tester = new GPSPolygonTester(polygon_waypoints);
GPSCoordinateCalculator coordinateCalculator = new GPSCoordinateCalculator();
CustomGPSMapper mapper = new CustomGPSMapper();
boolean finish = false;
String mode = "r";
Waypoint prev = polygon_waypoints.get(0);
double toRight = coordinateCalculator.calculateAngleBetweenWaypoints(polygon_waypoints.get(1).getPosition().getLatitude(), polygon_waypoints.get(1).getPosition().getLongitude(),
polygon_waypoints.get(2).getPosition().getLatitude(), polygon_waypoints.get(2).getPosition().getLongitude());
double toLeft = coordinateCalculator.calculateAngleBetweenWaypoints(polygon_waypoints.get(2).getPosition().getLatitude(), polygon_waypoints.get(2).getPosition().getLongitude(),
polygon_waypoints.get(1).getPosition().getLatitude(), polygon_waypoints.get(1).getPosition().getLongitude());
double toUpRight = coordinateCalculator.calculateAngleBetweenWaypoints(polygon_waypoints.get(3).getPosition().getLatitude(), polygon_waypoints.get(3).getPosition().getLongitude(),
polygon_waypoints.get(2).getPosition().getLatitude(), polygon_waypoints.get(2).getPosition().getLongitude());
double toUpLeft = coordinateCalculator.calculateAngleBetweenWaypoints(polygon_waypoints.get(0).getPosition().getLatitude(), polygon_waypoints.get(0).getPosition().getLongitude(),
polygon_waypoints.get(1).getPosition().getLatitude(), polygon_waypoints.get(1).getPosition().getLongitude());
double distanceDown = mapper.distanceInKmBetweenGPSCoordinates(polygon_waypoints.get(2), polygon_waypoints.get(3));
double travelledDown = 0;
while (!finish) {
if (mode.equals("r")) {
double[] nextA = coordinateCalculator.movePoint(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), 15.0, toRight);
Waypoint next = new DefaultWaypoint(nextA[0], nextA[1]);
if (tester.isInsideArea(next)) {
waypoints.add(next);
prev = next;
} else {
mode = "l";
double[] nextB = coordinateCalculator.movePoint(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), 10, toUpRight);
Waypoint next2 = new DefaultWaypoint(nextB[0], nextB[1]);
waypoints.add(next2);
travelledDown += mapper.distanceInKmBetweenGPSCoordinates(prev, next);
prev = next2;
}
} else {
double[] nextA = coordinateCalculator.movePoint(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), 15, toLeft);
Waypoint next = new DefaultWaypoint(nextA[0], nextA[1]);
if (tester.isInsideArea(next)) {
waypoints.add(next);
prev = next;
} else {
mode = "r";
double[] nextB = coordinateCalculator.movePoint(prev.getPosition().getLatitude(), prev.getPosition().getLongitude(), 10, toUpLeft);
Waypoint next2 = new DefaultWaypoint(nextB[0], nextB[1]);
waypoints.add(next2);
travelledDown += mapper.distanceInKmBetweenGPSCoordinates(prev, next);
prev = next2;
}
}
if (travelledDown >= distanceDown) {
finish = true;
}
}
return waypoints.stream().map(p -> new waypoints.Waypoint(p)).collect(Collectors.toList());
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:16:39.067",
"Id": "419230",
"Score": "1",
"body": "Why do you instantiate a new Waypoint for every WayPoint at the last line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:21:00.097",
"Id": "419232",
"Score": "0",
"body": "that is just a mapping from an API Waypoint to my own waypoint that provides extended functionality for export operations. I know this looks weird:)"
}
] | [
{
"body": "<p>Instead of using a variable 'finish', put the condition inside the loop:</p>\n\n<pre><code>do {\n...\n} while (travelledDown >= distanceDown)\n</code></pre>\n\n<p>Your modes of \"r\" and \"l\" aren't very descriptive. You should use an ENUM here (Or atleast rename r/l if you don't want an ENUM)</p>\n\n<pre><code>public Enum Mode\n{\n LEFT(\"L\"),\n RIGHT(\"R\")\n}\nmode = Mode.RIGHT\nif (mode == Mode.RIGHT)\n</code></pre>\n\n<p>The last line looks a little odd but you explained why. I'd suggest adding a comment in the code.</p>\n\n<pre><code>//\nreturn waypoints.stream().map(p -> new waypoints.Waypoint(p)).collect(Collectors.toList());\n</code></pre>\n\n<p>'nextA nextB next1 next2' should be renamed to be more meaningful</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:30:35.540",
"Id": "216723",
"ParentId": "216701",
"Score": "1"
}
},
{
"body": "<p>Without doing a full re-write:</p>\n\n<p>Are the methods in your helper classes static? Are they used elsewhere? Can they be made static in their home class? You may want to statically import these helper classes if they are not holding state.</p>\n\n<p>You have a lot of indirection (a.b.c()) fetching the same objects repeatedly - consider putting these in variables before you use them. this will clean up the code and might reveal another method you can extract</p>\n\n<p>Is there any reason movePoint() cannot just return a Waypoint?</p>\n\n<p>There is a lot of common code in the if and else clauses - can this be extracted as a single method that takes the single letter flag?</p>\n\n<p>You can just assign the finishing condition check to the finish variable and get rid of the if clause.</p>\n\n<p>Overall - try to aim for a top level method that 'describes the algorithm' then use subordinate methods to take care of sub-operations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:34:55.247",
"Id": "216724",
"ParentId": "216701",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T07:18:48.167",
"Id": "216701",
"Score": "1",
"Tags": [
"java"
],
"Title": "Java algorithm to fly over area"
} | 216701 |
<p>The problem is this:</p>
<p>A company supplies widgets in a set of pack sizes:</p>
<ul>
<li>250</li>
<li>500</li>
<li>1000</li>
<li>2000</li>
<li>5000</li>
</ul>
<p>Customers can order any number of widgets, but the following rules apply:</p>
<ul>
<li>Only whole packs can be sent and …</li>
<li>No more widgets than necessary should be sent and …</li>
<li>The fewest packs possible should be sent</li>
</ul>
<p>Some examples showing the number of widgets ordered and the required pack quantities and sizes to correctly fulfill the order:</p>
<ul>
<li>1 (1 x 250)</li>
<li>251 (1 x 500)</li>
<li>501 (1 x 500 and 1 x 250)</li>
<li>12001 (2 x 5000 and 1 x 2000 and 1 x 250)</li>
</ul>
<p>I’ve looked at some algorithms (greedy coin change, LAFF, etc.) as these seem to provide similar solutions, but can’t seem to see how to adapt them to the above.</p>
<p>For example:</p>
<pre><code><?php
function countWidgets($amount)
{
$packs = array(5000, 2000, 1000, 500,
250);
$packCounter = array(0, 0, 0, 0, 0);
$packsCount = count($packs);
// loop packs
for ($i = 0; $i < $packsCount; $i++)
{
if ($amount >= $packs[$i])
{
$packCounter[$i] = intval($amount /
$packs[$i]);
$amount = $amount -
$packCounter[$i] *
$packs[$i];
}
}
// if remainder
if ($amount > 0) {
// and if smallest pack size populated
if ($packCounter[4] == 1) {
// clear smallest pack size
$packCounter[4] = 0;
// increment next biggest pack size
$packCounter[3] += 1;
} else {
// increment smallest pack size
$packCounter[4] +=1;
}
}
// Print packs
echo ("Pack ->"."\n");
for ($i = 0; $i < $packsCount; $i++)
{
if ($packCounter[$i] != 0)
{
echo ($packs[$i] . " : " .
$packCounter[$i] . "\n");
}
}
}
$amount = 251;
countWidgets($amount);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T11:08:57.933",
"Id": "419211",
"Score": "0",
"body": "I don't see what the problem is here? You start by trying the biggest pack, until there are fewer widgets left than the size of that pack. Then you move to a smaller pack, and so on, until the smallest pack. If there are some ordered widget left, after all of this, you add one smallest pack. That's it. If you can do it by hand, then you can certainly program it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T11:46:50.497",
"Id": "419216",
"Score": "0",
"body": "Can you confirm that the code is complete and that it functions correctly? If so, I recommend that you [edit] to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see [help/on-topic]) and the question may be deleted."
}
] | [
{
"body": "<p>OK, I agree that this is a bit harder than I assumed yesterday. You basically have two opposing demands: </p>\n\n<ol>\n<li>No more widgets than necessary should be sent. </li>\n<li>The fewest packs possible should be sent.</li>\n</ol>\n\n<p>You <strong>cannot</strong> fulfill both. So if I tried to send 1200 widgets, rule 2 says I should send a pack of 2000, however, rule 1 says I should send 2 packs: one of 1000 and one of 250. Which rule should prevail?</p>\n\n<p>I chose that rule 1 should prevail in the solution below. The reason is that no customer wants more widgets than absolutely necessary.</p>\n\n<pre><code>$packSizes = [ 250,\n 500,\n 1000,\n 2000,\n 5000];\n\nfunction optimizePacks($packSizes,$number)\n{\n rsort($packSizes);\n $requiredPacks = array_fill_keys($packSizes,0);\n foreach ($packSizes as $size) {\n $packs = floor($number/$size);\n if ($packs > 0) {\n $requiredPacks[$size] = $packs;\n $number -= $packs*$size;\n }\n }\n if ($number > 0) $requiredPacks[min($packSizes)]++;\n return $requiredPacks;\n}\n\n$packs = optimizePacks($packSizes,6666);\n\nprint_r($packs);\n</code></pre>\n\n<p>This will work for any array of pack sizes and any number of widgets. The output of this code is:</p>\n\n<blockquote>\n <p>Array (\n [5000] => 1\n [2000] => 0\n [1000] => 1\n [500] => 1\n [250] => 1 )</p>\n</blockquote>\n\n<p>Which is one pack more than rule 2 would demand (one of 5000 and two of 1000). It would, of course, be possible to let rule 2 prevail, but I cannot fulfill both rules.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T11:29:30.360",
"Id": "419669",
"Score": "0",
"body": "You missed a rule `Only whole packs can be sent` The other 2 rules do not compete, you can send `No more widgets than necessary should be sent.` and `The fewest packs possible should be sent` For example `1200` would not be more then `necessary` and the `2000` unit box would be `fewest packs` - See the `Only whole packs` is the real competing rule (against, fewest packs) if that makes sense, well it makes sense to me. The `more then necessary` rule is actually half a rule So it can be ignored without the `Only whole packs` rule."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T11:32:40.737",
"Id": "419670",
"Score": "0",
"body": "Sending 1200 parts in a box that \"can\" hold 2000 is not sending more parts then necessary, it's sending the necessary parts in a bigger box. I built something like this before, I thought of the game [Mancala](https://en.wikipedia.org/wiki/Mancala)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-08T19:29:34.153",
"Id": "507267",
"Score": "0",
"body": "This almost works, except you need to calculate the actual minimum number to fullfil the order first, then optimsie it, so an order of 251 widgets is actually an order for 500, this way you will fulfill all 3 criteria, I built an example here https://wallys-widgets.tilt.ninja/"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:56:49.677",
"Id": "216788",
"ParentId": "216702",
"Score": "2"
}
},
{
"body": "<p>Here is one using a while loop and simple subtaction:</p>\n\n<pre><code>$packSizes = [250,500,1000,2000,5000];\n$number = 3000; \n\nfunction optimizePacks($packSizes,$number)\n{\n //insure packs are in decending order\n rsort($packSizes);\n //create a default array\n $results = array_fill_keys($packSizes, 0);\n\n while($number > 0){\n echo \"---------- $number ----------\\n\";\n\n foreach($packSizes as $size){\n if($size <= $number) break;\n }\n ++$results[$size];\n $number -= $size;\n }\n return $results;\n}\n\n$tests = [\n 1, // (1 x 250)\n 251, // (1 x 500)\n 501, // (1 x 500 and 1 x 250)\n 12001 // (2 x 5000 and 1 x 2000 and 1 x 250)\n\n];\n\nforeach($tests as $test) print_r(optimizePacks($packSizes,$test));\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>---------- 1 ----------\nArray\n(\n [5000] => 0\n [2000] => 0\n [1000] => 0\n [500] => 0\n [250] => 1\n)\n---------- 251 ----------\n---------- 1 ----------\nArray\n(\n [5000] => 0\n [2000] => 0\n [1000] => 0\n [500] => 0\n [250] => 2 //deviates from your example output (see below)\n)\n---------- 501 ----------\n---------- 1 ----------\nArray\n(\n [5000] => 0\n [2000] => 0\n [1000] => 0\n [500] => 1\n [250] => 1\n)\n---------- 12001 ----------\n---------- 7001 ----------\n---------- 2001 ----------\n---------- 1 ----------\nArray\n(\n [5000] => 2\n [2000] => 1\n [1000] => 0\n [500] => 0\n [250] => 1\n)\n</code></pre>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/0ad57a353b8ba28e6673a82e47791eeb76be9dc6\" rel=\"nofollow noreferrer\">Sandbox</a></p>\n\n<p>These 2 examples are at odds with each other</p>\n\n<pre><code>251, // (1 x 500)\n501, // (1 x 500 and 1 x 250)\n</code></pre>\n\n<p>The first one you make one incomplete <code>500</code> part box</p>\n\n<p>The second one you make a 500 (complete box) and an extra 250 with one part. </p>\n\n<p>So the question is, why is the first one only 1 box as it should be 250 x 2 boxes. Conversely why is the second 2 boxes when it could be 1000 x 1 boxes.</p>\n\n<p>So either you fit them in the smallest box that can contain them with the extra overflowing. Or you put them in complete boxes and put the remainder in the smallest box.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<pre><code>If you want the reverse I came up with this:\n\n$packSizes = [250,500,1000,2000,5000];\n\nfunction optimizePacks($packSizes,$number)\n{\n //insure packs are in ascending order\n sort($packSizes);\n //create a default array\n $results = array_fill_keys($packSizes, 0);\n\n while($number > 0){\n echo \"---------- $number ----------\\n\";\n\n foreach($packSizes as $size){\n if($size >= $number) break;\n }\n\n ++$results[$size];\n $number -= $size;\n }\n return $results;\n}\n\n$tests = [\n 1, // (1 x 250)\n 251, // (1 x 500)\n 501, // (1 x 500 and 1 x 250)\n 12001 // (2 x 5000 and 1 x 2000 and 1 x 250)\n\n];\n\nforeach($tests as $test) print_r(optimizePacks($packSizes,$test));\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>---------- 1 ----------\nArray\n(\n [250] => 1\n [500] => 0\n [1000] => 0\n [2000] => 0\n [5000] => 0\n)\n---------- 251 ----------\nArray\n(\n [250] => 0\n [500] => 1\n [1000] => 0\n [2000] => 0\n [5000] => 0\n)\n---------- 501 ----------\nArray\n(\n [250] => 0\n [500] => 0\n [1000] => 1 //deviates from your example output\n [2000] => 0\n [5000] => 0\n)\n---------- 12001 ----------\n---------- 7001 ----------\n---------- 2001 ----------\nArray\n(\n [250] => 0\n [500] => 0\n [1000] => 0\n [2000] => 0\n [5000] => 3 //deviates from your example output\n)\n</code></pre>\n\n<p>This also points out how the last example is at odds with this way. Which is to fit the most parts in the smallest size box. This may be a bigger box but it will not overflow. For example it wont pick 5000 for 1 part.</p>\n\n<p>I used a pretty nice trick with the foreach in the above code, that let me simplify it greatly. </p>\n\n<p>This only works if you sort it ASC, because if we don't find a box that can hold the full number, the last iteration leaves <code>$size</code> at the Max value in the array (its the last one after all). Which is exactly what we want because then we subtract that from <code>$number</code> and repeat the process.</p>\n\n<p>However if we do find a box that can contain all the parts, we simply exit (break) the foreach loop. This will be the smallest box that can fit all the parts (naturally). And we also subtract this which will leave <code>$number</code> at <code><= 0</code> and break the while loop which completes the function and returns the results.</p>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/819b718d62c299823a9ceff8be4137ede5ed187a\" rel=\"nofollow noreferrer\">Sandbox</a></p>\n\n<p>If you really want them (the sizes, compare the 2 results in my examples) in the other order, we can either send them in that order and build the default first, or sort one way build the default then reverse the array (which should be faster then sort).</p>\n\n<pre><code>function optimizePacks($packSizes,$number)\n{\n //insure packs are in decending order\n rsort($packSizes);\n //create a default array (baking in the order)\n $results = array_fill_keys($packSizes, 0);\n //flip the order\n $packSizes = array_reverse($packSizes);\n\n\n while($number > 0){\n</code></pre>\n\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/ca83f122677c0847861bab94cd77b0a1d7928b31\" rel=\"nofollow noreferrer\">Sandbox</a></p>\n\n<p><strong>Summery</strong></p>\n\n<p>Essentially you can't have both of these (or your mixed examples) without a whole lot of conditional statements that would violate using a dynamic array of sizes. You could do that with fixed sizes and special if conditions, for example. This is because your inconsistently applying your rules.</p>\n\n<p>Hope it helps, I get some weird enjoyment out of figuring this stuff out... lol</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-06T12:06:01.567",
"Id": "216976",
"ParentId": "216702",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:08:54.820",
"Id": "216702",
"Score": "2",
"Tags": [
"php",
"algorithm"
],
"Title": "PHP - Packing widgets into the fewest number of boxes, plus minimum order quantity"
} | 216702 |
<p>I use this to set language session for navigation. Someone said that this switch is too cumbersome. Why? Is there an easier way?</p>
<pre><code>$defaultLang = 'it';
if (!empty($_GET["lang"])) {
switch (strtolower($_GET["lang"])) {
case "en":
$_SESSION['lang'] = 'gb';
break;
case "tr":
$_SESSION['lang'] = 'tr';
break;
default:
$_SESSION['lang'] = $defaultLang;
break;
}
}
if (empty($_SESSION["lang"])) {
$_SESSION["lang"] = $defaultLang;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:33:56.450",
"Id": "419204",
"Score": "0",
"body": "Please note that mickmackusa changed his answer, to make it do exactly the same as the code in your question, after you had accepted his answer as the best possible. You might need to correct your own code, to reflect this change, if you copied his code."
}
] | [
{
"body": "<p>Yes. Definitely. You can use a lookup array.</p>\n\n<pre><code>$langs = [\n 'en' => 'gb',\n 'tr' => 'tr',\n];\n\n$defaultLang = 'it';\n\n\nif (isset($_GET['lang'])) {\n $lang = strtolower($_GET['lang']);\n $_SESSION['lang'] = $langs[$lang] ?? $defaultLang;\n} elseif (!isset($_SESSION['lang'])) { // meaning, no $_GET['lang'] and no $_SESSION['lang']\n $_SESSION['lang'] = $defaultLang;\n}\n// if there is no $_GET['lang'] and there is a $_SESSION['lang'], then nothing to update\n</code></pre>\n\n<p>A lookup array is concise and a breeze to maintain. You only need to update the lookup or the fallback value; never the processing block.</p>\n\n<p><a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"nofollow noreferrer\"><code>??</code></a> is the <a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"nofollow noreferrer\">null coalescing operator</a>, so if the lang value is not found in the lookup, the fallback value will be used.</p>\n\n<p>If your php version is not over 7 (then I urge you to upgrade) then you will need a longer condition syntax.</p>\n\n<pre><code>$_SESSION['lang'] = isset($langs[$lang]) ? $langs[$lang] : $defaultLang;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:29:40.067",
"Id": "419192",
"Score": "0",
"body": "I don't really know this type of operator: ??. i have a parse error unexpected '?' on $_SESSION['lang'] = $langs[$lang] ?? $defaultLang;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:39:43.833",
"Id": "419195",
"Score": "0",
"body": "I've update my answer to provide a null coalescing operator replacement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:48:09.823",
"Id": "419207",
"Score": "0",
"body": "@Ogum the alternative name for it is the 'isset ternary` because of what it does, it is essentially performing an `isset` check without the need for the `true` condition."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:03:29.917",
"Id": "216711",
"ParentId": "216703",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "216711",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:17:04.913",
"Id": "216703",
"Score": "3",
"Tags": [
"php",
"session",
"i18n"
],
"Title": "Language switch based on parameters and session state"
} | 216703 |
<p>This is the "Increasing Number problem", where we are looking for all numbers with <span class="math-container">\$n\$</span> digits where each digit is bigger than the digit before it. Or in Mathematical therms where: </p>
<p><span class="math-container">$$\mathit{IncreasingNumber} = c_n \times 10^n + c_{n-1} \times 10^{n-1} + \cdots + c_1 * 10 + c_0$$</span></p>
<p>and <span class="math-container">\$c_i < c_{i-1}\$</span>.</p>
<p>Examples: 123456789 or 123 or 569 or 139 or 45 or 12379. Goal: Give out all numbers that fullfill these properties depending on the number of digits <span class="math-container">\$n\$</span>. This is my brute force code: </p>
<pre><code>Sub AllIncreasingNumbers(N As Integer)
Dim Number As Long
Dim i As Long
Dim j As Integer
Dim lastdig As Integer
Dim remainder As Long
Dim thisdig As Integer
For i = (1 * 10 ^ (N - 1)) To 10 ^ (N)
remainder = i
lastdig = 0
For j = (N - 1) To 0 Step -1
thisdig = (remainder \ (10 ^ j))
If Not (lastdig < thisdig) Then
GoTo NotPass
End If
lastdig = thisdig
remainder = remainder Mod (10 ^ j)
Next j
Debug.Print i
NotPass:
Next i
End Sub
</code></pre>
<p>If you haven't guessed it, it functions as following: go through all Numbers with <code>N</code> digits and check if they are increasing Numbers, if yes print them.</p>
<p>For <span class="math-container">\$n\$</span> = 2 to 6 it is reasonably fast but for <span class="math-container">\$n\$</span> = 8 or 9 it is really slow despite <span class="math-container">\$n=9\$</span> only having one solution <code>123456789</code>. I think there could be a recursive algorithm to solve this but I can't figure it out. I used VBA because thats the language I am most familiar with but actually I am more intrested in the recursive algorithm to solve this. As soon as I have the algorithm I am able to implement it.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:31:37.920",
"Id": "419203",
"Score": "0",
"body": "As far as I get it, the problem does not require you to solve it on _numbers_. Why don't you solve it on strings/arrays of characters then? The output is text anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:40:41.620",
"Id": "419206",
"Score": "0",
"body": "@CiaPan Your comment implies that it would somehow be easier to solve it on strings. How and why would I do it with a string of characters?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T22:03:15.497",
"Id": "419279",
"Score": "0",
"body": "@LucasRaphaelPianegonda Just compare the integer codes for each digit character in the string. It makes it much simpler. It likely isn't as performant, but that probably isn't a concern. If you can read lisps, here's a predicate that can simply be looped over: https://gist.github.com/carcigenicate/d490f8284427b3b5db9da76c71bece43"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T08:27:56.663",
"Id": "419314",
"Score": "1",
"body": "Please note there are only 9 single-digit numbers (zero skipped), all of which are 'increasing', **but** there are 90 two-digits numbers and just 40 of them are increasing, which is 2/5. And in three-digits numbers only about 1/10.7 are increasing (84 out of 900). In the worst case you have just one increasing number among almost a billion of all 9-digit numbers. That's why your code is inefficient for bigger N values, and explicit construction should be faster."
}
] | [
{
"body": "<p>Instead of searching all numbers and checking them one by one, why not construct the numbers from the rule. In other words, start with the smallest digit being 1, then the next digit being 2 and so on. The digits can then be increased right to left as long as the rule holds.</p>\n\n<p>For example, finding all 8 digit numbers:</p>\n\n<p>Start with each digit increasing by 1 left to right:</p>\n\n<ul>\n<li>12345678</li>\n</ul>\n\n<p>Add one to the final digit:</p>\n\n<ul>\n<li>1234567<strong>9</strong></li>\n</ul>\n\n<p>Run out of digits so increase the digit to the left:</p>\n\n<ul>\n<li>123456<strong>8</strong>9</li>\n<li>12345<strong>7</strong>89</li>\n<li>1234<strong>6</strong>789 </li>\n<li>...</li>\n<li><strong>2</strong>3456789</li>\n</ul>\n\n<p>EDIT for further explanation:</p>\n\n<p>For smaller numbers, you then need to repeat this process recursively. For example:</p>\n\n<ul>\n<li>123 -> 124 -> 125 ... 129</li>\n</ul>\n\n<p>You would now need to \"reset\" the second digit and any following it to one above what it was:</p>\n\n<ul>\n<li><p>129 -> 134 -> 135 -> 136 ... 139</p></li>\n<li><p>139 -> 145 -> 146 -> 147 ... 149</p></li>\n<li><p>149 -> 156 -> 157 -> 158 -> 159</p></li>\n</ul>\n\n<p>And so on.</p>\n\n<p>You are still effectively working backwards through the digits, recursively increasing them right to left.</p>\n\n<p>Hope that helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:35:44.040",
"Id": "419205",
"Score": "0",
"body": "It doesn't yield all solutions: example: N=3; 123,124,... 129, 139, 149, 159... but 134 is also a solution that doesn't appear in this algorithm. You'd need to go from 129 to 134 then count up 135,136 ... 139, then increase to 145,146, until 149 then 156 ect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T11:09:23.310",
"Id": "419212",
"Score": "0",
"body": "@LucasRaphaelPianegonda Added an edit for further explanation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:42:42.557",
"Id": "216716",
"ParentId": "216708",
"Score": "1"
}
},
{
"body": "<p>Here is idea: starting from the smallest number:</p>\n\n<pre><code>[[1] [2] [3] [4] [5] [6] [7] [8] [9]]\n</code></pre>\n\n<p>Every subarray holds number ending with the specific digits.</p>\n\n<p>Then increasing one digit for each subarray. </p>\n\n<pre><code>[1] -> [12] [13] [14] [15] [16] [17] [18] [19] \n[2] -> [13] [14] [15] [16] [17] [18] [19]\n[3] -> [14] [15] [16] [17] [18] [19]\n[4] -> [15] [16] [17] [18] [19]\n[5] -> [16] [17] [18] [19]\n[6] -> [17] [18] [19]\n[7] -> [18] [19]\n[8] -> [19]\n</code></pre>\n\n<p>Then put every number into their bucket which ends with it. (if it's 9. then its the last number)</p>\n\n<p>Here is the result:</p>\n\n<pre><code> [[], [12], [13, 23], [14, 24, 34], [15, 25, 35, 45],\n [16, 26, 36, 46, 56], [17, 27, 37, 47, 57, 67], \n [18, 28, 38, 48, 58, 68, 78], [19, 29, 39, 49, 59, 69, 79, 89]]\n</code></pre>\n\n<p>Then recursive or iterate till N == 9.</p>\n\n<p>I prefer to use swift but the logic is same and obvious: </p>\n\n<pre><code> var base: [[Int]] = [[1],[2],[3],[4],[5],[6],[7],[8],[9]]\n\n var result : [Int] = []\n\n result.append(contentsOf: base.flatMap{$0})\n\n for N in 0..<8{\n\n var singleStep: [[Int]] = [[],[],[],[],[],[],[],[],[]]\n for i in N..<8 {\n for j in (i+1)..<9{\n for each in base[i]{\n singleStep[j].append(each * 10 + j + 1)\n }\n }\n }\n base = singleStep\n result.append(contentsOf: base.flatMap{$0})\n print(base)\n }\n print(result)\n\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 13, 23, 14, 24, 34, 15, 25, 35, 45, 16, \n 26, 36, 46, 56, 17, 27, 37, 47, 57, 67, 18, 28, 38, 48, 58, 68, 78, 19, \n 29, 39, 49, 59, 69, 79, 89, 123, 124, 134, 234, 125, 135, 235, 145, 245, \n 345, 126, 136, 236, 146, 246, 346, 156, 256, 356, 456, 127, 137, 237, \n 147, 247, 347, 157, 257, 357, 457, 167, 267, 367, 467, 567, 128, 138, \n 238, 148, 248, 348, 158, 258, 358, 458, 168, 268, 368, 468, 568, 178, \n 278, 378, 478, 578, 678, 129, 139, 239, 149, 249, 349, 159, 259, 359,\n 459, 169, 269, 369, 469, 569, 179, 279, 379, 479, 579, 679, 189, 289, \n 389, 489, 589, 689, 789, 1234, 1235, 1245, 1345, 2345, 1236, 1246, 1346, \n 2346, 1256, 1356, 2356, 1456, 2456, 3456, 1237, 1247, 1347, 2347, 1257, \n 1357, 2357, 1457, 2457, 3457, 1267, 1367, 2367, 1467, 2467, 3467, 1567, \n 2567, 3567, 4567, 1238, 1248, 1348, 2348, 1258, 1358, 2358, 1458, 2458, \n 3458, 1268, 1368, 2368, 1468, 2468, 3468, 1568, 2568, 3568, 4568, 1278, \n 1378, 2378, 1478, 2478, 3478, 1578, 2578, 3578, 4578, 1678, 2678, 3678,\n 4678, 5678, 1239, 1249, 1349, 2349, 1259, 1359, 2359, 1459, 2459, 3459, \n 1269, 1369, 2369, 1469, 2469, 3469, 1569, 2569, 3569, 4569, 1279, 1379,\n 2379, 1479, 2479, 3479, 1579, 2579, 3579, 4579, 1679, 2679, 3679, 4679, \n 5679, 1289, 1389, 2389, 1489, 2489, 3489, 1589, 2589, 3589, 4589, 1689, \n 2689, 3689, 4689, 5689, 1789, 2789, 3789, 4789, 5789, 6789, 12345, 12346,\n 12356, 12456, 13456, 23456, 12347, 12357, 12457, 13457, 23457, 12367, \n 12467, 13467, 23467, 12567, 13567, 23567, 14567, 24567, 34567, 12348, \n 12358, 12458, 13458, 23458, 12368, 12468, 13468, 23468, 12568, 13568,\n 23568, 14568, 24568, 34568, 12378, 12478, 13478, 23478, 12578, 13578, \n 23578, 14578, 24578, 34578, 12678, 13678, 23678, 14678, 24678, 34678, \n 15678, 25678, 35678, 45678, 12349, 12359, 12459, 13459, 23459, 12369, \n 12469, 13469, 23469, 12569, 13569, 23569, 14569, 24569, 34569, 12379, \n 12479, 13479, 23479, 12579, 13579, 23579, 14579, 24579, 34579, 12679,\n 13679, 23679, 14679, 24679, 34679, 15679, 25679, 35679, 45679, 12389,\n 12489, 13489, 23489, 12589, 13589, 23589, 14589, 24589, 34589, 12689, \n 13689, 23689, 14689, 24689, 34689, 15689, 25689, 35689, 45689, 12789, \n 13789, 23789, 14789, 24789, 34789, 15789, 25789, 35789, 45789, 16789,\n 26789, 36789, 46789, 56789, 123456, 123457, 123467, 123567, 124567, \n 134567, 234567, 123458, 123468, 123568, 124568, 134568, 234568, 123478, \n 123578, 124578, 134578, 234578, 123678, 124678, 134678, 234678, 125678, \n 135678, 235678, 145678, 245678, 345678, 123459, 123469, 123569, 124569, \n 134569, 234569, 123479, 123579, 124579, 134579, 234579, 123679, 124679, \n 134679, 234679, 125679, 135679, 235679, 145679, 245679, 345679, 123489, \n 123589, 124589, 134589, 234589, 123689, 124689, 134689, 234689, 125689,\n 135689, 235689, 145689, 245689, 345689, 123789, 124789, 134789, 234789,\n 125789, 135789, 235789, 145789, 245789, 345789, 126789, 136789, 236789,\n 146789, 246789, 346789, 156789, 256789, 356789, 456789, 1234567, 1234568,\n 1234578, 1234678, 1235678, 1245678, 1345678, 2345678, 1234569, 1234579, \n 1234679, 1235679, 1245679, 1345679, 2345679, 1234589, 1234689, 1235689,\n 1245689, 1345689, 2345689, 1234789, 1235789, 1245789, 1345789, 2345789, \n 1236789, 1246789, 1346789, 2346789, 1256789, 1356789, 2356789, 1456789, \n 2456789, 3456789, 12345678, 12345679, 12345689, 12345789, 12346789, \n 12356789, 12456789, 13456789, 23456789, 123456789]\n</code></pre>\n\n<p>In the above method, you have to record the position of the each digits. Actually the count of result is 511 which equals the sum of combination of the following array: [1,2,3,4,5,6,7,8,9].</p>\n\n<p>You just select an arbitrary number of numbers out of the array, because they are all different so there is only one ascending order. Thus the question has been transformed to calculate the the sum of combination of above array.</p>\n\n<pre><code> result = C9(1) + C9(2) + C9(3) + C9(4) + C9(5) + C9(6) + C9(7) + C9(8) + C9(9)\n</code></pre>\n\n<p>There are many ways to calculate this and also easily recursive without memorizing their last digits.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T18:55:35.750",
"Id": "216742",
"ParentId": "216708",
"Score": "0"
}
},
{
"body": "<p>This is just a combination problem. Python has this written already in itertools.</p>\n\n<pre><code>from itertools import combinations \n\nnumbers=[1,2,3,4,5,6,7,8,9] \nlength=[2,3,4,5,6,7,8,9]\nfor L in length:\n comb=combinations(numbers,L)\n for i in list(comb):\n num=0\n for n in range(len(i)):\n num=i[n]*10**(len(i)-n-1)+num\n print(num)\n</code></pre>\n\n<p>I start by defining the numbers available to use numbers=[1,2,3,4,5,6,7,8,9] \nthen define the lengths I'm interested in (everything but 1).\ncombinations from itertools then returns all possible combinations for a given length.</p>\n\n<p>The next section just takes the tuple of combinations eg (2,5,6,7), and changes them into the actual number 2567. </p>\n\n<pre><code>for i in list(comb):\n num=0\n for n in range(len(i)):\n num=i[n]*10**(len(i)-n-1)+num\n print(num)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T11:56:49.193",
"Id": "419334",
"Score": "0",
"body": "Welcome to codereview NAP_time. The question was about Visual Basic, an answer using python might not be helpful to the OP, depending on their skillset."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T13:22:22.677",
"Id": "419341",
"Score": "0",
"body": "Fair enough. I guess I assumed that visual basic might have something similar. At the least, searching for combinations code will probably turn something up."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T09:13:16.373",
"Id": "216771",
"ParentId": "216708",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:49:47.247",
"Id": "216708",
"Score": "2",
"Tags": [
"algorithm",
"vba",
"recursion",
"time-limit-exceeded"
],
"Title": "Looking for all numbers where each digit is bigger than the previous digit"
} | 216708 |
<p>Since my last <a href="https://codereview.stackexchange.com/questions/164846/mvc-structured-rest-api-in-php">question</a> related to this I have managed to create a working base and to understand how MVC works.</p>
<p>I'm writing <strong>REST</strong>ful APIS in PHP, they serve the purpose but I see that my code is repeating. </p>
<p>For example, for each action, I have a <em>controller</em>, a <em>service</em>... etc and a lot of that code can be reused not that I write a ton of code for one simple route.</p>
<p>I have tried a few of my ideas but I end up having spaghetti code and it does not look clean.</p>
<hr>
<p>Here is folder the structure in one of my APIS.</p>
<pre><code>.
├── README.md
├── apache_default
├── composer.json
├── composer.lock
├── config
│ ├── config-development.yml
│ ├── config-production.yml
│ ├── dependencies
│ │ ├── common
│ │ │ ├── cashing.yml
│ │ │ ├── components.yml
│ │ │ ├── controllers.yml
│ │ │ ├── domains.yml
│ │ │ ├── middleware.yml
│ │ │ ├── objmap.yml
│ │ │ ├── repositories.yml
│ │ │ └── services.yml
│ │ ├── development
│ │ │ └── db.yml
│ │ ├── general-production.yml
│ │ ├── general.yml
│ │ └── main.yml
│ ├── parameters
│ │ └── development
│ │ └── tables.yml
│ └── routing.yml
├── phpunit.xml
├── public
│ ├── Bootstrap.php
│ ├── Kernel.php
│ ├── index.php
│ └── monolog.log
├── resources
│ ├── git
│ │ ├── diagram.png
│ │ ├── schema.png
│ │ └── schema_1.png
│ └── loggs
│ └── monolog.txt
├── src
│ └── Spartan
│ ├── Core
│ │ ├── Component
│ │ │ ├── Collection.php
│ │ │ ├── Controller.php
│ │ │ ├── DataMapper.php
│ │ │ ├── Exception.php
│ │ │ ├── MapperFactory.php
│ │ │ └── Service.php
│ │ ├── Database
│ │ │ ├── ES.php
│ │ │ └── PDOCompat.php
│ │ ├── Entities
│ │ │ ├── CanPersistMapper.php
│ │ │ ├── HasId.php
│ │ │ └── ResponseBootstrap.php
│ │ ├── Logger
│ │ │ └── Logger.php
│ │ └── Mapper
│ │ └── CanCreateMapper.php
│ ├── Models
│ │ ├── Adapters
│ │ ├── Cashing
│ │ │ └── WorkoutCashing.php
│ │ ├── Collections
│ │ │ ├── DescriptionCollection.php
│ │ │ ├── ExerciseCollection.php
│ │ │ ├── NameCollection.php
│ │ │ ├── RoundCollection.php
│ │ │ ├── TagCollection.php
│ │ │ ├── WorkoutCollection.php
│ │ │ └── WorkoutListCollection.php
│ │ ├── Domains
│ │ │ ├── AddWorkoutDomain
│ │ │ │ └── AddWorkoutDomain.php
│ │ │ ├── DeleteWorkoutDomain
│ │ │ │ └── DeleteWorkoutDomain.php
│ │ │ ├── EditWorkoutDomain
│ │ │ │ └── EditWorkoutDomain.php
│ │ │ ├── GetWorkoutDomain
│ │ │ │ └── GetWorkoutDomain.php
│ │ │ ├── GetWorkoutIdsDomain
│ │ │ │ └── GetWorkoutIdsDomain.php
│ │ │ ├── GetWorkoutListDomain
│ │ │ │ └── GetWorkoutListDomain.php
│ │ │ ├── ReleaseWorkoutDomain
│ │ │ │ └── ReleaseWorkoutDomain.php
│ │ │ └── WorkoutExsistsDomain
│ │ │ └── WorkoutExsistsDomain.php
│ │ ├── Entities
│ │ │ ├── Description.php
│ │ │ ├── Exercise.php
│ │ │ ├── Name.php
│ │ │ ├── Round.php
│ │ │ ├── Tag.php
│ │ │ ├── Version.php
│ │ │ ├── Workout.php
│ │ │ └── WorkoutList.php
│ │ ├── Exceptions
│ │ │ ├── BaseError.php
│ │ │ ├── DescriptionConfliect.php
│ │ │ ├── ESError.php
│ │ │ ├── NameConflict.php
│ │ │ ├── RoundError.php
│ │ │ └── TagError.php
│ │ ├── Facades
│ │ ├── Helpers
│ │ ├── Interfaces
│ │ │ └── CanPersistWorkout.php
│ │ ├── Mappers
│ │ │ ├── VersionMapper.php
│ │ │ ├── WorkoutBase.php
│ │ │ ├── WorkoutDescription.php
│ │ │ ├── WorkoutListMapper.php
│ │ │ ├── WorkoutName.php
│ │ │ ├── WorkoutRound.php
│ │ │ └── WorkoutTag.php
│ │ ├── Middlewares
│ │ │ ├── CreateWorkoutMiddleware.php
│ │ │ ├── DeleteWorkoutMiddleware.php
│ │ │ ├── EditWorkoutMiddleware.php
│ │ │ ├── GetWorkoutByIdsMiddleware.php
│ │ │ ├── GetWorkoutListMiddleware.php
│ │ │ ├── GetWorkoutMiddleware.php
│ │ │ └── ReleaseWorkoutMiddleware.php
│ │ ├── Repositories
│ │ │ └── WorkoutRepository.php
│ │ └── Services
│ │ └── WorkoutService.php
│ └── Presentation
│ ├── Controller
│ │ ├── LogController.php
│ │ └── WorkoutController.php
│ └── Mappers
│ └── WorkoutMapp.php
└── tests
├── bootstrap.php
├── fixture
├── integration
├── mock
│ ├── Entity.php
│ ├── Factory.php
│ ├── Mapper.php
│ ├── RepoEntity.php
│ └── RepoMapper.php
├── report
└── unit
└── Spartan
├── Cashing
│ └── WorkoutCashingTest.php
├── Component
│ ├── CollectionTest.php
│ ├── DataMapperTest.php
│ └── MapperFactoryTest.php
├── Controller
│ └── MappTest.php
├── Domains
├── Entities
│ ├── DescriptionTest.php
│ ├── ExerciseTest.php
│ ├── NameTest.php
│ ├── RoundTest.php
│ ├── TagTest.php
│ ├── VersionTest.php
│ ├── WorkoutListTest.php
│ └── WorkoutTest.php
├── Mappers
│ ├── VersionTest.php
│ ├── WorkoutBaseTest.php
│ ├── WorkoutDescriptionTest.php
│ ├── WorkoutListTest.php
│ ├── WorkoutNameTest.php
│ ├── WorkoutRoundTest.php
│ └── WorkoutTagTest.php
├── Repositories
│ └── WorkoutTest.php
└── Services
└── WorkoutTest.php
</code></pre>
<p>For each activity I have a controller, that controller has a service injected into it via DI over yml.</p>
<p>When the service loads I have a domain folder where I keep my logic and over a factory, I create mappers there which I need(if I need them).</p>
<p>Each domain does one action, for example version workout(I need this for auditing of my data in MySQL).</p>
<p>Than I have a middleware in my service which does cashing(I'm working to change)</p>
<p>And thats basically how each of my routes works a lot of repeated code.</p>
<p>It looks very boring to write code now and I need a push into another direction.</p>
<hr>
<p>Here is a part of my code:</p>
<p>index.php</p>
<pre><code><?php
//Display errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
use Symfony\Component\HttpFoundation\Request;
// load vendor
require __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/../public/Kernel.php';
require_once __DIR__.'/../public/Bootstrap.php';
// new kernel
$kernel = new Kernel('dev');
$bootstrap = new Bootstrap;
// new request
$request = Request::createFromGlobals();
// loader interface
$config = $kernel->registerContainerConfiguration();
// response from
$response = $bootstrap->handle($request,$config,null);
</code></pre>
<p>bootstrap.php</p>
<pre><code><?php
class Bootstrap
{
public function handle($request,$config,$ipRange)
{
// Configuration
$locator = new FileLocator(__DIR__ . '/../config');
$data = new ResponseBootstrap();
// Create a log channel
$log = new Logger('spartan_workouts_ms');
$log->pushHandler(new StreamHandler('monolog.log'));
$log->pushHandler(new LogglyHandler('55920048-11f0-4b7e-a203-e90083d6962d/tag/monolog', Logger::INFO));
// Dependency Injection Container
$container = new DependencyInjection\ContainerBuilder;
$loader = new DependencyInjection\Loader\YamlFileLoader($container, $locator);
$loader->load($config);
$container->compile();
// Routing
$loader = new Routing\Loader\YamlFileLoader($locator);
$context = new Routing\RequestContext();
$context->fromRequest($request);
$matcher = new Routing\Matcher\UrlMatcher(
$loader->load('routing.yml'),
$context
);
try{
$parameters = $matcher->match($request->getPathInfo());
foreach ($parameters as $key => $value) {
$request->attributes->set($key, $value);
}
$command = $request->getMethod() . $request->get('action');
$resource = "controller.{$request->get('controller')}";
$controller = $container->get($resource);
$data = $controller->{$command}($request);
}
// log custom thrown exceptions
catch (\Exception $e) {
/**
* This is to slow it takes to much time to log
*/
// // log errors
// $log->addWarning(
// json_encode([
// "date"=> date("Y-m-d h:i:s"),
// "code"=> $e->getCode(),
// "message"=> $e->getMessage(),
// "file"=> $e->getFile(),
// "line"=> $e->getLine()
// ])
// );
$data->setData([
"date"=> date("Y-m-d h:i:s"),
"code"=> $e->getCode(),
"message"=> $e->getMessage(),
"file"=> $e->getFile(),
"line"=> $e->getLine()
]);
if($e->getCode() == 0){
// TODO log data
$data->setStatus(404);
}else{
// TODO log data
$data->setStatus($e->getCode());
}
$data->setMessage($e->getMessage());
//echo "log to monolog";
} catch (\TypeError $error) {
// TODO log data
$data->setStatus(404);
$data->setMessage(new Response("Invalid dependency: {$error->getMessage()}"));
die(print_r(new Response("Invalid dependency: {$error->getMessage()}")));
}
// Check if json in array from
if(!empty($data->getData())){
$response = new JsonResponse($data->getData());
}else{
// Not json
$response = new Response;
}
//Set custom headers
$response->setStatusCode(
(int)$data->getStatus(),
empty($data->getMessage()) ? $data->getMessage() : null
);
// preflighted request handle
if($request->getMethod() === 'OPTIONS'){
// set status
$response->setStatusCode((int)200);
}
// headers
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT,DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set("Access-Control-Max-Age", "1728000");
// return response
$response->send();
return $response;
}
}
</code></pre>
<p>Kernel.php</p>
<pre><code><?php
class Kernel
{
protected $env;
public function __construct($env = null)
{
if (is_null($env)) {
$this->env = is_null($env) ? 'prod' : 'dev';
}else{
$this->env = $env;
}
}
/**
* Loads the container configuration.
*/
public function registerContainerConfiguration()
{
if((string)$this->env === (string)'dev'){
$configuration = 'config-development.yml';
}else{
$configuration = 'config-production.yml';
}
return $configuration;
}
}
</code></pre>
<p>WorkoutController.php</p>
<pre><code><?php
class WorkoutController extends Controller
{
private $workoutService;
private $workoutMapp;
public function __construct(WorkoutService $workoutService, WorkoutMapp $workoutMapp){
$this->workoutService = $workoutService;
$this->workoutMapp = $workoutMapp;
// construct the parent
parent::__construct();
}
/**
* Get workout
* Get workouts by id
* Get workout list
*
* @param Request $request
* @return ResponseBootstrap
*/
public function get(Request $request):ResponseBootstrap
{
$workout = $this->workoutMapp->getWorkoutUniversal($request);
// list
if(!is_null($workout->getOffset()) && !is_null($workout->getLimit()) && !is_null($workout->getState())){
return $this->workoutService->getWorkoutList($workout);
}
// get workout by id
if($workout->getId() && $workout->getState()){
return $this->workoutService->getWorkout($workout);
}
// get workout ids
if($workout->getIds()){
return $this->workoutService->getWorkoutIds($workout);
}
return $this->badRequest();
}
/**
* Create workout
*
* @param Request $request
* @return ResponseBootstrap
*/
public function post(Request $request)
{
// raw data
$data = json_decode($request->getContent(), true);
// map raw data to workout object
$workout = $this->workoutMapp->addWorkout($data);
// check if the name, description, tags and rounds are not empty
if(!empty($workout->getNames()->toArray()) && !empty($workout->getDescriptions()->toArray()) && !empty($workout->getTags()->toArray()) && !empty($workout->getRounds()->toArray())){
return $this->workoutService->addWorkout($workout);
}
// when empty return a response from the base controller
return $this->badRequest();
}
....
</code></pre>
<p>WorkoutService.php</p>
<pre><code><?php
class WorkoutService extends Service
{
......
/**
* Add Workout
*
* @param Workout $workout
* @return ResponseBootstrap
*/
public function addWorkout(Workout $workout):ResponseBootstrap
{
// middleware for handling cashing
$this->createWorkoutMiddleware->handle(
$this->addWorkoutDomain,
$workout,
$this->getWorkoutDomain);
return $this->formResponse($workout, true);
}
/**
* Delete Workout
*
* @param Workout $workout
* @return ResponseBootstrap
*/
public function deleteWorkout(Workout $workout):ResponseBootstrap
{
// middleware for handling cashing
$this->deleteWorkoutMiddleware->handle(
$this->deleteWorkoutDomain,
$workout);
return $this->formResponse($workout, false);
}
/**
* Edit Workout
*
* @param Workout $workout
* @return ResponseBootstrap
*/
public function editWorkout(Workout $workout):ResponseBootstrap
{
// middleware for handling cashing
$this->editWorkoutMiddleware->handle(
$this->editWorkoutDomain,
$workout,
$this->getWorkoutDomain);
return $this->formResponse($workout, false);
}
</code></pre>
<p>WorkoutRepository.php</p>
<pre><code><?php
class WorkoutRepository implements CanPersistWorkout
{
private $mapperFactory;
private $list = [
Workout::class => WorkoutBase::class,
Round::class => WorkoutRound::class,
Name::class => WorkoutName::class,
Version::class => VersionMapper::class,
Description::class => WorkoutDescription::class,
Tag::class => WorkoutTag::class,
RoundCollection::class => WorkoutRound::class,
NameCollection::class => WorkoutName::class,
DescriptionCollection::class => WorkoutDescription::class,
TagCollection::class => WorkoutTag::class,
WorkoutListCollection::class => WorkoutListMapper::class
];
public function __construct(CanCreateMapper $mapperFactory)
{
$this->mapperFactory = $mapperFactory;
}
/*********************************************************************************************/
/************************************ Store **************************************/
/*********************************************************************************************/
public function storeDescription(Description $description, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($description), $override);
$mapper->store($description);
}
public function storeBase(Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($workout), $override);
$mapper->store($workout);
}
public function storeRound(Round $round, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($round), $override);
$mapper->store($round);
}
public function storeName(Name $name, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($name), $override);
$mapper->store($name);
}
public function versionUp(Version $version, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($version), $override);
$mapper->versionUp($version);
}
public function storeTag(Tag $tag, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($tag), $override);
$mapper->store($tag);
}
/*********************************************************************************************/
/************************************ Delete **************************************/
/*********************************************************************************************/
public function deleteWorkout(Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($workout), $override);
$mapper->delete($workout);
}
public function deleteRounds(Round $round, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($round), $override);
$mapper->delete($round,$workout);
}
public function deleteDescriptions(Description $description, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($description), $override);
$mapper->delete($description,$workout);
}
public function deleteNames(Name $name, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($name), $override);
$mapper->delete($name,$workout);
}
public function deleteTags(Tag $tag, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($tag), $override);
$mapper->delete($tag,$workout);
}
/*********************************************************************************************/
/************************************ Fetch **************************************/
/*********************************************************************************************/
public function getDescriptions(DescriptionCollection $description, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($description), $override);
$mapper->fetch($description, $workout);
}
public function getRounds(RoundCollection $round, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($round), $override);
$mapper->fetch($round, $workout);
}
public function getNames(NameCollection $name, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($name), $override);
$mapper->fetch($name,$workout);
}
public function getWorkout(Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($workout), $override);
$mapper->fetch($workout);
}
public function getTags(TagCollection $tag, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($tag), $override);
$mapper->fetch($tag, $workout);
}
public function getWorkoutList(WorkoutListCollection $list, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($list), $override);
$mapper->fetch($list, $workout);
}
public function getTotalWorkotus(Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($workout), $override);
$mapper->total($workout);
}
/*********************************************************************************************/
/*********************************** Update ********************************************/
/*********************************************************************************************/
public function updateNameState(NameCollection $name, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($name), $override);
$mapper->update($name, $workout);
}
public function updateRoundState(RoundCollection $round, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($round), $override);
$mapper->update($round,$workout);
}
public function updateBaseState(Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($workout), $override);
$mapper->update($workout);
}
public function updateDescriptionState(DescriptionCollection $description, Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($description), $override);
$mapper->update($description,$workout);
}
/*********************************************************************************************/
/*********************************** Audit ********************************************/
/*********************************************************************************************/
public function auditRound(Round $round,Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($round), $override);
$mapper->storeToAudit($round, $workout);
}
public function auditDescription(Description $description,Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($description), $override);
$mapper->storeToAudit($description, $workout);
}
public function auditBase(Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($workout), $override);
$mapper->storeToAudit($workout);
}
public function auditName(Name $name,Workout $workout, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($name), $override);
$mapper->storeToAudit($name,$workout);
}
/*********************************************************************************************/
/*********************************** Helpers ********************************************/
/*********************************************************************************************/
public function begginTransaction()
{
$mapper = $this->mapperFactory->create(WorkoutBase::class);
$mapper->begginTransaction();
}
public function commitTransaction()
{
$mapper = $this->mapperFactory->create(WorkoutBase::class);
$mapper->commit();
}
private function computeKey(string $key, string $override = null): string
{
if ($override !== null) {
$key = $override;
}
if (array_key_exists($key, $this->list) === false) {
throw new \RuntimeException("No mapper for class '{$key}' has been defined!");
}
return $key;
}
private function retrieveMapper(string $name, string $override = null)
{
$key = $this->computeKey($name, $override);
$entry = $this->list[$key];
return $this->mapperFactory->create($entry);
}
public function define(string $entity, string $mapper)
{
if (class_exists($entity) === false) {
throw new \RuntimeException("Entity class '{$entity}' was not found!");
}
if (class_exists($mapper) === false) {
throw new \RuntimeException("Mapper class '{$mapper}' was not found!");
}
$this->list[$entity] = $mapper;
}
public function load($identity, string $override = null)
{
$mapper = $this->retrieveMapper(get_class($identity), $override);
$mapper->fetch($identity);
}
}
</code></pre>
<p>VersionMapper.php</p>
<pre><code><?php
class VersionMapper extends DataMapper
{
/**
* Version Up
*
* @param Version $version
*/
public function versionUp(Version $version) // TODO handle exceptions
{
$sql = "INSERT INTO version VALUES(null)";
$statement = $this->connection->prepare($sql);
$statement->execute();
$version->setVersion($this->connection->lastInsertId());
}
}
</code></pre>
<p>AddWorkoutDomain.php</p>
<pre><code><?php
class AddWorkoutDomain
{
private $repository;
public function __construct(Repository $repository)
{
$this->repository = $repository;
}
/*********************************************************************************************/
/***************************** Visible functions to children ******************************/
/*********************************************************************************************/
/**
* Handle
*
* @param Workout $workout
* @return array
*/
public function handle(Workout $workout):array
{
// beggin transaction
$this->repository->begginTransaction();
$messages = [];
$messages = array_merge($messages, $this->storeBase($workout));
$messages = array_merge($messages, $this->storeNames($workout));
$messages = array_merge($messages, $this->storeDescriptions($workout));
$messages = array_merge($messages, $this->storeRounds($workout));
$messages = array_merge($messages, $this->storeTags($workout));
// commit transaction
$this->repository->commitTransaction();
return $messages;
}
/**
* Get Total
*
* @param Workout $workout
*/
public function getTotal(Workout $workout):void
{
$this->repository->getTotalWorkotus($workout);
}
/*********************************************************************************************/
/************************************* Executors ******************************************/
/*********************************************************************************************/
/**
* Store Base
*
* @param Workout $workout
* @return array
*/
private function storeBase(Workout $workout):array
{
// version up
$workout->setVersion($this->versionUp()->getVersion());
$workout->setState('P');
$this->repository->storeBase($workout);
return ['success'=>'Base'];
}
/**
* Store Names
*
* @param Workout $workout
* @return array
*/
private function storeNames(Workout $workout):array
{
foreach($workout->getNames()->toArray() as $name){
// set workout parent
$name->setParent($workout->getId());
$name->setState('P');
$this->repository->storeName($name);
}
return ['success'=>'Names'];
}
/**
* Store Descriptions
*
* @param Workout $workout
* @return array
*/
private function storeDescriptions(Workout $workout):array
{
foreach($workout->getDescriptions()->toArray() as $description){
// set workout parent
$description->setParent($workout->getId());
$description->setState('P');
$this->repository->storeDescription($description);
}
return ['success'=>'Descriptions'];
}
/**
* Store Rounds
*
* @param Workout $workout
* @return array
*/
private function storeRounds(Workout $workout):array
{
foreach($workout->getRounds()->toArray() as $round){
// set workout parent
$round->setParent($workout->getId());
$round->setState('P');
$this->repository->storeRound($round);
}
return ['success'=>'Rounds'];
}
/**
* Store Tags
*
* @param Workout $workout
* @return array
*/
private function storeTags(Workout $workout):array
{
foreach($workout->getTags()->toArray() as $tag){
// set workout parent
$tag->setParent($workout->getId());
$this->repository->storeTag($tag);
}
return ['success'=>'Rounds'];
}
/**
* Version Up
*
* @return Version
*/
private function versionUp():Version
{
$version = new Version();
$this->repository->versionUp($version);
return $version;
}
}
</code></pre>
<p>Any comment and advice are welcome, I'm seeking to expand my knowledge.</p>
<p>Credits to <a href="https://stackoverflow.com/users/727208/tere%C5%A1ko">Tereško</a> for helping me out.</p>
| [] | [
{
"body": "<p>Take the following <code>Kernel</code> class:</p>\n\n<pre><code>class Kernel\n{\n protected $env;\n\n const ENV_TYPE_DEV = 'dev';\n const ENV_TYPE_PROD = 'prod';\n\n public function __construct($env = null)\n {\n $this->env = $env ?? self::ENV_TYPE_DEV;\n }\n\n /**\n * Loads the container configuration.\n */\n public function registerContainerConfiguration()\n {\n if ($this->env === self::ENV_TYPE_DEV) {\n $configuration = 'config-development.yml';\n } else {\n $configuration = 'config-production.yml';\n }\n\n return $configuration;\n }\n}\n</code></pre>\n\n<p>The changes I made are as follows:</p>\n\n<ul>\n<li>Defined two constants so you can reference them rather than passing a direct string as the <code>$env</code>. This also gives you the option to change the values in the future without having to consider hardcoded versions of the values</li>\n<li>Simplified your <code>if</code> statement (via the <a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"nofollow noreferrer\">null coalescing operator</a>) in your <code>__construct</code> to set the <code>$env</code> property to whatever is passed to <code>ENV_TYPE_DEV</code> as a default</li>\n<li>In <code>registerContainerConfiguration</code> I removed your casts as they were redundant and turned the hard-coded string into the respective <code>const</code></li>\n</ul>\n\n<p>Then your <code>index.php</code> file:</p>\n\n<pre><code>use Symfony\\Component\\HttpFoundation\\Request;\n// load vendor\nrequire __DIR__.'/../vendor/autoload.php';\n\n// autoloading done through composer\n// error handling based on kernel env\n// type that is passed.\n\n// new kernel\n$kernel = new Kernel(Kernel::ENV_TYPE_DEV);\n$bootstrap = new Bootstrap;\n\n// new request\n$request = Request::createFromGlobals();\n// loader interface\n$config = $kernel->registerContainerConfiguration();\n// response from\n$response = $bootstrap->handle($request, $config, null);\n</code></pre>\n\n<p>The changes I made / suggest are as follows:</p>\n\n<ul>\n<li>You should have your error reporting work in conjunction with your environment that is defined in your <code>Kernel</code></li>\n<li>You should autoload your classes through composer</li>\n<li>I changed the hardcoded <code>dev</code> string to the defined constant</li>\n</ul>\n\n<p>In your <code>AddWorkoutDomain</code> class, I'd simplify the handle function:</p>\n\n<pre><code>/**\n * Handle \n * \n * @param Workout $workout\n * @return array\n */\n public function handle(Workout $workout):array\n {\n // beggin transaction\n $this->repository->begginTransaction();\n\n $messages = array_merge($messages, $this->storeBase($workout), $this->storeNames($workout), $this->storeDescriptions($workout), $this->storeRounds($workout), $this->storeTags($workout));\n\n // commit transaction\n $this->repository->commitTransaction();\n\n return $messages;\n }\n</code></pre>\n\n<ul>\n<li>Merged the <a href=\"https://www.php.net/manual/en/function.array-merge.php\" rel=\"nofollow noreferrer\"><code>array_merge</code></a> calls into one (pun intended...), as per the documentation, the second parameter can be a list of variables to merge, doesn't have to be one per function call</li>\n</ul>\n\n<h2>Miscellaneous</h2>\n\n<ul>\n<li>Opinionated but, you seem to have quite a few blank lines within your classes, I would reduce that down</li>\n<li><p>In various places you check for <code>null</code> variables in long, drawn out, if statements:</p>\n\n<pre><code>if(!is_null($workout->getOffset()) && !is_null($workout->getLimit()) && !is_null($workout->getState())){\n return $this->workoutService->getWorkoutList($workout);\n}\n</code></pre></li>\n</ul>\n\n<p>Consider the following:</p>\n\n<pre><code>if (isset($workout->getOffset(), $workout->getLimit(), $workout->getState())) {\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T06:41:48.103",
"Id": "419304",
"Score": "0",
"body": "I have implemented your changes, thank you!\n\nI won't accept your answer but I will upvote it.\n\nIf you could go through the whole code and give me full feedback on my code and classes and how it can be reduced I will accept it then."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:40:13.727",
"Id": "216718",
"ParentId": "216714",
"Score": "3"
}
},
{
"body": "<p>Since nobody answered my question probably because I have not explained what I want here is an answer which satisfied my needs. </p>\n\n<p>I have been wondering in the dark than I have found this <a href=\"https://stackoverflow.com/questions/3937586/generic-programming-vs-metaprogramming\">answer</a> which expanded my knowledge regarding programming.</p>\n\n<p>I have seen some of those methods but I have never taught of the level of abstraction which they can bring.</p>\n\n<p>As the accepted answer states:</p>\n\n<blockquote>\n <p>Programming: Writing a program that creates, transforms, filters,\n aggregates and otherwise manipulates data.</p>\n \n <p>Metaprogramming: Writing a program that creates, transforms, filters,\n aggregates and otherwise manipulates programs.</p>\n \n <p>Generic Programming: Writing a program that creates, transforms,\n filters, aggregates and otherwise manipulates data, but makes only the\n minimum assumptions about the structure of the data, thus maximizing\n reuse across a wide range of data types.</p>\n</blockquote>\n\n<p>I saw that I have been typing code which can be easily avoided.</p>\n\n<p>Long story short here is my implementation to the issue I had.</p>\n\n<hr>\n\n<p>My controller is still not there where I want it to be but I have managed to call my actions like this:</p>\n\n<pre><code> return $this->baseService->actionHandler($exercise,\n [\n BaseService::ACT_GET_NAME,\n BaseService::ACT_GET_DESC,\n BaseService::ACT_GET_BASE,\n BaseService::ACT_GET_OBJ\n ],\n $queryParams\n );\n</code></pre>\n\n<p>And my service looks something like this:</p>\n\n<pre><code>class BaseService\n{\n\n // vars\n private $domainRepository;\n private $responseBootstrap;\n private $versionDomain;\n private $nameDomain;\n private $tagDomain;\n private $planDomain;\n private $packageDomain;\n private $roundDomain;\n private $auditDomain;\n private $deleteDomain;\n private $languageDomain;\n\n\n //actions create\n const ACT_VERSION = 'versionUp';\n const ACT_CREATE = 'createObject';\n const ACT_SINGLE_OBJ = 'returnSingleObject';\n const ACT_CRE_NAME = 'createName';\n const ACT_CRE_DESC = 'createDescription';\n const ACT_CRE_TAG = 'createTags';\n const ACT_CRE_BODY = 'createBody';\n const ACT_CRE_PKG_PLAN = 'createPackagePlan';\n const ACT_CRE_WRK_PLN_DAY = 'createWorkoutPlanDay';\n const ACT_CRE_ROUND = 'createRound';\n const ACT_RELEASE = 'releaseContent';\n const ACT_DELETE = 'delete';\n\n // actions delete \n const ACT_ED_NAME = 'editName';\n const ACT_ED_OBJ = 'editObject';\n const ACT_ED_DESC = 'editDescription';\n const ACT_ED_TAG = 'editTag';\n const ACT_ED_ROUND = 'editRound';\n const ACT_ED_BODY = 'editBody';\n const ACT_ED_DAY = 'editDay';\n const ACT_ED_PKG_PLAN = 'editPackagePlan';\n\n // actions get\n const ACT_GET_NAME = 'getName';\n const ACT_GET_DESC = 'getDescription';\n const ACT_GET_BODY = 'getBody';\n const ACT_GET_OBJ = 'getObjectResponse';\n const ACT_GET_BASE = 'getBase';\n\n // system actions\n const SYS_ACT_BEG_TRANS = 'begginTransaction';\n const SYS_ACT_COM_TRANS = 'commitTransaction';\n const SYS_ACT_ROLB_TRANS = 'rollbackTransaction';\n\n private $responseArray = [];\n\n\n\n /**\n * Constructor\n * \n * @param DomainRepository $domainRepository\n * @param ResponseBootstrap $responseBootstrap\n * @param VersionDomain $versionDomain\n * @param NameDomain $nameDomain\n * @param NameDomain $descriptionDomain\n */\n\n public function __construct(\n DomainRepository $domainRepository,\n ResponseBootstrap $responseBootstrap,\n VersionDomain $versionDomain,\n NameDomain $nameDomain,\n TagDomain $tagDomain,\n PlanDomain $planDomain,\n PackageDomain $packageDomain,\n RoundDomain $roundDomain,\n AuditDomain $auditDomain,\n DeleteDomain $deleteDomain, \n LanguageDomain $languageDomain)\n {\n $this->domainRepository = $domainRepository;\n $this->responseBootstrap = $responseBootstrap;\n $this->versionDomain = $versionDomain;\n $this->nameDomain = $nameDomain;\n $this->tagDomain = $tagDomain;\n $this->planDomain = $planDomain;\n $this->packageDomain = $packageDomain;\n $this->roundDomain = $roundDomain;\n $this->auditDomain = $auditDomain;\n $this->deleteDomain = $deleteDomain;\n $this->languageDomain = $languageDomain;\n }\n\n\n /**\n * Action Handler\n * \n * @param object $object\n * @param array $actions\n * @return object\n */\n public function actionHandler(object $object, array $actions = [], QueryParams $queryParams = null):object\n {\n try{\n // beggin transaction\n $this->domainRepository->begginTransaction();\n\n foreach($actions as $action){\n // on create return object\n if($action == BaseService::ACT_SINGLE_OBJ){\n // commit transaction\n $this->domainRepository->commitTransaction(); \n return $this->{$action}($object);\n }\n // on get return object\n else if($action == BaseService::ACT_GET_OBJ){\n // commit transaction\n $this->domainRepository->commitTransaction();\n\n return $this->{$action}();\n }else{\n $this->{$action}($object, $queryParams);\n }\n } \n }catch(\\PDOException $e){\n // handle rollback of sql action\n $this->domainRepository->rollbackTransaction($e);\n }\n }\n\n\n /*********************************************************************************************/\n /*********************************** Executors *********************************/\n /*********************************************************************************************/\n\n\n /**\n * Version Up\n * \n * @param object $object\n */\n private function versionUp(object $object):void\n {\n // version up\n $this->versionDomain->handle($object);\n }\n\n ...........\n</code></pre>\n\n<p>The <strong>BaseService</strong> class has all the actions and it calls the DAO layer which is flexible enough to construct the query I need.</p>\n\n<p>I need to add a caching layer to it and a few more things but this is the answer which I have been asking for(at least I think so if somebody else had a better version of it feel free to post your answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T10:09:42.933",
"Id": "217481",
"ParentId": "216714",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217481",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:27:01.740",
"Id": "216714",
"Score": "5",
"Tags": [
"php",
"api",
"rest"
],
"Title": "Avoiding code repeating in RESTful APIS PHP"
} | 216714 |
<p>I recently had to code an algorithm that will, for an input of: matrix of up to 5x5 size and a defined path length, find a path of this given length from the first top left matrix element (0, 0) to the last bottom right element (n, n). The desired path is the one which maximizes the sum of matrix elements along the path. After reading about common path finding algorithms like Dijkstra or A* and DFS vs. BFS, here is what I've come up with:</p>
<pre><code>def gridsum(grid):
"""Calculates sum of all grid elements"""
s = 0
for el in grid:
s += sum(el)
return s
def longpaths(grid, path):
"""Function to calculate best path for long paths with respect to no. of grid elements"""
# For path length equal to number of grid elements, the solution is trivial:
if path == len(grid)*len(grid[0]):
return gridsum(grid)
# Not sure down to which path length this works..?
if path+1 == len(grid)*len(grid[0]):
s = gridsum(grid)
del grid[0][0]
del grid[len(grid)-1][len(grid[-1])-1]
return s - min(sum(grid, []))
if path+2 == len(grid)*len(grid[0]):
s = gridsum(grid)
del grid[0][0]
del grid[len(grid)-1][len(grid[-1])-1]
m1 = min(sum(grid, []))
s -= m1
for i in range(len(grid)):
if m1 in grid[i]:
gindexm1 = i
grid[gindexm1].remove(m1)
return s - min(sum(grid, []))
class Node():
def __init__(self, parent=None, position=None, value=0):
self.position = position # a tuple representing the indices in grid
self.value = value # grid position value
self.cpl = 0 # current path length
self.cpv = 0 # current path value
self.parents = [parent]
if parent is not None:
for el in parent.parents:
self.parents.append(el)
def __eq__(self, other):
return self.position == other.position
def minsteps(grid, position):
"""Calculates the minimum number of steps necessary to reach target node"""
steps = 0
x, y = position[0], position[1]
while x < len(grid)-1 and y < len(grid[0])-1:
x, y, steps = x+1, y+1, steps+1
while x < len(grid)-1:
x, steps = x+1, steps+1
while y < len(grid[0])-1:
y, steps = y+1, steps+1
return steps
def g_key(grid, path):
# For long paths relative to amount of grid elements, solution is simple
if path+2 >= len(grid)*len(grid[0]):
return longpaths(grid, path)
# Create start and end node
start_node = Node(None, (0, 0), grid[0][0])
start_node.cpv = start_node.value
start_node.cpl = 1
end_node = Node(None, (len(grid)-1, len(grid[0])-1), grid[len(grid)-1][len(grid[0])-1])
# Add a node queue to loop through, start node has not been previously visited
queued_nodes = [start_node]
previously_visited = None
final_path_values = []
while len(queued_nodes) > 0:
# Set current node to first element of queued nodes
current_node = queued_nodes[0]
# If target is unreachable within path length restrictions, skip calculation of this node
if path-current_node.cpl < minsteps(grid, current_node.position):
queued_nodes.remove(current_node)
continue
# Add all paths with length {path} that end at the final node to final paths list
if current_node.cpl == path:
if current_node == end_node:
final_path_values.append(current_node.cpv)
queued_nodes.remove(current_node)
continue
# Generate child nodes to current node, make sure new nodes are within grid and
# have not been visited within the current path, then add them to the node queue
children = []
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1)]: # adjacent grid elements
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
if any((node_position[0] < 0, node_position[1] < 0, node_position[0] > len(grid)-1, node_position[1] > len(grid[0])-1)):
continue
new_child = Node(current_node, node_position, grid[node_position[0]][node_position[1]])
for parent in new_child.parents:
if parent is not None:
if node_position == parent.position:
previously_visited = True
if previously_visited:
previously_visited = False
continue
children.append(new_child)
queued_nodes.append(new_child)
# Update current path length and value for children
for child in children:
child.cpl = current_node.cpl + 1
child.cpv = current_node.cpv + child.value
# Calculation for this node done, remove it from queue
queued_nodes.remove(current_node)
return max(final_path_values)
</code></pre>
<p>For an input of:</p>
<pre><code>g_key([[1, 6, 7, 2, 4],
[0, 4, 9, 5, 3],
[7, 2, 5, 1, 4],
[3, 3, 2, 2, 9],
[2, 6, 1, 4, 0]], 9)
</code></pre>
<p>this code finds the correct solution of 46.</p>
<p>However, this algorithm is incredibly slow, as I think it scales with <span class="math-container">\$O(n^m)\$</span>, where n = matrix size and m = path length, and memory intensive since every node has to keep track of every parent/grandparent/great-grandparent node it has to prevent visiting matrix elements multiple times within each path. That is why I had to add the longpaths function to get reasonable runtimes for long paths.</p>
<p>Is there any way to speed this up or at least make it less memory intensive? I have found plenty of documentation how to do this if we just wanted to minimize the path length, but since in this case we want to maximize the path value while keeping a constant path length, I haven't been able to come up with a way to improve on what is basically a brute-force method of calculating everything.</p>
| [] | [
{
"body": "<p>This is pretty easily solvable in <code>O(n^2)</code>. Notice that any longest path from <code>a</code> to <code>c</code> with length <code>>1</code> is a combination of a longest <code>ab</code> path and a longest <code>bc</code> path for some <code>b</code>. What you want to do here is to find the longest path to all squares using dynamic programming. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T01:16:10.297",
"Id": "419286",
"Score": "0",
"body": "The desired path length is given as input, we're interested in the path of this length that maximizes the sum of matrix elements it passes by (for the example input I provided, the path of length 9 is: (start: element (0, 0)) 1, 6, 7, 9, 5, 5, 4, 9, 0 (end: element (n, n)), the sum of which is 46). Breaking the problem down into smaller subproblems does not seem trivial to me, since the final solution for path length of x may be completely different from the final solution for path length of x-1 and thus not composed of the solutions for shorter paths."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T16:42:58.137",
"Id": "216733",
"ParentId": "216717",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T09:56:30.187",
"Id": "216717",
"Score": "2",
"Tags": [
"python",
"performance",
"graph",
"pathfinding"
],
"Title": "Maximize Path Value"
} | 216717 |
<pre><code>Const FOLDERPATH As String = "\ITSEASY"
Const DATAFOLDER As String = "\AS"
Const OLDDATAFOLDER As String = "\ABC"
Public Sub ExportData()
Application.ScreenUpdating = False
'GET DROPBOX PATH
Dim TheDropBoxPath As String
TheDropBoxPath = DropBoxPath.GetDBPath
Dim files() As Variant 'STARTS AT 1
files = FileStuff.listfiles(TheDropBoxPath & FOLDERPATH & DATAFOLDER)
Dim NumberOfFlies As Integer
On Error GoTo blob
NumberOfFlies = UBound(files)
On Error GoTo 0
'FILE FOR EXPORTED DATA
Dim ExportWB As Workbook
Set ExportWB = Workbooks.Open(TheDropBoxPath & FOLDERPATH & "\" &
"Pushed.xlsx")
Dim ExportWBLastRow As Long
ExportWB.Sheets(1).UsedRange.Clear
'FILE BEING READ
Dim DataWB As Workbook
Dim DataWBLastRow As Long
For i = 1 To UBound(files)
'OPEN THE FILE
Set DataWB = Workbooks.Open(TheDropBoxPath & FOLDERPATH & DATAFOLDER & "\" & files(i))
DataWBLastRow = DataWB.Sheets(1).Cells(1, 1).End(xlDown).Row
If i > 1 Then 'LAZY
ExportWBLastRow = ExportWB.Sheets(1).Cells(1, 1).End(xlDown).Row + 1
End If
If i = 1 Then 'FOR HEADER ROW
DataWB.Sheets(1).Range("1:1").Copy
ExportWB.Sheets(1).Range("A1").PasteSpecial xlPasteValues
ExportWBLastRow = 2
End If
'COPY PASTE CONTENT
DataWB.Sheets(1).Range("2:" & DataWBLastRow).Copy
ExportWB.Sheets(1).Range("A" & ExportWBLastRow).PasteSpecial xlPasteValues
Application.DisplayAlerts = False
DataWB.Close
Application.DisplayAlerts = True
'MOVE FILE TO OLD
Call FileStuff.MoveFiles(TheDropBoxPath & FOLDERPATH & DATAFOLDER & "\" & files(i), TheDropBoxPath & FOLDERPATH & DATAFOLDER & "\AYE\" & files(i))
Next i
ExportWB.Sheets(1).UsedRange.RemoveDuplicates Columns:=1, Header:=xlGuess
ThisWorkbook.Save
Application.DisplayAlerts = False
ExportWB.Save
ExportWB.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox (NumberOfFlies & " dfghdfsgsfg tf " & Chr(34) & "FAKETEXT" & Chr(34) & "BLABLA")
Exit Sub
blob: MsgBox ("FAKE MESSAGE NUMBER 2 " & TheDropBoxPath & FOLDERPATH & DATAFOLDER): Exit Sub
End Sub
</code></pre>
<p>I'm looking for improvement on the way I deal with processing multiple files. Currently i'm using FSO, I feel like it's slow. Any better way to do that ?</p>
<p>Is there a way to copy the content of a sheet without having to open it ?</p>
<p>Self answer : ADODB does that</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T19:52:54.937",
"Id": "419261",
"Score": "0",
"body": "If they are Excel files, ADODB is a decent approach without having to go through the Excel object model. If they aren't excel files. or you can convert them to a e.g. csv file there are alternatives. Buffering a string, then using `Get` is very fast. Have a look for potentially some helpful methods if you decide to go that route. https://codereview.stackexchange.com/a/188068/108307"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:25:36.050",
"Id": "419359",
"Score": "0",
"body": "They are excel files, however I'm very open to having to go though excel object model(I will, I want to know everything about excel). I have managed to do it using ADODB connection. however it was useless as the range I need to do things with isn't known before I open the file and is identified by another sub I have created (the way I have managed to do it required the range fed to the recordset / sql query) and no table in the files either obviously.\nNo problem converting the files to csv. \nLooking at your link RN, not sure I understand it all and how it apply to my problem. Will dig.\nTY."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T19:16:11.193",
"Id": "419378",
"Score": "0",
"body": "Solution offering is going to be dependent on your data and what you are trying to accomplish. Some examples might be helpful here. As for this part \"I have managed to do it using ADODB connection. however it was useless as the range I need to do things with isn't known before I open the file and is identified by another sub I have created...\" ADODB should be picking the sheet up as a table, so all the data should be there in a recordset object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T12:06:09.327",
"Id": "419444",
"Score": "0",
"body": "i'm going to read a bit more about adodb then. \nThe example I was folowing was putting a range in the ADODB.Recordset like in this thread : [link](https://stackoverflow.com/questions/39415326/search-workbook-and-extract-data-without-opening-it-excel-vba)\n\nCould you ellaborate on what you meant by buffering a string out of the book converted to csv. Convert to csv : Can do. Turn Csv to string : can do. What do you mean by buffering ? and `get`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T16:44:11.977",
"Id": "419479",
"Score": "0",
"body": "One way to speed up string operations is to allocate a string to the size you need ahead of time. You do this to avoid the string being reallocated every time you change it as strings are immutable. You can set size of a string like `myString = Space$(50000)`. `Get` is a vba statement to read data from a file to a variable. You can read more about it here --> https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/get-statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T11:01:02.247",
"Id": "419540",
"Score": "0",
"body": "Now that I took the time to read the full thread (your link in first comment) I understand, seems within my reach for the \"slower\" version of processing file you answered in that thread.\nWill try to adapt it to my needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T21:07:43.723",
"Id": "420603",
"Score": "0",
"body": "I found for my requirements the DIR function provided much better speed than the FSO"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T10:52:30.930",
"Id": "216719",
"Score": "0",
"Tags": [
"vba",
"excel"
],
"Title": "VBA processing multiple files"
} | 216719 |
<p>I saw this question and wondered how it'd be best to accomplish this using Ramda.</p>
<p>I'm new to the library so I thought it'd be an interesting learning exercise.</p>
<p>I have a working solution but it seems overly complicated and verbose. I'd be grateful for any suggestions on what other ways it would be possible to achieve this output using Ramda.</p>
<p>I'm aware that this doesn't need a library; as I say, I approached it as a learning exercise.</p>
<p>Here's what I have:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { addIndex, always, fromPairs, join, map, sort, toPairs, unnest } = R;
const song = {
"99": [0, 7],
"bottles": [1, 8],
"of": [2, 9],
"beer": [3, 10],
"on": [4],
"the": [5],
"wall": [6]
};
const toSentence = join(' ');
const parsed = toSentence(
map(
([_, word]) => word,
sort(
([a, _], [b, __]) => a < b ? -1 : 1,
unnest(
map(
([word, indices]) => map(
index => [index, word],
indices,
),
toPairs(song)
)
)
)
)
)
console.dir(parsed)</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T16:44:29.050",
"Id": "419255",
"Score": "1",
"body": "Reverse the order of the `sort` and the `map`, then the sort doesn't need to do \\$n \\cdot log(n)\\$ array dereferences. Your sort function is unstable and won't preserve the ordering of equal elements. It doesn't matter in this problem; when it does matter, it's a source of nasty, subtle bugs, so always be aware of when you're doing that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T07:47:24.330",
"Id": "419309",
"Score": "0",
"body": "@OhMyGoodness Thank you for your comment, which is very useful!"
}
] | [
{
"body": "<p>This is a great question.</p>\n\n<p>I found no easy Ramda functional way to solve this, but you could just use a forEach approach. I find it easier to read.</p>\n\n<pre><code>const {forEachObjIndexed, forEach} = R;\n\nconst song = {\n \"99\": [0, 7],\n \"bottles\": [1, 8],\n \"of\": [2, 9],\n \"beer\": [3, 10],\n \"on\": [4],\n \"the\": [5],\n \"wall\": [6]\n};\n\nlet words = [];\n\nforEachObjIndexed((indexes, word) => forEach(idx => words[idx] = word, indexes), song);\n\nconsole.log(words.join(' '));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T08:00:52.817",
"Id": "419311",
"Score": "0",
"body": "This is an interesting approach to the problem and I also find it easier to read than the code I had"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:16:52.093",
"Id": "216750",
"ParentId": "216722",
"Score": "1"
}
},
{
"body": "<h2>Names</h2>\n<p>Variable names are very important,Try to keep the code understandable by defining named functions that relate to the abstract thing the do. (see example)</p>\n<p>Same with the arguments. The names <code>indices</code>, and <code>index</code> are misleading. You are referring to the word position. Thus the names <code>positions</code> and <code>position</code> would be better suited. I would use <code>pos</code> rather than <code>position</code></p>\n<h2>Redundant code</h2>\n<ul>\n<li><p>In the sorting compare function the two arguments <code>_</code>, and <code>__</code> are not not needed. The return can be any number value -10 and -1 are equivalent, so use the sorter for <code>a-b</code>. <code> ([a, _], [b, __]) => a < b ? -1 : 1,</code> becomes <code>([a], [b]) => a - b,</code></p>\n</li>\n<li><p>The function extracting the word can be <code>pair => pair[1],</code> or <code>([, word]) => word,</code> rather than <code>([_, word]) => word,</code></p>\n</li>\n<li><p>Why store the result in <code>parsed</code>. Just pass it on to the handling function. In this case the console.</p>\n</li>\n</ul>\n<h2>Scope clutter</h2>\n<p>Keep the Ramba functions associated with the object so you don't end up with name clashes, and it makes it clearer what is doing what. (see example)</p>\n<h2>Example</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const lyrics = {\"99\": [0, 7],\"bottles\": [1, 8], \"of\": [2, 9], \"beer\": [3, 10], \"on\": [4], \"the\": [5], \"wall\": [6]};\n\nconst log = console.log;\nconst song = R.join(' ');\nconst position = ([a], [b]) => a - b;\nconst word = ([,word]) => word;\nconst swapPair = ([word, positions]) => R.map(pos=> [pos, word], positions);\n\nlog(\n song(\n R.map(\n word, R.sort(\n position, R.unnest(R.map(\n swapPair, R.toPairs(lyrics)\n ))\n )\n )\n )\n);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T00:24:24.530",
"Id": "216755",
"ParentId": "216722",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T12:51:47.707",
"Id": "216722",
"Score": "2",
"Tags": [
"javascript",
"ramda.js"
],
"Title": "Ramda - Forming a string based on array of word positions"
} | 216722 |
<p>I created a very simple multiple choice math practice game in C for a fun project. Essentially the user first enters how many questions they want, then they enter what operation (+, -, *, /) they want to practice. The game then presents a set of 4 multiple choice answers. The user enters which choice thy think is correct and the program tells them if they were right or wrong. This process continues until the last question, after that the program tells the user the time they took and the percent they got correct.</p>
<pre><code>#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
int TwoDigNum = 0;
int ThreeDigNum = 0;
int Answer = 0;
int NumCorrect = 0;
int TotalProbs = 0;
char StudentAns;
char AnswerLoc;
time_t Start,End;
void AddProbScript(int TwoDigNum, int ThreeDigNum)
{
printf("Solve the following: %d + %d\n", TwoDigNum, ThreeDigNum);
printf("Here are your choices:\n");
}
void SubProbScript(int TwoDigNum, int ThreeDigNum)
{
printf("Solve the following: %d - %d\n", ThreeDigNum, TwoDigNum);
printf("Here are your choices:\n");
}
void MultProbScript(int TwoDigNum, int ThreeDigNum)
{
printf("Solve the following: %d x %d\n", TwoDigNum, ThreeDigNum);
printf("Here are your choices:\n");
}
void DivProbScript(int TwoDigNum, int ThreeDigNum)
{
printf("Solve the following: %d / %d\n", ThreeDigNum, TwoDigNum);
printf("Here are your choices:\n");
}
int FindAns(char C, int TwoDigNum, int ThreeDigNum)
{
int Ans = 0;
switch (C)
{
case '+':
Ans = TwoDigNum + ThreeDigNum;
break;
case '-':
Ans = ThreeDigNum - TwoDigNum;
break;
case 'x':
Ans = TwoDigNum * ThreeDigNum;
break;
case '*':
Ans = TwoDigNum * ThreeDigNum;
break;
default:
Ans = ThreeDigNum/TwoDigNum;
}
return Ans;
}
void MakeAnswers(int Ans)
{
srand(time(NULL));
int WhereToPut = rand() % 999;
int Rand1 = rand() % 99;
int Rand2 = (rand() % 9) * 2;
int Rand3 = ((rand() % 9) * (rand() % 9))+1;
if (WhereToPut < 250)
{
printf("A.) %d\n", Ans + Rand1);
printf("B.) %d\n", Ans);
printf("C.) %d\n", Ans + Rand2);
printf("D.) %d\n", Ans - Rand3);
AnswerLoc = 'b';
}
if (WhereToPut >= 250 && WhereToPut < 500)
{
printf("A.) %d\n", Ans - Rand1);
printf("B.) %d\n", Ans + Rand2);
printf("C.) %d\n", Ans + Rand3);
printf("D.) %d\n", Ans);
AnswerLoc = 'd';
}
if (WhereToPut >= 500 && WhereToPut < 750)
{
printf("A.) %d\n", Ans);
printf("B.) %d\n", Ans - Rand1);
printf("C.) %d\n", Ans + Rand2);
printf("D.) %d\n", Ans + Rand3);
AnswerLoc = 'a';
}
if (WhereToPut >= 750)
{
printf("A.) %d\n", 2*Rand1);
printf("B.) %d\n", Ans + Rand2);
printf("C.) %d\n", Ans);
printf("D.) %d\n", Ans - Rand3);
AnswerLoc = 'c';
}
}
void CheckAnswer(char AnswerLoc)
{
printf("Enter the choice you think is the answer:");
StudentAns = getch();
printf("%c", StudentAns);
if (StudentAns == AnswerLoc)
{
printf("\nGOOD JOB! You got it right!");
NumCorrect++;
}
else
{
printf("\nThat's wrong, but keep trying!");
}
}
int main()
{
srand(time(NULL));
printf("How many problems do you want to do?");
scanf("%d", &TotalProbs);
Start = clock();
for (int i = 0; i<TotalProbs ;i++)
{
ThreeDigNum = (rand() % 999);
TwoDigNum = (rand() % 99) + 1;
printf("\nEnter what operation you want to practice (+,-,x,/):");
char C = getch();
printf("%c\n", C);
switch (C)
{
case '+':
AddProbScript(TwoDigNum, ThreeDigNum);
Answer = FindAns(C, TwoDigNum, ThreeDigNum);
MakeAnswers(Answer);
CheckAnswer(AnswerLoc);
break;
case '-':
SubProbScript(TwoDigNum, ThreeDigNum);
Answer = FindAns(C, TwoDigNum, ThreeDigNum);
MakeAnswers(Answer);
CheckAnswer(AnswerLoc);
break;
case 'x':
MultProbScript(TwoDigNum, ThreeDigNum);
Answer = FindAns(C, TwoDigNum, ThreeDigNum);
MakeAnswers(Answer);
CheckAnswer(AnswerLoc);
break;
default:
DivProbScript(TwoDigNum, ThreeDigNum);
Answer = FindAns(C, TwoDigNum, ThreeDigNum);
MakeAnswers(Answer);
CheckAnswer(AnswerLoc);
}
}
End = clock();
double PercentCorrect = ((double)(NumCorrect) / TotalProbs)*100;
double t = (End - Start) / CLOCKS_PER_SEC;
printf("\nWow you got %d out %d correct! Thats %.2f percent!", NumCorrect, TotalProbs, PercentCorrect);
printf("Time taken: %.2f seconds\n\n\n", t);
if (PercentCorrect >= 90.0)
{
for (int x = 0; x < 100; x++)
{
system("color 0a");
Sleep(100);
system("color 0b");
Sleep(100);
system("color 0c");
Sleep(100);
system("color 0d");
Sleep(100);
system("color 0e");
Sleep(100);
system("color 0f");
Sleep(100);
}
}
else
exit(0);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T16:00:07.903",
"Id": "419251",
"Score": "1",
"body": "*\"some of the randomly generated answer choices come out to the same number. How can I avoid this?\"* is off-topic for a review; you're supposed to have the code **working as intended** before asking for review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T22:19:08.853",
"Id": "419280",
"Score": "0",
"body": "@TobySpeight The code is working as intended, there is just a slight issue that happens occasionally. I was just seeking some help to see why that is happening. This is not HW or anything I just decided to make this for fun to practice C."
}
] | [
{
"body": "<p><strong>Global Variables</strong></p>\n\n<p>Most of the variables are declared globally, they are not used globally. The general rule to declaring variables is to declare them as you need them and limit the scope of the variable. The reason for this is that it makes the code easier to read and much easier to code and debug. This program is already passing variables as parameters so there really is no need for global variables. The variable <code>NumCorrect</code> should be passed by reference into the function <code>CheckAnswer</code>.</p>\n\n<p>An example, the variables <code>ThreeDigNum</code> and <code>TwoDigNum</code> should be declared in the for loop currently in main:</p>\n\n<pre><code> for (int i = 0; i<TotalProbs ;i++)\n {\n int ThreeDigNum = (rand() % 999);\n int TwoDigNum = (rand() % 99) + 1;\n\n ...\n }\n</code></pre>\n\n<p>This might solve your problem with random numbers.</p>\n\n<p><strong>DRY Code</strong> </p>\n\n<p>One software development principle is <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself principle</a>.</p>\n\n<p>There is a number of places in the program where code is repeated. In switch statement in the main for loop 3 function calls are repeated 4 times. A variation of the switch statement itself is repeated within one of the function calls. It might be better if the switch statement in the main for loop was removed and have the function <code>FindAns</code> call <code>AddProbScript</code>, <code>SubProbScript</code>, <code>MultProbScript</code> or <code>DivProbScript</code>.</p>\n\n<pre><code> for (int i = 0; i<TotalProbs ;i++)\n {\n int ThreeDigNum = (rand() % 999);\n int TwoDigNum = (rand() % 99) + 1;\n printf(\"\\nEnter what operation you want to practice (+,-,x,/):\");\n char C = getch();\n printf(\"%c\\n\", C);\n\n Answer = FindAns(C, TwoDigNum, ThreeDigNum);\n MakeAnswers(Answer);\n CheckAnswer(AnswerLoc, &NumCorrect);\n }\n</code></pre>\n\n<p>This would help reduce the complexity of main as well.</p>\n\n<p><strong>Reduce Complexity</strong> </p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">The Single Responsibility Principle</a> states that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class (in this case function).</p>\n\n<p>The function main is overly complex. As your C programs get larger the function main should just be a controller that loads the program, calls a function to execute the program and cleans up when the program is complete. The function main currently contains code that should be in at least 2 sub functions. One function might be RunQuiz(int TotalProbs) and the other function might be DoStatistics(time start, time end, int NumCorrect, int TotalProbs).</p>\n\n<p><strong>Use Standard Constants to Make the Code More Readable</strong></p>\n\n<p>The code already includes the stdlib.h header file, rather than using <code>exit(0);</code> it might be better to use <code>exit(EXIT_SUCCESS);</code> or <code>exit(EXIT_FAILURE);</code>. These are more portable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T13:26:20.837",
"Id": "216781",
"ParentId": "216725",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216781",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T14:39:42.140",
"Id": "216725",
"Score": "1",
"Tags": [
"c",
"quiz"
],
"Title": "Multiple Choice Four-Function Math Game"
} | 216725 |
<p>As part of an insurance claims system we have created, the claims managers can log incoming telephone calls relating to a claim. </p>
<p>The claims manager must validate the caller by asking a number of 'Data Protection' questions that are generated dynamically from information stored against the claim in a database. I believe this type of security is known as 'knowledge-based authentication'.</p>
<p><strong>Notes about Data Protection Questions:</strong></p>
<ul>
<li>Some questions are mandatory and some are not. </li>
<li>All mandatory questions must be answered in order to validate the caller. </li>
<li>At least one non-mandatory question must be answered in order to validate the
caller. </li>
<li>Additional non-mandatory questions can remain unanswered. </li>
<li>Each question may have multiple correct answers.</li>
</ul>
<p>Below are before and after screen shots of the Data Protection part of the Add Call view:</p>
<p><a href="https://i.stack.imgur.com/7tg9Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7tg9Q.png" alt="Before Data Protection has been validated"></a></p>
<p><a href="https://i.stack.imgur.com/I0VWi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/I0VWi.png" alt="After Data Protection has been validated"></a></p>
<p>The current system was written five years ago and we did not attempt to use any design patterns or modern approaches (such as Domain-Driven Design) because we lacked the time and understanding.</p>
<p>We now have the opportunity to re-write this software and would like to follow a Domain-driven approach.</p>
<p><strong>First draft of a DataProtectionQuestion entity class:</strong></p>
<pre><code>public class DataProtectionQuestion
{
public string Question { get; set; }
public IEnumerable<string> Answers { get; set; }
public bool IsRequired { get; set; }
public string Answer { get; set; }
public bool IsAnswered => !string.IsNullOrWhiteSpace(Answer);
public bool AnswerIsCorrect => Answers?.Contains(Answer) ?? false;
}
</code></pre>
<p><strong>Questions that arose from this design:</strong></p>
<ul>
<li>Is this an anaemic model? </li>
<li>Is the DataProtectionQuestion entity the 'right' place to validate the answer?</li>
<li>Should the entity have methods like 'SetAnswer' or 'SetAnswerIsValid'? </li>
<li>Should the setters be private and should clients supply data through a constructor? </li>
<li>Should an Answer be an entity in its own right with a property for 'IsValid'?</li>
<li>How do I display answers in the UI to include 'Unanswered' and 'Incorrect Answer'? (I realise the UI is not the concern of the Domain, but having the ability to choose these as answers is)</li>
</ul>
<p><strong>Second draft (in an attempt to answer some of the above):</strong></p>
<pre><code>public class DataProtectionAnswer
{
public DataProtectionAnswer(string answer, bool isValid)
{
Answer = answer;
IsValid = isValid;
}
public string Answer { get; private set; }
public bool IsValid { get; private set; }
}
public class DataProtectionQuestion
{
public DataProtectionQuestion(string question, bool isRequired, IEnumerable<DataProtectionAnswer> answers)
{
// validate non-null parameters?
Question = question;
IsRequired = isRequired;
Answers = answers;
}
public string Question { get; private set; }
public bool IsRequired { get; private set; }
public IEnumerable<DataProtectionAnswer> Answers { get; private set; }
public DataProtectionAnswer SelectedAnswer { get; private set; }
public bool IsAnswered => SelectedAnswer != null;
public bool AnswerIsCorrect => SelectedAnswer?.IsValid ?? false;
public void SetSelectedAnswer(DataProtectionAnswer answer)
{
// Should validate that answer is not null and contained in Answers?
SelectedAnswer = answer;
}
}
</code></pre>
<p><strong>Some answers..leading to more questions?:</strong></p>
<ul>
<li>Q. Should the entity have methods like 'SetAnswer' or
'SetAnswerIsValid'? </li>
<li>A. I have added a 'SetSelectedAnswer' method but I still don't know if this 'feels' right?</li>
<li>Q. Should the setters be private and should clients supply data through a constructor? </li>
<li>A. I don't know but that's what I've done in draft 2.</li>
<li>Q. Should an Answer be an entity in its own right with a property for 'IsValid'?</li>
<li>A. As per previous question, this is what I've done but should I have?</li>
<li>Q. How do I display answers in the UI to include 'Unanswered' and 'Incorrect Answer'?</li>
<li>A. I can now do this by adding an 'Unanswered' and 'Incorrect Answer' DataProtectionAnswer to the DataProtectionQuestion, but this
'feels' wrong. Isn't this the responsibility of the Presenter?</li>
</ul>
<p>As you can probably tell, I'm floundering and really struggling to get my head around how to model this scenario using a DDD approach. Perhaps DDD isn't right for this situation. I don't know and I feel very stupid right now!</p>
<p>Can anyone please offer some guidance / suggestions on a way forward / better approach?</p>
| [] | [
{
"body": "<p>To start with, you're not doing DDD here.</p>\n\n<p>DDD (Domain-Driven Design / Development) is based around the idea that we <em>start with</em> the domain. We don't touch code yet—we develop the domain models <em>on-paper</em> (or whiteboard, whatever is preferred). Once that is done, we build the code <em>as closely to the domain</em> as possible. The point of DDD is that the code should <em>mirror</em> the domain design.</p>\n\n<p>Before we get going, I <em>highly, highly, <strong>highly</strong></em> recommend this book, by Scott Wlaschin, a prominent F# developer who brings DDD into a <em>very</em> easy-to-understand view (the examples are F#, but they apply to C# as well): <a href=\"https://pragprog.com/book/swdddf/domain-modeling-made-functional\" rel=\"nofollow noreferrer\">Domain Modeling made Functional</a></p>\n\n<p>DDD is about:</p>\n\n<ol>\n<li><p><strong>Define the domain, the inputs, and the outputs.</strong> That is, as a user of the system, what does the domain <em>need</em> to do. Here it sounds like we have <em>part</em> of the domain defined:</p>\n\n<blockquote>\n <p>As part of an insurance claims system we have created, the claims managers can log incoming telephone calls relating to a claim.</p>\n \n <p>The claims manager must validate the caller by asking a number of 'Data Protection' questions that are generated dynamically from information stored against the claim in a database. I believe this type of security is known as 'knowledge-based authentication'.</p>\n \n <p><strong>Notes about Data Protection Questions:</strong></p>\n \n <ul>\n <li>Some questions are mandatory and some are not.</li>\n <li>All mandatory questions must be answered in order to validate the caller.</li>\n <li>At least one non-mandatory question must be answered in order to validate the \n caller.</li>\n <li>Additional non-mandatory questions can remain unanswered.</li>\n <li>Each question may have multiple correct answers.</li>\n </ul>\n</blockquote></li>\n<li><p><strong>From there, we define our types.</strong> Generally, I do DDD with F#, but it's just as applicable to C#. We model the <em>physical</em> domain, so here we're not modeling the <em>questions</em>, we're modeling the <em>validation</em>. That is: the user must answer various questions and prove they are <strong>knowledgeable on the claim.</strong></p>\n\n<p>This is the root of our domain model: we need to <em>validate</em> some information. You have mixed multiple pieces here, so we're going to separate them a bit.</p></li>\n<li><p><strong>After building the types, we build the work.</strong> That is, the functions. We build the types as <em>just</em> data-structures, then we build the functions next to encapsulate the <em>domain rules</em>.</p></li>\n</ol>\n\n<p>So, you've defined the domain (at least, as far as I see it) via the quoted-blurb, so what I want to do is move that into some types.</p>\n\n<p>To start with, we'll define a <code>DataProtectionResponse</code> (we're going to use the <em>exact</em> language from the domain model, the purpose of DDD is to translate the human-language into code).</p>\n\n<pre><code>class DataProtectionResponse {\n public DataProtectionQuestion Question { get; set; }\n public IEnumerable<ValidQuestionAnswer> ValidQuestionAnswers { get; set; }\n public Response Response { get; set; }\n}\n</code></pre>\n\n<p>Now, we need to come up with a model for <code>DataProtectionQuestion</code>:</p>\n\n<pre><code>class DataProtectionQuestion {\n public string Question { get; set; }\n public bool Required { get; set; }\n}\n</code></pre>\n\n<p>As you see, we are ONLY modeling two components of the question: the actual question, and whether or not it's required. The questions <em>themselves</em> are a different part of the domain, they're generated <em>as a question</em>, and using this is how we get into building a flexible model. We can now take these <em>same questions</em> somewhere else, and use them as a whole other tool, assuming it needs to interact with our <em>current</em> domain.</p>\n\n<p>Next, we have <code>ValidQuestionAnswer</code>. This is going to be the answer that are valid for <em>this</em> particular claim:</p>\n\n<pre><code>class ValidQuestionAnswer {\n public Response Response { get; set; }\n}\n</code></pre>\n\n<p>We made this a class as we <em>absolutely</em> want to consider a situation where an answer might have more data to it.</p>\n\n<p>Finally, the <code>Response</code>. You might say, \"Der Kommissar, why does that need to be a class, it's always a string?\" Again, we <em>might</em> need to add more to this model, including functionality, so we do that by using a class.</p>\n\n<pre><code>class Response {\n public string Value { get; set; }\n}\n</code></pre>\n\n<p>So now, our domain will consume an <code>IEnumerable<DataProtectionResponse></code>, but <em>not</em> directly.</p>\n\n<pre><code>class DataProtection {\n public IEnumerable<DataProtectionResponse> Questions { get; set; }\n}\n</code></pre>\n\n<p>Why another class? Well, let's start talking functionality.</p>\n\n<p>First and foremost, the primary component of our design is that <code>DataProtection</code> <em>must</em> validate. For this to work, we need a <code>IsValid</code> function or property there:</p>\n\n<pre><code>public bool IsValid => Questions.All(x => x.IsSufficient);\n</code></pre>\n\n<p>Alright, so we have some concepts now. We have a <code>IsValid</code> that indicates if our <code>DataProtection</code> is valid or not, and we have decided that <em>all</em> of the questions must be sufficiently answered.</p>\n\n<p>Next, we need to prove that a question is sufficiently answered.</p>\n\n<pre><code>public bool IsSufficient => ValidQuestionAnswers.Any(x => x.Acceptable(Question, Response));\n</code></pre>\n\n<p>Again, we are going to encode our actual logic: this <code>DataProtectionResponse</code> is sufficient if <em>any</em> of the <code>ValidQuestionAnswers</code> are acceptable with the question and response.</p>\n\n<p>Next, how do we prove they're acceptable?</p>\n\n<p>Well, the first rule is that if it's not required and there is no response, then it's valid:</p>\n\n<pre><code>if (!question.Required && response?.IsEmpty ?? false == false)\n{\n return true;\n}\n</code></pre>\n\n<p>And of course, <code>Response.IsEmpty</code>:</p>\n\n<pre><code>public bool IsEmpty => String.IsNullOrWhiteSpace(Value);\n</code></pre>\n\n<p>Otherwise, we want to prove that this response and the provided response are acceptable:</p>\n\n<pre><code>return response.Satisfies(Response);\n</code></pre>\n\n<p>And this is why we made it a class right-off-the-bat: we might have more logic that goes into <code>Satisfies</code> that might do heuristic analysis. I.e. if you provide an address, the logic might say <code>123 Main St.</code> and <code>123 Main St</code> and <code>123 Main Street</code> are all the same.</p>\n\n<pre><code>public bool Acceptable(DataProtectionQuestion question, Response response)\n{\n if (!question.Required && response?.IsEmpty ?? true)\n {\n return true;\n }\n\n return response.Satisfies(Response);\n}\n</code></pre>\n\n<p>Next, our <code>Response.Satisfies</code>:</p>\n\n<pre><code>public bool Satisfies(Response response) => Value == response.Value;\n</code></pre>\n\n<p>And viola, we're done. We've encoded the entire domain, concisely, and using the <em>actual terms</em> the domain considers. Only 37 lines of code:</p>\n\n<pre><code>class Response\n{\n public string Value { get; set; }\n public bool IsEmpty => String.IsNullOrWhiteSpace(Value);\n\n public bool Satisfies(Response response) => Value == response.Value;\n}\nclass ValidQuestionAnswer\n{\n public Response Response { get; set; }\n\n public bool Acceptable(DataProtectionQuestion question, Response response)\n {\n if (!question.Required && response?.IsEmpty ?? true)\n {\n return true;\n }\n\n return response.Satisfies(Response);\n }\n}\nclass DataProtectionQuestion\n{\n public string Question { get; set; }\n public bool Required { get; set; }\n}\nclass DataProtectionResponse\n{\n public DataProtectionQuestion Question { get; set; }\n public IEnumerable<ValidQuestionAnswer> ValidQuestionAnswers { get; set; }\n public Response Response { get; set; }\n public bool IsSufficient => ValidQuestionAnswers.Any(x => x.Acceptable(Question, Response));\n}\nclass DataProtection\n{\n public IEnumerable<DataProtectionResponse> Questions { get; set; }\n public bool IsValid => Questions.All(x => x.IsSufficient);\n}\n</code></pre>\n\n<p>We don't have any odd logic, we don't have any conflated values: each model concerns itself with it's own work, no one else's.</p>\n\n<p>Additionally, when our domain changes now (or we have to change the satisfaction logic) we have built the flexibility in-place without needing major infrastructure rewrites. If we need to override a response, we encode that in <code>DataProtectionResponse</code> and modify <code>IsSufficient</code>.</p>\n\n<p>Finally, you could even shorten <code>Acceptable</code> to a single statement, since the logic is relatively straightforward:</p>\n\n<pre><code>class Response\n{\n public string Value { get; set; }\n public bool IsEmpty => String.IsNullOrWhiteSpace(Value);\n\n public bool Satisfies(Response response) => Value == response.Value;\n}\nclass ValidQuestionAnswer\n{\n public Response Response { get; set; }\n\n public bool Acceptable(DataProtectionQuestion question, Response response) =>\n (!question.Required && response?.IsEmpty ?? true) || response.Satisfies(Response);\n}\nclass DataProtectionQuestion\n{\n public string Question { get; set; }\n public bool Required { get; set; }\n}\nclass DataProtectionResponse\n{\n public DataProtectionQuestion Question { get; set; }\n public IEnumerable<ValidQuestionAnswer> ValidQuestionAnswers { get; set; }\n public Response Response { get; set; }\n public bool IsSufficient => ValidQuestionAnswers.Any(x => x.Acceptable(Question, Response));\n}\nclass DataProtection\n{\n public IEnumerable<DataProtectionResponse> Questions { get; set; }\n public bool IsValid => Questions.All(x => x.IsSufficient);\n}\n</code></pre>\n\n<hr>\n\n<p>You noted in the comments that I missed the requirement of <em>at least one</em> optional question, and you're absolutely right. So let's talk about another strength of DDD: verifying our code matches the domain.</p>\n\n<blockquote>\n <p>At least one non-mandatory question must be answered in order to validate the caller.</p>\n</blockquote>\n\n<p>So, looking through our code we see that we can start with <code>DataProtection.IsValid</code>:</p>\n\n<pre><code>public bool IsValid => Questions.All(x => x.IsSufficient);\n</code></pre>\n\n<p>Aha, we already know our problem is here. We make sure all questions are sufficient, but that does not take <em>at least one</em> optional into account. So how do we fix that?</p>\n\n<p>Well, to start, we'll modify <code>IsValid</code> to support some theoretical work:</p>\n\n<pre><code>public bool IsValid => Questions.All(x => x.IsSufficient) && Questions.Where(x => !x.IsRequired).Any(x => x.IsAnswered);\n</code></pre>\n\n<p>Here, we've decided that if each <code>DataProtectionResponse</code> tells us if it's required or not, and if it's answered or not, we can prove that we have <em>at least one</em> non-required question answered.</p>\n\n<p>Next, we need to implement those two items. Both are trivial, and actually help with our other code:</p>\n\n<pre><code>public bool IsRequired => Question.Required;\npublic bool IsAnswered => ValidQuestionAnswers.Any(x => x.AnsweredBy(Response));\n</code></pre>\n\n<p>Now we have another method to implement: <code>ValidQuestionAnswer.AnsweredBy(Response)</code>:</p>\n\n<pre><code>public bool AnsweredBy(Response response) => response.Satisfies(Response);\n</code></pre>\n\n<p>You'll notice we've repeated one bit of code: <code>response.Satisfies(Response)</code> is in both <code>AnsweredBy</code>, and <code>Acceptable</code>, let's change that:</p>\n\n<pre><code>public bool Acceptable(DataProtectionQuestion question, Response response) =>\n (!question.Required && response?.IsEmpty ?? true) || AnsweredBy(Response);\n</code></pre>\n\n<p>Once again, our contract is now satisfied, and we ONLY go at-most one-level-deep in each model from a parent model. (That is, we could have done <code>!x.Question.Required</code> instead of <code>!x.IsRequired</code>, but it's not the responsibility of <code>DataProtection</code> to know what makes a response required or not.)</p>\n\n<p>So, 36 lines of code to build our new requirements:</p>\n\n<pre><code>class Response\n{\n public string Value { get; set; }\n public bool IsEmpty => String.IsNullOrWhiteSpace(Value);\n\n public bool Satisfies(Response response) => Value == response.Value;\n}\nclass ValidQuestionAnswer\n{\n public Response Response { get; set; }\n\n public bool AnsweredBy(Response response) => response.Satisfies(Response);\n\n public bool Acceptable(DataProtectionQuestion question, Response response) =>\n (!question.Required && response?.IsEmpty ?? true) || AnsweredBy(Response);\n}\nclass DataProtectionQuestion\n{\n public string Question { get; set; }\n public bool Required { get; set; }\n}\nclass DataProtectionResponse\n{\n public DataProtectionQuestion Question { get; set; }\n public IEnumerable<ValidQuestionAnswer> ValidQuestionAnswers { get; set; }\n public Response Response { get; set; }\n\n public bool IsRequired => Question.Required;\n public bool IsAnswered => ValidQuestionAnswers.Any(x => x.AnsweredBy(Response));\n public bool IsSufficient => ValidQuestionAnswers.Any(x => x.Acceptable(Question, Response));\n}\nclass DataProtection\n{\n public IEnumerable<DataProtectionResponse> Questions { get; set; }\n public bool IsValid => Questions.All(x => x.IsSufficient) && Questions.Where(x => !x.IsRequired).Any(x => x.IsAnswered);\n}\n</code></pre>\n\n<hr>\n\n<p>Finally, you asked a few questions about your implementation: as you see, I ignored them, <em>purposefully</em>. With DDD, those questions are not things to ask about the <em>implementation</em> but things to ask about the <em>domain</em>. With DDD we do iterations of \"design\", \"implement\", \"design\", \"implement\"—all the questions you have should go in the <em>design</em> stage, which is where you (and the other domain experts) gather and hash-out the principles of the project. This means, now that you have an implementation, we go back to design and clarify those questions. As the developer, when you see these things you should be creating a working list of potential problem-points, you might find out the domain-experts have considered them, or they may not, so you take your concerns back to them and <em>refine</em> the design. (Again, DDD is an iterative concept.)</p>\n\n<p><em>But</em>, suppose I were to answer them:</p>\n\n<blockquote>\n <p>Should the entity have methods like 'SetAnswer' or 'SetAnswerIsValid'?</p>\n</blockquote>\n\n<p><strong>A</strong>: That's actually a design question, do you <em>need</em> to override whether an answer is valid or not? (I briefly touched on that in the first part of the answer.)</p>\n\n<blockquote>\n <p>Should the setters be private and should clients supply data through a constructor?</p>\n</blockquote>\n\n<p><strong>A</strong>: This <em>seems</em> like an implementation question at first glance, but if we reword it things are different: <em>can a client change an answer</em>? If the answer is yes, the proposed design is fine. If not, model for immutability.</p>\n\n<blockquote>\n <p>Should an Answer be an entity in its own right with a property for 'IsValid'?</p>\n</blockquote>\n\n<p><strong>A</strong>: In my humble opinion, <em>yes</em>. Answers aren't a string, they're a <em>concept</em>. Additionally, with a base-class, you can override that for answers that are <code>bool</code>, <code>DateTime</code>, etc. But, again: take it back to the DDD drawing board. The domain model will tell you what needs done.</p>\n\n<blockquote>\n <p>How do I display answers in the UI to include 'Unanswered' and 'Incorrect Answer'?</p>\n</blockquote>\n\n<p><strong>A</strong>: That's a design question, but my suggestion is to ditch the <code>Valid</code> checkbox and provide a red/green \"Needs Answered\", \"Incorrect Answer\", or \"Correct Answer\" state. Again, do what the <em>domain</em> calls for. You're mixing some concerns here, and with DDD we create a clear separation. When you have a question <em>like this</em>, we go <em>back</em> into the design stage and hash it out. (It might turn out that you <strong>must not</strong> indicate if an answer is incorrect. Compliance laws are weird.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T08:27:43.330",
"Id": "419313",
"Score": "0",
"body": "Thank you for taking the time to write such a comprehensive response. It is much appreciated. You're absolutely right when you say I'm mixing concerns. I am struggling to get my mindset away from data-driven towards domain-drive design. Your suggested approach to DDD has given me much needed food for thought. One thing I mentioned in my original post that I don't think your answer covers: \"At least one non-mandatory question must be answered in order to validate the caller.\" I believe the code you have suggested allows for all non-mandatory questions to be left unanswered?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T13:24:50.157",
"Id": "419342",
"Score": "0",
"body": "@datahandler I just edited the answer to address that (I did not change the existing answer, but instead showed how we would validate that the model we built conforms to the DDD specification). Hopefully all of this helps you figure out where you can modify the process to do DDD a little more effectively. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T16:19:54.600",
"Id": "216731",
"ParentId": "216727",
"Score": "19"
}
}
] | {
"AcceptedAnswerId": "216731",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:19:10.907",
"Id": "216727",
"Score": "15",
"Tags": [
"c#",
"ddd"
],
"Title": "Knowledge-based authentication using Domain-driven Design in C#"
} | 216727 |
<p>I implemented a Hangman/guess the word clone in Python. This is my first attempt at making an actual interactive app instead of just a list of functions or a static program. It is also the first time I try to actually implement classes since I've been having a hard time wrapping my head around them. It's probably not the best or most practical application for a class, but it saved me the trouble of having to go around declaring globals and nonlocals throughout the code.</p>
<pre><code>import json
import random
from os import system, name
import msvcrt
import colorama
class Hangman:
def __init__(self):
self.level = ""
self.word = ""
self.wrong_chars = []
self.from_victory = 0
self.from_defeat = 0
self.game_state = ""
self.on_repeat = True
@staticmethod
def cls():
system('cls' if name == 'nt' else 'clear')
def difficulty_scene(self):
print("""
DIFFICULTY LEVEL:
------------------
(1) Very easy.
Very long words (10+ characters) and 10 lives
(2) Easy.
Long words (8 or 9 characters) and 8 lives
(3) Standard.
Medium words (6 or 7 characters) and 6 lives
(4) Hard.
Short words (4 or 5 characters) and 4 lives
(5) Impossible.
Tiny words (3 characters) and 3 lives.
""")
self.level = input(" Select difficulty (1-5): ")
def game_prep(self):
self.word = word_list[-int(self.level) + 5][int(random.random()
* len(word_list))]
self.wrong_chars = []
self.from_victory = len(self.word)
self.from_defeat = self.make_from_defeat()
self.game_state = ""
def make_from_defeat(self):
return {
"1": 10,
"2": 8,
"3": 6,
"4": 4,
"5": 3
}.get(self.level, 6)
def main_scene(self):
colorama.init()
print(f"\n {'_' * len(self.word)}")
while True:
char = msvcrt.getch().decode('UTF-8')
if char in self.word:
for i in range(len(self.word)):
if char == self.word[i]:
print(f'\x1b[2;{i+3}H', end="")
print(char, end="")
self.from_victory -= 1
else:
self.wrong_chars.append(char)
print(f'\x1b[4;{((len(self.wrong_chars) - 1) * 2) + 3}H', end="")
print(char, end="")
self.from_defeat -= 1
if self.from_victory == 0 or self.from_defeat == 0:
break
def end_scene(self):
if self.from_victory == 0:
print("\n YOU HAVE WON")
elif self.from_defeat == 0:
print("\n YOU HAVE LOST")
print(f" your word was {self.word}")
repeat = input("\n Try again? (y/n):\n ")
if repeat == "y":
self.on_repeat = True
else:
self.on_repeat = False
def main(self):
self.cls()
self.difficulty_scene()
self.cls()
while self.on_repeat:
self.game_prep()
self.main_scene()
self.cls()
self.end_scene()
self.cls()
game = Hangman()
if __name__ == '__main__':
with open("words.json", "r") as read_file:
word_list = json.load(read_file)
game.main()
</code></pre>
<p><code>words.json</code> is a 2-dimensional array of words sorted by length.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T16:33:28.853",
"Id": "419756",
"Score": "0",
"body": "@Jamal Hey, I'm still new to Code Review, was there a point to editing the formatting of the code? why is one method preferred over the other?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T02:56:32.930",
"Id": "419804",
"Score": "1",
"body": "Not entirely, but I usually revert it to indented (the way it used to be) if there's something else to edit. It at least helps the code stand out from the text in the editor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T07:11:08.787",
"Id": "419834",
"Score": "0",
"body": "Gotcha, thanks for the fixes"
}
] | [
{
"body": "<ul>\n<li><strong>Docstrings</strong>: You should include a <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>docstring</code></a> at the beginning of every method, class, and module you write. This will help any documentation identify what your code is supposed to do.</li>\n<li><strong>Simplified boolean comparisons</strong>: </li>\n</ul>\n\n<p>You have code like:</p>\n\n<pre><code>if repeat == \"y\":\n self.on_repeat = True\nelse:\n self.on_repeat = False\n</code></pre>\n\n<p>Instead of having an <code>if/else</code> and setting the boolean condition based on that, you can simply set the value of <code>self.on_repeat</code> based off the first check, like so:</p>\n\n<pre><code>self.on_repeat = repeat == \"y\"\n</code></pre>\n\n<ul>\n<li><strong>Meaningful method names</strong>: Method names should be based off what the code inside them does. While some of your methods do (<code>main_scene</code>, <code>end_scene</code>), some of them do not. <code>make_from_defeat</code> for example. I had no clue what the same was trying to suggest about the method, and it doesn't seem to correlate to what the method does. I left them unchanged so you could figure out for yourself what those method names should be.</li>\n<li><strong>Constant Variable Naming</strong>: All constant variables in your program should be UPPERCASE, to distinct them from non-constants and make it clear to you/a reviewer that they are constants.</li>\n</ul>\n\n<p><strong><em>Updated Code</em></strong></p>\n\n<pre><code>\"\"\"\nModule Doctring:\nA description of your program goes here\n\"\"\"\nimport json\nimport random\nfrom os import system, name\nimport msvcrt\nimport colorama\n\nclass Hangman:\n \"\"\"\n Class for storing properties of the object `Hangman`\n \"\"\"\n def __init__(self):\n self.level = \"\"\n self.word = \"\"\n self.wrong_chars = []\n self.from_victory = 0\n self.from_defeat = 0\n self.game_state = \"\"\n self.on_repeat = True\n\n @staticmethod\n def cls():\n \"\"\" Clears the console \"\"\"\n system('cls' if name == 'nt' else 'clear')\n\n def difficulty_scene(self):\n \"\"\" Prints the difficulty options \"\"\"\n print(\"\"\"\n DIFFICULTY LEVEL:\n ------------------\n\n (1) Very easy.\n Very long words (10+ characters) and 10 lives\n\n (2) Easy.\n Long words (8 or 9 characters) and 8 lives\n\n (3) Standard.\n Medium words (6 or 7 characters) and 6 lives\n\n (4) Hard.\n Short words (4 or 5 characters) and 4 lives\n\n (5) Impossible.\n Tiny words (3 characters) and 3 lives.\n\n \"\"\")\n self.level = input(\" Select difficulty (1-5): \")\n\n def game_prep(self):\n \"\"\" Prepares the game \"\"\"\n self.word = WORD_LIST[-int(self.level) + 5][int(random.random()\n * len(WORD_LIST))]\n self.wrong_chars = []\n self.from_victory = len(self.word)\n self.from_defeat = self.make_from_defeat()\n self.game_state = \"\"\n\n def make_from_defeat(self):\n \"\"\" Retuns the length of the word to guess \"\"\"\n return {\n \"1\": 10,\n \"2\": 8,\n \"3\": 6,\n \"4\": 4,\n \"5\": 3\n }.get(self.level, 6)\n\n def main_scene(self):\n \"\"\" Determines if letter is inside word \"\"\"\n colorama.init()\n\n print(f\"\\n {'_' * len(self.word)}\")\n\n while True:\n char = msvcrt.getch().decode('UTF-8')\n if char in self.word:\n for i in range(len(self.word)):\n if char == self.word[i]:\n print(f'\\x1b[2;{i+3}H', end=\"\")\n print(char, end=\"\")\n self.from_victory -= 1\n else:\n self.wrong_chars.append(char)\n print(f'\\x1b[4;{((len(self.wrong_chars) - 1) * 2) + 3}H', end=\"\")\n print(char, end=\"\")\n self.from_defeat -= 1\n if self.from_victory == 0 or self.from_defeat == 0:\n break\n\n def end_scene(self):\n \"\"\" Determines if the player has won or list \"\"\"\n if self.from_victory == 0:\n print(\"\\n YOU HAVE WON\")\n elif self.from_defeat == 0:\n print(\"\\n YOU HAVE LOST\")\n print(f\" your word was {self.word}\")\n repeat = input(\"\\n Try again? (y/n):\\n \")\n self.on_repeat = repeat == \"y\"\n\n def run(self):\n \"\"\" Runs the game \"\"\"\n self.cls()\n self.difficulty_scene()\n self.cls()\n while self.on_repeat:\n self.game_prep()\n self.main_scene()\n self.cls()\n self.end_scene()\n self.cls()\n\nif __name__ == '__main__':\n\n GAME = Hangman()\n\n with open(\"words.json\", \"r\") as read_file:\n WORD_LIST = json.load(read_file)\n\n GAME.run()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-05T02:48:18.073",
"Id": "225555",
"ParentId": "216735",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T17:27:50.790",
"Id": "216735",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"hangman"
],
"Title": "Python Hangman (guess the word) game"
} | 216735 |
<p>Generate a linked list of any type using macros. The linked list contains functions for adding and removing elements to both ends and also at the middle. You can also add elements relatively to a list node. It also comes with an iterator that can go back and forwards through the list.</p>
<p>Macros that generate a linked list:</p>
<ul>
<li><code>LINKEDLIST_GENERATE</code> - Generate a linked list in a single file</li>
</ul>
<p>If you want to generate the linked list in a separate source file and have a header to access its functions you have two options:</p>
<ul>
<li>PUBLIC (have access to the struct internals)
<ul>
<li><code>LINKEDLIST_GENERATE_HEADER_PUBLIC</code> - Generate header</li>
<li><code>LINKEDLIST_GENERATE_SOURCE_PUBLIC</code> - Generate source</li>
<li>This way the user will have full access to all functions and members of a struct</li>
</ul></li>
<li>PRIVATE (no access to the struct internals)
<ul>
<li><code>LINKEDLIST_GENERATE_HEADER_PRIVATE</code> - Generate header</li>
<li><code>LINKEDLIST_GENERATE_SOURCE_PRIVATE</code> - Generate source</li>
<li>This way the user won't have access to the struct internals an functions that are part of the linked list implementation.</li>
</ul></li>
</ul>
<p>The above macros (except for <code>LINKEDLIST_GENERATE</code>) are made to interface with one of my <a href="https://codereview.stackexchange.com/questions/213553/simple-generic-macro-generated-containers">previous question</a> that didn't get much attention, but it is part of the same collections library.</p>
<p><strong>macro_collections.h</strong></p>
<pre><code>#ifndef CMC_MACRO_COLLECTIONS
#define CMC_MACRO_COLLECTIONS
#include <stdlib.h>
#include <stdbool.h>
#define CONCATH_(C, P) C##_GENERATE_HEADER##_##P
#define CONCATC_(C, P) C##_GENERATE_SOURCE##_##P
#define CONCATH(C, P) CONCATH_(C, P)
#define CONCATC(C, P) CONCATC_(C, P)
#define COLLECTION_GENERATE(C, P, PFX, SNAME, FMOD, K, V) \
COLLECTION_GENERATE_HEADER(C, P, PFX, SNAME, FMOD, K, V) \
COLLECTION_GENERATE_SOURCE(C, P, PFX, SNAME, FMOD, K, V)
#define COLLECTION_GENERATE_HEADER(C, P, PFX, SNAME, FMOD, K, V) \
CONCATH(C, P) \
(PFX, SNAME, FMOD, K, V)
#define COLLECTION_GENERATE_SOURCE(C, P, PFX, SNAME, FMOD, K, V) \
CONCATC(C, P) \
(PFX, SNAME, FMOD, K, V)
#endif /* CMC_MACRO_COLLECTIONS */
</code></pre>
<ul>
<li><strong>C</strong> - The container you want (the uppercase name, e.g., LINKEDLIST);</li>
<li><strong>P</strong> - If you want your data structure's fields visible;</li>
<li><strong>PFX</strong> - Functions prefix, or namespace;</li>
<li><strong>SNAME</strong> - Structure name (<code>typedef SNAME##_s SNAME;</code>);</li>
<li><strong>FMOD</strong> - Functions modifier (<code>static</code> or empty);</li>
<li><strong>K</strong> - Used by associative containers (leave empty for LINKEDLIST);</li>
<li><strong>V</strong> - Your data type to be worked with.</li>
</ul>
<p><strong>linkedlist.h</strong></p>
<pre><code>#ifndef CMC_LINKEDLIST_H
#define CMC_LINKEDLIST_H
#include <stdlib.h>
#include <stdbool.h>
#define LINKEDLIST_GENERATE(PFX, SNAME, FMOD, V) \
LINKEDLIST_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
LINKEDLIST_GENERATE_HEADER(PFX, SNAME, FMOD, V) \
LINKEDLIST_GENERATE_SOURCE(PFX, SNAME, FMOD, V)
/* PRIVATE *******************************************************************/
#define LINKEDLIST_GENERATE_HEADER_PRIVATE(PFX, SNAME, FMOD, K, V) \
LINKEDLIST_GENERATE_HEADER(PFX, SNAME, FMOD, V)
#define LINKEDLIST_GENERATE_SOURCE_PRIVATE(PFX, SNAME, FMOD, K, V) \
LINKEDLIST_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
LINKEDLIST_GENERATE_SOURCE(PFX, SNAME, FMOD, V)
/* PUBLIC ********************************************************************/
#define LINKEDLIST_GENERATE_HEADER_PUBLIC(PFX, SNAME, FMOD, K, V) \
LINKEDLIST_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
LINKEDLIST_GENERATE_HEADER(PFX, SNAME, FMOD, V)
#define LINKEDLIST_GENERATE_SOURCE_PUBLIC(PFX, SNAME, FMOD, K, V) \
LINKEDLIST_GENERATE_SOURCE(PFX, SNAME, FMOD, V)
/* STRUCT ********************************************************************/
#define LINKEDLIST_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
\
struct SNAME##_s \
{ \
struct SNAME##_node_s *head; \
struct SNAME##_node_s *tail; \
size_t count; \
}; \
\
struct SNAME##_node_s \
{ \
V data; \
struct SNAME##_s *owner; \
struct SNAME##_node_s *next; \
struct SNAME##_node_s *prev; \
}; \
\
struct SNAME##_iter_s \
{ \
struct SNAME##_s *target; \
struct SNAME##_node_s *cursor; \
size_t index; \
bool start; \
bool end; \
}; \
\
/* HEADER ********************************************************************/
#define LINKEDLIST_GENERATE_HEADER(PFX, SNAME, FMOD, V) \
\
typedef struct SNAME##_s SNAME; \
typedef struct SNAME##_node_s SNAME##_node; \
typedef struct SNAME##_iter_s SNAME##_iter; \
\
FMOD SNAME *PFX##_new(void); \
FMOD void PFX##_free(SNAME *_list_); \
FMOD bool PFX##_push_front(SNAME *_list_, V element); \
FMOD bool PFX##_push(SNAME *_list_, V element, size_t index); \
FMOD bool PFX##_push_back(SNAME *_list_, V element); \
FMOD bool PFX##_pop_front(SNAME *_list_); \
FMOD bool PFX##_pop(SNAME *_list_, size_t index); \
FMOD bool PFX##_pop_back(SNAME *_list_); \
FMOD bool PFX##_push_if(SNAME *_list_, V element, size_t index, bool condition); \
FMOD bool PFX##_pop_if(SNAME *_list_, size_t index, bool condition); \
FMOD V PFX##_front(SNAME *_list_); \
FMOD V PFX##_get(SNAME *_list_, size_t index); \
FMOD V PFX##_back(SNAME *_list_); \
FMOD bool PFX##_empty(SNAME *_list_); \
FMOD size_t PFX##_count(SNAME *_list_); \
\
FMOD SNAME##_node *PFX##_new_node(SNAME *_owner_, V element); \
FMOD SNAME##_node *PFX##_front_node(SNAME *_list_); \
FMOD SNAME##_node *PFX##_get_node(SNAME *_list_, size_t index); \
FMOD SNAME##_node *PFX##_back_node(SNAME *_list_); \
FMOD bool PFX##_insert_nxt(SNAME##_node *node, V element); \
FMOD bool PFX##_insert_prv(SNAME##_node *node, V element); \
FMOD bool PFX##_remove_nxt(SNAME##_node *node); \
FMOD bool PFX##_remove_cur(SNAME##_node *node); \
FMOD bool PFX##_remove_prv(SNAME##_node *node); \
FMOD SNAME##_node *PFX##_next_node(SNAME##_node *node); \
FMOD SNAME##_node *PFX##_prev_node(SNAME##_node *node); \
\
FMOD void PFX##_iter_new(SNAME##_iter *iter, SNAME *target); \
FMOD bool PFX##_iter_start(SNAME##_iter *iter); \
FMOD bool PFX##_iter_end(SNAME##_iter *iter); \
FMOD void PFX##_iter_tostart(SNAME##_iter *iter); \
FMOD void PFX##_iter_toend(SNAME##_iter *iter); \
FMOD bool PFX##_iter_next(SNAME##_iter *iter, V *result, size_t *index); \
FMOD bool PFX##_iter_prev(SNAME##_iter *iter, V *result, size_t *index); \
\
/* SOURCE ********************************************************************/
#define LINKEDLIST_GENERATE_SOURCE(PFX, SNAME, FMOD, V) \
\
FMOD SNAME *PFX##_new(void) \
{ \
SNAME *_list_ = malloc(sizeof(SNAME)); \
\
if (!_list_) \
return NULL; \
\
_list_->count = 0; \
_list_->head = NULL; \
_list_->tail = NULL; \
\
return _list_; \
} \
\
FMOD void PFX##_free(SNAME *_list_) \
{ \
SNAME##_node *scan = _list_->head; \
while (_list_->head != NULL) \
{ \
_list_->head = _list_->head->next; \
free(scan); \
scan = _list_->head; \
} \
free(_list_); \
} \
\
FMOD bool PFX##_push_front(SNAME *_list_, V element) \
{ \
SNAME##_node *node = PFX##_new_node(_list_, element); \
\
if (!node) \
return false; \
\
if (PFX##_empty(_list_)) \
{ \
_list_->head = node; \
_list_->tail = node; \
} \
else \
{ \
node->next = _list_->head; \
_list_->head->prev = node; \
_list_->head = node; \
} \
\
_list_->count++; \
\
return true; \
} \
\
FMOD bool PFX##_push(SNAME *_list_, V element, size_t index) \
{ \
if (index > _list_->count) \
return false; \
\
if (index == 0) \
{ \
return PFX##_push_front(_list_, element); \
} \
else if (index == _list_->count) \
{ \
return PFX##_push_back(_list_, element); \
} \
\
SNAME##_node *node = PFX##_new_node(_list_, element); \
\
if (!node) \
return false; \
\
SNAME##_node *scan = PFX##_get_node(_list_, index - 1); \
\
node->next = scan->next; \
node->prev = scan; \
node->next->prev = node; \
node->prev->next = node; \
\
_list_->count++; \
\
return true; \
} \
\
FMOD bool PFX##_push_back(SNAME *_list_, V element) \
{ \
SNAME##_node *node = PFX##_new_node(_list_, element); \
\
if (!node) \
return false; \
\
if (PFX##_empty(_list_)) \
{ \
_list_->head = node; \
_list_->tail = node; \
} \
else \
{ \
node->prev = _list_->tail; \
_list_->tail->next = node; \
_list_->tail = node; \
} \
\
_list_->count++; \
\
return true; \
} \
\
FMOD bool PFX##_pop_front(SNAME *_list_) \
{ \
if (PFX##_empty(_list_)) \
return false; \
\
SNAME##_node *node = _list_->head; \
_list_->head = _list_->head->next; \
\
free(node); \
\
if (_list_->head == NULL) \
_list_->tail = NULL; \
else \
_list_->head->prev = NULL; \
\
_list_->count--; \
\
return true; \
} \
\
FMOD bool PFX##_pop(SNAME *_list_, size_t index) \
{ \
if (PFX##_empty(_list_)) \
return false; \
\
if (index >= _list_->count) \
return false; \
\
if (index == 0) \
{ \
return PFX##_pop_front(_list_); \
} \
else if (index == _list_->count - 1) \
{ \
return PFX##_pop_back(_list_); \
} \
\
SNAME##_node *node = PFX##_get_node(_list_, index); \
\
if (!node) \
return false; \
\
node->next->prev = node->prev; \
node->prev->next = node->next; \
\
free(node); \
\
_list_->count--; \
\
return true; \
} \
\
FMOD bool PFX##_pop_back(SNAME *_list_) \
{ \
if (PFX##_empty(_list_)) \
return false; \
\
SNAME##_node *node = _list_->tail; \
_list_->tail = _list_->tail->prev; \
\
free(node); \
\
if (_list_->tail == NULL) \
_list_->head = NULL; \
else \
_list_->tail->next = NULL; \
\
_list_->count--; \
\
return true; \
} \
\
FMOD bool PFX##_push_if(SNAME *_list_, V element, size_t index, bool condition) \
{ \
if (condition) \
return PFX##_push(_list_, element, index); \
\
return false; \
} \
\
FMOD bool PFX##_pop_if(SNAME *_list_, size_t index, bool condition) \
{ \
if (condition) \
return PFX##_pop(_list_, index); \
\
return false; \
} \
\
FMOD V PFX##_front(SNAME *_list_) \
{ \
if (PFX##_empty(_list_)) \
return 0; \
\
return _list_->head->data; \
} \
\
FMOD V PFX##_get(SNAME *_list_, size_t index) \
{ \
if (index >= _list_->count) \
return 0; \
\
if (PFX##_empty(_list_)) \
return 0; \
\
SNAME##_node *scan = PFX##_get_node(_list_, index); \
\
if (scan == NULL) \
return 0; \
\
return scan->data; \
} \
\
FMOD V PFX##_back(SNAME *_list_) \
{ \
if (PFX##_empty(_list_)) \
return 0; \
\
return _list_->tail->data; \
} \
\
FMOD bool PFX##_empty(SNAME *_list_) \
{ \
return _list_->count == 0; \
} \
\
FMOD size_t PFX##_count(SNAME *_list_) \
{ \
return _list_->count; \
} \
\
FMOD SNAME##_node *PFX##_new_node(SNAME *_owner_, V element) \
{ \
SNAME##_node *node = malloc(sizeof(SNAME##_node)); \
\
if (!node) \
return NULL; \
\
node->owner = _owner_; \
node->data = element; \
node->next = NULL; \
node->prev = NULL; \
\
return node; \
} \
\
FMOD SNAME##_node *PFX##_front_node(SNAME *_list_) \
{ \
return _list_->head; \
} \
\
FMOD SNAME##_node *PFX##_get_node(SNAME *_list_, size_t index) \
{ \
if (index >= _list_->count) \
return NULL; \
\
if (PFX##_empty(_list_)) \
return NULL; \
\
SNAME##_node *scan = NULL; \
\
if (index <= _list_->count / 2) \
{ \
scan = _list_->head; \
for (size_t i = 0; i < index; i++) \
{ \
scan = scan->next; \
} \
} \
else \
{ \
scan = _list_->tail; \
for (size_t i = _list_->count - 1; i > index; i--) \
{ \
scan = scan->prev; \
} \
} \
\
return scan; \
} \
\
FMOD SNAME##_node *PFX##_back_node(SNAME *_list_) \
{ \
return _list_->tail; \
} \
\
FMOD bool PFX##_insert_nxt(SNAME##_node *node, V element) \
{ \
SNAME##_node *new_node = PFX##_new_node(node->owner, element); \
\
if (!new_node) \
return false; \
\
new_node->next = node->next; \
if (node->next != NULL) \
node->next->prev = new_node; \
else \
node->owner->tail = new_node; \
\
new_node->prev = node; \
node->next = new_node; \
\
node->owner->count++; \
\
return true; \
} \
\
FMOD bool PFX##_insert_prv(SNAME##_node *node, V element) \
{ \
SNAME##_node *new_node = PFX##_new_node(node->owner, element); \
\
if (!new_node) \
return false; \
\
new_node->prev = node->prev; \
if (node->prev != NULL) \
node->prev->next = new_node; \
else \
node->owner->head = new_node; \
\
new_node->next = node; \
node->prev = new_node; \
\
node->owner->count++; \
\
return true; \
} \
\
FMOD bool PFX##_remove_nxt(SNAME##_node *node) \
{ \
if (node->next == NULL) \
return false; \
\
SNAME##_node *tmp = node->next; \
\
if (node->next != NULL) \
{ \
node->next = node->next->next; \
node->next->prev = node; \
} \
else \
node->owner->tail = node; \
\
node->owner->count--; \
\
free(tmp); \
\
return true; \
} \
\
FMOD bool PFX##_remove_cur(SNAME##_node *node) \
{ \
if (node->prev != NULL) \
node->prev->next = node->next; \
else \
node->owner->head = node->next; \
\
if (node->next != NULL) \
node->next->prev = node->prev; \
else \
node->owner->tail = node->prev; \
\
node->owner->count--; \
\
free(node); \
\
return true; \
} \
\
FMOD bool PFX##_remove_prv(SNAME##_node *node) \
{ \
if (node->prev == NULL) \
return false; \
\
SNAME##_node *tmp = node->prev; \
\
if (node->prev != NULL) \
{ \
node->prev = node->prev->prev; \
node->prev->next = node; \
} \
else \
node->owner->head = node; \
\
free(tmp); \
\
return true; \
} \
\
FMOD SNAME##_node *PFX##_next_node(SNAME##_node *node) \
{ \
return node->next; \
} \
\
FMOD SNAME##_node *PFX##_prev_node(SNAME##_node *node) \
{ \
return node->prev; \
} \
\
FMOD void PFX##_iter_new(SNAME##_iter *iter, SNAME *target) \
{ \
iter->target = target; \
iter->cursor = target->head; \
iter->index = 0; \
iter->start = true; \
iter->end = PFX##_empty(target); \
} \
\
FMOD bool PFX##_iter_start(SNAME##_iter *iter) \
{ \
return iter->cursor->prev == NULL && iter->start; \
} \
\
FMOD bool PFX##_iter_end(SNAME##_iter *iter) \
{ \
return iter->cursor->next == NULL && iter->end; \
} \
\
FMOD void PFX##_iter_tostart(SNAME##_iter *iter) \
{ \
iter->cursor = iter->target->head; \
iter->index = 0; \
iter->start = true; \
iter->end = PFX##_empty(iter->target); \
} \
\
FMOD void PFX##_iter_toend(SNAME##_iter *iter) \
{ \
iter->cursor = iter->target->tail; \
iter->index = iter->target->count - 1; \
iter->start = PFX##_empty(iter->target); \
iter->end = true; \
} \
\
FMOD bool PFX##_iter_next(SNAME##_iter *iter, V *result, size_t *index) \
{ \
if (iter->end) \
return false; \
\
*index = iter->index; \
*result = iter->cursor->data; \
iter->start = false; \
\
if (iter->cursor->next == NULL) \
iter->end = true; \
else \
{ \
iter->cursor = iter->cursor->next; \
iter->index++; \
} \
\
return true; \
} \
\
FMOD bool PFX##_iter_prev(SNAME##_iter *iter, V *result, size_t *index) \
{ \
if (iter->start) \
return false; \
\
*index = iter->index; \
*result = iter->cursor->data; \
iter->end = false; \
\
if (iter->cursor->prev == NULL) \
iter->start = true; \
else \
{ \
iter->cursor = iter->cursor->prev; \
iter->index--; \
} \
\
return true; \
}
#endif /* CMC_LINKEDLIST_H */
</code></pre>
<p><strong>EXAMPLE 1</strong></p>
<p>If you want to have access to the struct members:</p>
<p><strong>header.h</strong></p>
<pre><code>#include "macro_collections.h"
#include "linkedlist.h"
COLLECTION_GENERATE_HEADER(LINKEDLIST, PUBLIC, l, list, /* static */, /* K */, int)
// You can also generate other linked lists of other types
</code></pre>
<p><strong>source.c</strong></p>
<pre><code>#include "header.h"
COLLECTION_GENERATE_SOURCE(LINKEDLIST, PUBLIC, l, list, /* static */, /* K */, int)
// You can also generate other linked lists of other types
</code></pre>
<p><strong>main.c</strong></p>
<pre><code>#include "header.h"
int main(int argc, char const *argv[])
{
list *int_list = l_new(100); // New integer list of capacity 100
// Do stuff
size_t list_count1 = int_list->count; // Valid if PUBLIC
size_t list_count2 = l_count(int_list); // Valid for PUBLIC and PRIVATE
// Do more stuff
l_free(int_list); // Free internal buffer and list struct
}
</code></pre>
<p>Now you just have to compile <strong>source.c</strong> and <strong>main.c</strong> and link them in the end.</p>
<p><strong>EXAMPLE 2</strong></p>
<p>Another example, now using some of the functionalities of the linked list.</p>
<pre><code>#include <stdio.h>
#include <assert.h>
#include "linkedlist.h"
LINKEDLIST_GENERATE(l, list, static, int)
int main(int argc, char const *argv[])
{
list *l = l_new();
for (int i = 0; i < 97; i++)
l_push_back(l, i);
// Add 99 after and 33 before every node where its data is divisible by 3
for (list_node *node = l->head; node != NULL; node = node->next)
{
if (node->data % 3 == 0)
{
l_insert_prv(node, 33);
l_insert_nxt(node, 99);
node = node->next; // skip 99
}
}
size_t s = 0;
for (list_node *node = l_front_node(l); node != NULL; node = l_next_node(node), s++)
{
if (node->prev == NULL)
printf("[ %d, ", node->data);
else if (node->next == NULL)
printf("%d ]\n", node->data);
else
printf("%d, ", node->data);
}
printf("List Head: %d\nList Tail: %d\nList Count: %d\n", l->head->data, l->tail->data, l->count);
assert(s == l->count);
l_free(l);
return 0;
}
</code></pre>
<p><strong>CONCERNS</strong></p>
<p>I have not been able to write intensive tests to check if the list ever gets into some invalid state. Also, allowing the user to deal with nodes is something I was very against at the beginning, but it seems to be working.</p>
<p>I have not had the time to add some functions that are essential to linked lists like <code>splice</code> or <code>concat</code>.</p>
| [] | [
{
"body": "<p>I have only questions, but maybe some of these are useful.</p>\n\n<ul>\n<li>It is desirable to fail fast and in a predictable manner to improper <code>LINKEDLIST_GENERATE</code> commands, maybe with a comment saying what's wrong.</li>\n<li><code>LINKEDLIST_GENERATE_HEADER_PUBLIC</code>, <em>etc</em> is probably too confusing; could it could be simplified? You include <code>FMOD</code>; these defines appear interconnected.</li>\n<li><code>owner</code> for every node is potentially wasteful, are you sure you need it? Same thing, <code>count</code>, are you sure you need it? It makes it so much harder to maintain the proper state.</li>\n<li>Are you sure that you want to do memory allocation internal to the list? It would be much simpler to hand that over to the user. I see <code>l_new(100)</code>, that contradicts <code>PFX##_new(void)</code>; not sure what's going on there.</li>\n<li>Are all of those functions needed? Eg, <code>PFX##_remove_prv, cur, nxt</code>, but the user could easily duplicate pointers.</li>\n<li>In your examples, it's possible to have a <code>l_new</code> that's null and crash. I'm not sure whether checking the pre-conditions in each function is better, or the user is required to verify that the list is not null, but I think you should document it.</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_Tortoise_and_Hare\" rel=\"nofollow noreferrer\">Floyd's algorithm</a> provides great cycle-detection with minimal code. Might be useful when you implement <code>splice</code> and <code>concat</code>. Maybe a debug function that checks if it's in a valid state.</li>\n</ul>\n\n<p>I think it's a very valid use of the pre-processor to generate repeated code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T02:10:18.533",
"Id": "420494",
"Score": "2",
"body": "Thanks for the review! Indeed I plan to change this linked list. It looks very derpy. Also I've written this question a bit too fast so some inconsistencies passed through like the `l_new(100)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:53:15.603",
"Id": "217361",
"ParentId": "216737",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217361",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T17:52:53.560",
"Id": "216737",
"Score": "2",
"Tags": [
"c",
"linked-list",
"generics",
"collections",
"macros"
],
"Title": "Generic Macro Generated Linked List in C"
} | 216737 |
<p>The "nasty implementation" I mentioned is within the <code>void calculator()</code> inside of <code>calculator.cpp</code>. Everything goes well as long as user don't type in the erroneous syntax. But I think this isn't the good idea to implement it this way.
Can I do it the other way around with more reasonable implementation without losing the functionality of being able to calculate infinitely(not really,I know).</p>
<p>main.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "calculator.h"
int main()
{
calculator();
return 0;
}
</code></pre>
<p>calculator.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <cassert>
#include "calculator.h"
int getIntInput()
{
int x{};
std::cin >> x;
assert("Syntax Error!!" && !std::cin.fail());
return x;
}
char getOperatorInput()
{
char x{};
std::cin >> x;
bool b{x == '+' || x == '-' || x == '*' || x == '/' || x == '^'};
assert("Syntax Error!!" && b);
return x;
}
int calculate(int x)
{
char op{getOperatorInput()};
int tmp{getIntInput()};
if(op == '+')
{
return x + tmp;
}
else if(op == '-')
{
return x - tmp;
}
else if(op == '*')
{
return x * tmp;
}
else if(op == '/')
{
return x / tmp;
}
return 0;
}
void calculator()
{
std::cout << "Enter your expression : ";
int64_t result{};
int loopCount{0};
do{
if(loopCount == 0)
result = getIntInput();
result = calculate(result);
loopCount++;
}
while(std::cin.peek() != '\n');
std::cout << "Your result is : " << result << '\n';
}
</code></pre>
<p>calculator.h:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef CALCULATOR_H
#define CALCULATOR_H
int getIntInput();
char getOperatorInput();
void calculator();
#endif // CALCULATOR_H
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>Some general comments:</p>\n\n<ul>\n<li><p>I think your program is small enough not to warrant any functions. Of course, this can be a matter of taste. It's also reasonable to do input parsing, for instance, in a separate function.</p></li>\n<li><p>To avoid hardcoding the possible binary operators, I suggest taking a more data-driven approach and storing all possibilities in a suitable container (like a map).</p></li>\n<li><p>You use integers as your operands, but you support division. Because you truncate the result into an integer type, 1/2 will equal 0 in your calculator. For this reason, you might want to use a floating point type.</p></li>\n</ul>\n\n<p>We could rewrite your program into the following 50 lines or so:</p>\n\n<pre><code>#include <iostream>\n#include <limits>\n#include <map>\n#include <functional>\n#include <cassert>\n\nint main()\n{\n typedef std::function<float(float, float)> binary_op;\n const std::map<char, binary_op> binary_ops =\n {\n { '+', std::plus<float>() },\n { '-', std::minus<float>() },\n { '*', std::multiplies<float>() },\n { '/', std::divides<float>() },\n // NOTE: see how easy adding new functionality is.\n { '#', [](float x, float y) { return x * x * x + y; } }\n };\n\n std::cout << \"Enter your expression: \";\n float result = 0.0;\n\n float x;\n float y;\n char op;\n\n if (!(std::cin >> x >> op >> y))\n {\n std::cout << \"ERROR!\\n\";\n return 0;\n }\n\n const auto op_iter = binary_ops.find(op);\n // Handle errors as you wish.\n assert(op_iter != binary_ops.end());\n result = op_iter->second(x, y);\n\n while (std::cin.peek() != '\\n')\n {\n if (!(std::cin >> op >> y))\n {\n std::cout << \"ERROR!\\n\";\n return 0;\n }\n\n const auto op_iter = binary_ops.find(op);\n // Handle errors as you wish.\n assert(op_iter != binary_ops.end());\n\n result = op_iter->second(result, y);\n }\n\n std::cout << \"Result: \" << result << \"\\n\";\n}\n</code></pre>\n\n<p>Comments about this solution:</p>\n\n<ul>\n<li><p>We do not correctly handle operator precedence. If you want to do this, I suggest looking at something like the <a href=\"https://en.wikipedia.org/wiki/Reverse_Polish_notation\" rel=\"nofollow noreferrer\">Reverse Polish notation</a>.</p></li>\n<li><p>The <code>std::map</code> now implements the data-driven approach as suggested: you easily add more binary operators as long as they satisfy the required interface. That is, any operator will do as long as it takes two operands (castable to floats) and returns a float. For example, you could add in a fifth line for operator '#' (or whatever you want to call it), and parsing etc. is done automagically for you.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T05:07:53.787",
"Id": "426116",
"Score": "0",
"body": "I'm a learner sir. Thanks for your fix. I askd you to fix it so I can learn it. I know about the precedence problem but I'm thinking of taking in the input as a stream with getline() and access it character by character to determine the sequence but I think that could be computationally expensive. How can I fix that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-20T06:07:10.050",
"Id": "426124",
"Score": "0",
"body": "@MichaelDBlake See my edit and particularly the Reverse Polish notation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T18:46:38.900",
"Id": "216741",
"ParentId": "216738",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T17:53:31.927",
"Id": "216738",
"Score": "1",
"Tags": [
"c++",
"calculator",
"math-expression-eval"
],
"Title": "Calculator for any number of inputs"
} | 216738 |
<p>I have this following code to sort an array of strings order by ASCII value (alphabetically) using bubble sort.</p>
<pre><code>#include <stdio.h>
#include <string.h>
int main(){
char txt1[201][10], temp[201];
for(int i=0; i < 10; i++){
if(i){scanf("%c", txt1[i]);}
scanf("%[^\n]s", txt1[i]);
}
for(int i=0; i<9; i++){
for(int j=i+1; j<10; j++){
if(strcmp(txt1[i], txt1[j]) > 0){
strcpy(temp, txt1[i]);
strcpy(txt1[i], txt1[j]);
strcpy(txt1[j], temp);
}
}
}
for(int i=0; i < 10; i++){
printf("%s\n", txt1[i]);
}
}
</code></pre>
<hr>
<p><strong>Sample</strong></p>
<pre><code>> Input
Bravo
Charlie
Foxtrot
Alpha
Golf
Delta
Echo
Hotel
India
Juliet
> Output
Alpha
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliet
</code></pre>
<hr>
<p>But I have a concern at line 6-7 (In the first for loop). I need to input value with <code>space</code> so I used <code>%[^\n]s</code> (to receive a string with <code>space</code>) and <code>%c</code> (to receive <code>space</code> between each input).</p>
<p>Will it produce any problem when sorting if using this method on inputting the value?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T02:59:08.310",
"Id": "419399",
"Score": "0",
"body": "Who or what text suggested an `s` in `\"%[^\\n]s\"`?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T18:34:20.410",
"Id": "216740",
"Score": "1",
"Tags": [
"c",
"strings",
"sorting"
],
"Title": "Sort an array of strings using bubble sort"
} | 216740 |
<p>I have a controller in an ASP.NET Web API application which generates a CSV file. The controller looks like this:</p>
<pre><code>[System.Web.Http.HttpGet]
public HttpResponseMessage Download(int? id = null)
{
if ( !id.HasValue)
return new HttpResponseMessage(HttpStatusCode.NotFound);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(new MemoryStream(_personService
.ExportPersonsToCSV().Content));
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new
ContentDispositionHeaderValue("attachment") {
FileName = _personService.ExportPersonsToCSV().FileName };
return result;
}
</code></pre>
<p>And method <code>ExportPersonsToCSV()</code> of <code>PersonService</code> class:</p>
<pre><code>public FileDTO ExportPersonsToCSV()
{
//...
var dto = new FileDTO()
{
FileName = $"Persons {DateTime.Now}.csv",
MediaTypeHeaderValue = Globals.MEDIA_TYPE_HEADER_VALUE,
Content = _csvExport.WriteCSV(personDeps, columnNames)
};
return dto;
}
</code></pre>
<p>And CSVExport class looks like this:</p>
<pre><code>public class CSVExport : ICSVExport
{
/// <summary>
/// Converting content of MemoryStream into byte array
/// </summary>
public byte[] WriteCSV<T>(IEnumerable<T> objectlist
, IEnumerable<string> columnNames = null)
{
byte[] bytes = null;
using (var memStream = new MemoryStream())
using (var sw = new StreamWriter(memStream, Encoding.GetEncoding("Windows-1251")))
{
sw.WriteLine("sep=,");
foreach (var line in ToCsv(objectlist, columnNames))
{
sw.WriteLine(line);
}
sw.Flush();
memStream.Seek(0, SeekOrigin.Begin);
bytes = memStream.ToArray();
}
return bytes;
}
private IEnumerable<string> ToCsv<T>(IEnumerable<T> objectlist,
IEnumerable<string> columnNames = null, string separator = ",",
bool header = true)
{
//... code omitted for the brevity
yield return string.Join(separator, fields
.ToArray());
}
}
</code></pre>
<p>Recently, I've thought whether a method <code>public byte[] WriteCSV<T>(...)</code> is a violation of Single Responsibility Principle?</p>
<p><strong>My thought it is ok to place here:</strong></p>
<ul>
<li>It is appropriate place to put a logic of converting csv file into byte array cause a method <code>public byte[] WriteCSV<T>(...)</code> placed into a class <code>CSVExport</code></li>
</ul>
<p><strong>My thoughts it is NOT ok to place here:</strong></p>
<ul>
<li>What is <code>MemoryStream</code> class doing here? It is a class of ExportCSV and nothing more!</li>
<li>It is possible to extract dependency(<code>MemoryStream</code>) into separate class like and use it into CSVExport:
IMemoryStream{ byte[] WriteCSV(IEnumerable objects);}</li>
</ul>
<p>So is a method <code>public byte[] WriteCSV<T>(...)</code> placed into <code>CSVExport</code> a violation of Single Responsibility Principle?
Any other criticism are welcome.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T20:34:57.580",
"Id": "419266",
"Score": "2",
"body": "Just curious, did you consider using a csv library such as `CsvHelper` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T07:12:14.480",
"Id": "419307",
"Score": "0",
"body": "@BradM Thanks for advice, however, I would like to implement by myself:)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T19:29:08.960",
"Id": "216744",
"Score": "3",
"Tags": [
"c#",
"csv",
"asp.net-mvc",
"asp.net-web-api",
"asp.net-core"
],
"Title": "Controller in an ASP.NET Web API application which generates a CSV file"
} | 216744 |
<p>I'm a first year computer engineering student who's learning about algorithms and data structures. I've implemented a parallel merge sort algorithm in C++ and would like constructive criticism. This was done in Visual Studio on Windows.</p>
<p><strong>Some thoughts:</strong></p>
<ul>
<li>portability isn't a concern I have atm.</li>
<li><code>merge_sort</code> isn't using tail recursion, which I would like it to do</li>
</ul>
<hr>
<p><br>
<strong>includes:</strong>
<code>#include <thread></code></p>
<p><br>
<strong>function merge:</strong></p>
<pre><code>template<typename T>
void merge(T sequence[], int size)
{
T* sorted = new T[size];
int middle = size / 2;
int index_left = 0;
int index_right = middle;
int index_sequence = 0;
while (index_left < middle && index_right < size)
{
if (sequence[index_left] < sequence[index_right])
sorted[index_sequence++] = sequence[index_left++];
else
sorted[index_sequence++] = sequence[index_right++];
}
while (index_left < middle)
sorted[index_sequence++] = sequence[index_left++];
while (index_right < size)
sorted[index_sequence++] = sequence[index_right++];
for (int i = 0; i < size; i++)
sequence[i] = sorted[i];
delete[] sorted;
}
</code></pre>
<p><br>
<strong>function merge_sort:</strong></p>
<pre><code>template<typename T, int min_size_to_thread = 10000>
void merge_sort(T sequence[], int size)
{
if (size > 1)
{
int middle = size / 2;
if (size > min_size_to_thread)
{
std::thread left(merge_sort<T, min_size_to_thread>, &sequence[0], middle);
std::thread right(merge_sort<T, min_size_to_thread>, &sequence[middle], size - middle);
left.join();
right.join();
}
else
{
merge_sort<T, min_size_to_thread>(&sequence[0], middle);
merge_sort<T, min_size_to_thread>(&sequence[middle], size - middle);
}
merge<T>(sequence, size);
}
}
</code></pre>
<hr>
<p>For those who are interested: I Did some performance testing on a i5-2530M 2.50Ghz (2 cores).<br>
The sequence to merge sort is <code>int[100000]</code></p>
<hr>
<p><strong>Edit:</strong><br>
<br>
I made <code>merge_sort</code> and <code>merge</code> take a <code>T tmp[]</code>. And I made a "wrapper" function around <code>merge_sort</code> like this: </p>
<pre><code>template<typename T>
void merge_sort(T* sequence, int size)
{
T* tmp = new T[size];
_merge_sort(sequence, tmp, size);
delete[] tmp;
}
</code></pre>
<p>Now <code>new</code> is only called once. The "old" <code>merge_sort</code> is renamed to <code>_merge_sort</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T20:41:20.780",
"Id": "419268",
"Score": "0",
"body": "Is `std::thread right` redundant?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:04:53.753",
"Id": "419273",
"Score": "1",
"body": "**I've tested:** `merge_sort` runs faster *without* threading `right`, so it's better to only thread `left` and let right run in the main thread."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T01:02:43.103",
"Id": "419285",
"Score": "0",
"body": "for an array of `100000` elements, you're calling `new` about `100000` times... that will not be efficient"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T12:17:46.000",
"Id": "419336",
"Score": "0",
"body": "@MartinYork Remember that the size of the sequence is halfed for each recursive call. E.g. with `min_size_to_thread = 50000` only 1 extra thread is made."
}
] | [
{
"body": "<p>You would hava a) thread-pools so that the code won't spawn a new thread on each sub-sort, b) a limit on the number of sorts split into threads so that there isn't a new thread spawned for a low number of elements and c) a single array where all the sorting takes place and which is paritioned like a stack among the sort-threads (afaik the whole length should be two times the size of the array).</p>\n\n<p>That would be a much of work to gain an efficient implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T16:27:05.673",
"Id": "419583",
"Score": "0",
"body": "a) can you show how? b) `min_size_to_thread` is the limit. c) that's smart"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T06:28:50.777",
"Id": "216908",
"ParentId": "216746",
"Score": "4"
}
},
{
"body": "<p>That's my parallel merge sort. It's a class with thread-pooling and attached to each thread there is a sort buffer which is recycled when a standby-thread gets another segment to sort; this ensures that the thread works with its memory already lying in the most local caches. The code uses the thread with the most-fitting sort-buffer or when all standby-threads have to small sort-buffers, one thread is arbitrarily chosen and the size of the sort-buffer is adjusted accordingly.</p>\n\n<p>The class is instantiated once with the predicate and you can call .sort() multiple times with the thread- and buffer-pool recycled for each call. Or you can create a temporary object and then call .sort on it, i.e. call parallel_merge_sort().sort( ... ).</p>\n\n<pre><code>#include <vector>\n#include <list>\n#include <thread>\n#include <memory>\n#include <mutex>\n#include <condition_variable>\n#include <algorithm>\n#include <utility>\n#include <exception>\n#include <cassert>\n#include <iterator>\n\ntemplate<typename T>\nstruct invoke_on_destruct\n{\nprivate:\n T &m_t;\n bool m_enabled;\n\npublic:\n invoke_on_destruct( T &t ) :\n m_t( t ), m_enabled( true )\n {\n }\n\n ~invoke_on_destruct()\n {\n if( m_enabled )\n m_t();\n }\n\n void invoke_and_disable()\n {\n m_t();\n m_enabled = false;\n }\n};\n\nstruct sort_exception : public std::exception\n{\n};\n\ntemplate<typename InputIt, typename P = std::less<typename std::iterator_traits<InputIt>::value_type>>\nclass parallel_merge_sort\n{\npublic:\n parallel_merge_sort( P const &p = P() );\n ~parallel_merge_sort();\n void sort( InputIt itBegin, size_t n, std::size_t minThreaded );\n std::size_t get_buffer_size();\n void empty_buffers();\n\nprivate:\n typedef typename std::iterator_traits<InputIt>::value_type value_type;\n typedef typename std::vector<value_type> buffer_type;\n typedef typename buffer_type::iterator buffer_iterator;\n\n struct pool_thread\n {\n enum CMD : int { CMD_STOP = -1, CMD_NONE = 0, CMD_SORT = 1 };\n enum RSP : int { RSP_ERR = -1, RSP_NONE = 0, RSP_SUCCESS = 1 };\n\n std::thread m_thread;\n std::mutex m_mtx;\n std::condition_variable m_sigInitiate;\n CMD m_cmd;\n buffer_iterator m_itBegin;\n std::size_t m_n;\n std::condition_variable m_sigResponse;\n RSP m_rsp;\n std::vector<value_type> m_sortBuf;\n\n pool_thread( parallel_merge_sort *pPMS );\n ~pool_thread();\n void sort_thread( parallel_merge_sort *pPMS );\n static std::size_t calc_buffer_size( size_t n );\n };\n\n P m_p;\n std::size_t m_minThreaded;\n unsigned m_maxRightThreads;\n buffer_type m_callerSortBuf;\n std::mutex m_mtxPool;\n std::list<pool_thread> m_standbyThreads;\n std::list<pool_thread> m_activeThreads;\n\n template<typename InputIt2>\n void threaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf );\n template<typename InputIt2>\n void unthreaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf );\n template<typename OutputIt>\n void merge_back( OutputIt itUp, buffer_iterator itLeft, buffer_iterator itLeftEnd, buffer_iterator itRight, buffer_iterator itRightEnd );\n};\n\ntemplate<typename InputIt, typename P>\nparallel_merge_sort<InputIt, P>::parallel_merge_sort( P const &p ) :\n m_p( p )\n{\n unsigned hc = std::thread::hardware_concurrency();\n m_maxRightThreads = hc != 0 ? (hc - 1) : 0;\n}\n\ntemplate<typename InputIt, typename P>\nvoid parallel_merge_sort<InputIt, P>::sort( InputIt itBegin, size_t n, std::size_t minThreaded )\n{\n size_t const MIN_SIZE = 2;\n if( n < MIN_SIZE )\n return;\n if( (m_minThreaded = minThreaded) < (2 * MIN_SIZE) )\n m_minThreaded = 2 * MIN_SIZE;\n try\n {\n std::size_t s = pool_thread::calc_buffer_size( n );\n if( m_callerSortBuf.size() < s )\n m_callerSortBuf.resize( s );\n threaded_sort( itBegin, n, m_callerSortBuf.begin() );\n }\n catch( ... )\n {\n throw sort_exception();\n }\n}\n\ntemplate<typename InputIt, typename P>\nparallel_merge_sort<InputIt, P>::~parallel_merge_sort()\n{\n assert(m_activeThreads.size() == 0);\n}\n\ntemplate<typename InputIt, typename P>\ninline\nstd::size_t parallel_merge_sort<InputIt, P>::pool_thread::calc_buffer_size( std::size_t n )\n{\n for( std::size_t rest = n, right; rest > 2; )\n right = rest - (rest / 2),\n n += right,\n rest = right;\n return n;\n}\n\ntemplate<typename InputIt, typename P>\nparallel_merge_sort<InputIt, P>::pool_thread::~pool_thread()\n{\n using namespace std;\n unique_lock<mutex> threadLock( m_mtx );\n m_cmd = pool_thread::CMD_STOP;\n m_sigInitiate.notify_one();\n threadLock.unlock();\n m_thread.join();\n}\n\ntemplate<typename InputIt, typename P>\ntemplate<typename InputIt2>\nvoid parallel_merge_sort<InputIt, P>::threaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf )\n{\n using namespace std;\n unique_lock<mutex> poolLock( m_mtxPool );\n\n if( n < m_minThreaded || (m_standbyThreads.empty() && m_activeThreads.size() >= m_maxRightThreads) )\n {\n poolLock.unlock();\n unthreaded_sort( itBegin, n, itSortBuf );\n return;\n }\n\n typedef typename list<pool_thread>::iterator pt_it;\n pt_it itPT;\n pool_thread *pPT;\n size_t left = n / 2,\n right = n - left;\n if( !m_standbyThreads.empty() )\n {\n pt_it itPTScan;\n size_t optimalSize = pool_thread::calc_buffer_size( right ),\n bestFit = (size_t)(ptrdiff_t)-1,\n size;\n for( itPT = m_standbyThreads.end(), itPTScan = m_standbyThreads.begin();\n itPTScan != m_standbyThreads.end(); ++itPTScan )\n if( (size = itPTScan->m_sortBuf.size()) >= optimalSize && size < bestFit )\n itPT = itPTScan,\n bestFit = size;\n if( itPT == m_standbyThreads.end() )\n itPT = --m_standbyThreads.end();\n m_activeThreads.splice( m_activeThreads.end(), m_standbyThreads, itPT );\n poolLock.unlock();\n pPT = &*itPT;\n }\n else\n m_activeThreads.emplace_back( this ),\n itPT = --m_activeThreads.end(),\n pPT = &*itPT,\n poolLock.unlock();\n\n auto pushThreadBack = [&poolLock, &itPT, this]()\n {\n poolLock.lock();\n m_standbyThreads.splice( m_standbyThreads.end(), m_activeThreads, itPT );\n };\n invoke_on_destruct<decltype(pushThreadBack)> autoPushBackThread( pushThreadBack );\n\n buffer_iterator itMoveTo = itSortBuf;\n for( InputIt2 itMoveFrom = itBegin, itEnd = itMoveFrom + n; itMoveFrom != itEnd; *itMoveTo = move( *itMoveFrom ), ++itMoveTo, ++itMoveFrom );\n\n buffer_iterator itLeft = itSortBuf,\n itRight = itLeft + left;\n unique_lock<mutex> threadLock( pPT->m_mtx );\n pPT->m_cmd = pool_thread::CMD_SORT;\n pPT->m_rsp = pool_thread::RSP_NONE;\n pPT->m_itBegin = itRight;\n pPT->m_n = right;\n pPT->m_sigInitiate.notify_one();\n threadLock.unlock();\n\n auto waitForThread = [&threadLock, pPT]()\n {\n threadLock.lock();\n while( pPT->m_rsp == pool_thread::RSP_NONE )\n pPT->m_sigResponse.wait( threadLock );\n assert(pPT->m_rsp == pool_thread::RSP_SUCCESS || pPT->m_rsp == pool_thread::RSP_ERR);\n };\n invoke_on_destruct<decltype(waitForThread)> autoWaitForThread( waitForThread );\n\n threaded_sort( itLeft, left, itSortBuf + n );\n\n autoWaitForThread.invoke_and_disable();\n if( pPT->m_rsp == pool_thread::RSP_ERR )\n throw sort_exception();\n threadLock.unlock();\n\n merge_back( itBegin, itLeft, itLeft + left, itRight, itRight + right );\n}\n\ntemplate<typename InputIt, typename P>\ntemplate<typename InputIt2>\nvoid parallel_merge_sort<InputIt, P>::unthreaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf )\n{\n assert(n >= 2);\n using namespace std;\n if( n == 2 )\n {\n if( m_p( itBegin[1], itBegin[0] ) )\n {\n value_type temp( move( itBegin[0] ) );\n itBegin[0] = move( itBegin[1] );\n itBegin[1] = move( temp );\n }\n return;\n }\n\n buffer_iterator itMoveTo = itSortBuf;\n for( InputIt2 itMoveFrom = itBegin, itEnd = itMoveFrom + n; itMoveFrom != itEnd; *itMoveTo = move( *itMoveFrom ), ++itMoveTo, ++itMoveFrom );\n\n size_t left = n / 2,\n right = n - left;\n buffer_iterator itLeft = itSortBuf,\n itRight = itLeft + left;\n if( left >= 2 )\n unthreaded_sort( itLeft, left, itSortBuf + n );\n if( right >= 2 )\n unthreaded_sort( itRight, right, itSortBuf + n );\n merge_back( itBegin, itLeft, itLeft + left, itRight, itRight + right );\n}\n\ntemplate<typename InputIt, typename P>\ntemplate<typename OutputIt>\ninline\nvoid parallel_merge_sort<InputIt, P>::merge_back( OutputIt itUp, buffer_iterator itLeft, buffer_iterator itLeftEnd, buffer_iterator itRight, buffer_iterator itRightEnd )\n{\n assert(itLeft < itLeftEnd && itRight < itRightEnd);\n using namespace std;\n for( ; ; )\n if( m_p( *itLeft, *itRight ) )\n {\n *itUp = move( *itLeft );\n ++itUp, ++itLeft;\n if( itLeft == itLeftEnd )\n {\n for( ; itRight != itRightEnd; *itUp = move( *itRight ), ++itUp, ++itRight );\n break;\n }\n }\n else\n {\n *itUp = move( *itRight );\n ++itUp, ++itRight;\n if( itRight == itRightEnd )\n {\n for( ; itLeft != itLeftEnd; *itUp = move( *itRight ), ++itUp, ++itLeft );\n break;\n }\n }\n}\n\ntemplate<typename InputIt, typename P>\nstd::size_t parallel_merge_sort<InputIt, P>::get_buffer_size()\n{\n std::size_t s = 0;\n for( pool_thread &pt : m_standbyThreads )\n s += pt.m_sortBuf.capacity();\n return s + m_callerSortBuf.capacity();\n}\n\ntemplate<typename InputIt, typename P>\nvoid parallel_merge_sort<InputIt, P>::empty_buffers()\n{\n for( pool_thread &pt : m_standbyThreads )\n pt.m_sortBuf.clear(),\n pt.m_sortBuf.shrink_to_fit();\n m_callerSortBuf.clear();\n m_callerSortBuf.shrink_to_fit();\n}\n\ntemplate<typename InputIt, typename P>\nparallel_merge_sort<InputIt, P>::pool_thread::pool_thread( parallel_merge_sort *pPMS ) :\n m_mtx(),\n m_sigInitiate(),\n m_cmd( pool_thread::CMD_NONE ),\n m_thread( std::thread( []( pool_thread *pPT, parallel_merge_sort *pPMS ) -> void { pPT->sort_thread( pPMS ); }, this, pPMS ) )\n{\n}\n\ntemplate<typename InputIt, typename P>\nvoid parallel_merge_sort<InputIt, P>::pool_thread::sort_thread( parallel_merge_sort *pPMS )\n{\n using namespace std;\n for( ; ; )\n {\n unique_lock<mutex> threadLock( m_mtx );\n while( m_cmd == CMD_NONE )\n m_sigInitiate.wait( threadLock );\n if( m_cmd == CMD_STOP )\n return;\n assert(m_cmd == pool_thread::CMD_SORT);\n m_cmd = CMD_NONE;\n threadLock.unlock();\n bool success;\n try\n {\n size_t size = calc_buffer_size( m_n );\n if( m_sortBuf.size() < size )\n m_sortBuf.resize( size );\n pPMS->threaded_sort( m_itBegin, m_n, m_sortBuf.begin() );\n success = true;\n }\n catch( ... )\n {\n success = false;\n }\n threadLock.lock();\n m_rsp = success ? RSP_SUCCESS : RSP_ERR,\n m_sigResponse.notify_one();\n }\n}\n\ntemplate<typename InputIt, typename P = std::less<typename std::iterator_traits<InputIt>::value_type>>\nclass ref_parallel_merge_sort\n{\nprivate:\n struct ref\n {\n InputIt it;\n };\n\n struct ref_predicate\n {\n ref_predicate( P p );\n bool operator ()( ref const &left, ref const &right );\n P m_p;\n };\n\npublic:\n ref_parallel_merge_sort( P const &p = P() );\n void sort( InputIt itBegin, size_t n, std::size_t maxUnthreaded );\n std::size_t get_buffer_size();\n void empty_buffers();\n\nprivate:\n parallel_merge_sort<ref, ref_predicate> m_sorter;\n};\n\ntemplate<typename InputIt, typename P>\ninline\nref_parallel_merge_sort<InputIt, P>::ref_predicate::ref_predicate( P p ) :\n m_p ( p )\n{\n}\n\ntemplate<typename InputIt, typename P>\ninline\nbool ref_parallel_merge_sort<InputIt, P>::ref_predicate::operator ()( ref const &left, ref const &right )\n{\n return m_p( *left.it, *right.it );\n}\n\ntemplate<typename InputIt, typename P>\ninline\nref_parallel_merge_sort<InputIt, P>::ref_parallel_merge_sort( P const &p ) :\n m_sorter( ref_predicate( p ) )\n{\n}\n\ntemplate<typename InputIt, typename P>\nvoid ref_parallel_merge_sort<InputIt, P>::sort( InputIt itBegin, size_t n, std::size_t maxUnthreaded )\n{\n using namespace std;\n try\n {\n typedef typename iterator_traits<InputIt>::value_type value_type;\n vector<ref> refBuf;\n InputIt it;\n int i;\n\n refBuf.resize( n );\n for( i = 0, it = itBegin; i != n; refBuf[i].it = it, ++i, ++it );\n m_sorter.sort( &refBuf[0], n, maxUnthreaded );\n\n vector<value_type> reorderBuf;\n reorderBuf.resize( n );\n for( i = 0, it = itBegin; i != n; reorderBuf[i] = move( *it ), ++i, ++it );\n for( i = 0, it = itBegin; i != n; *it = move( reorderBuf[i] ), ++i, ++it );\n }\n catch( ... )\n {\n throw sort_exception();\n }\n}\n\ntemplate<typename InputIt, typename P>\ninline\nstd::size_t ref_parallel_merge_sort<InputIt, P>::get_buffer_size()\n{\n return m_sorter.get_buffer_size();\n}\n\ntemplate<typename InputIt, typename P>\ninline\nvoid ref_parallel_merge_sort<InputIt, P>::empty_buffers()\n{\n m_sorter.empty_buffers();\n}\n\n#include <iostream>\n#include <cstdlib>\n#include <functional>\n#include <random>\n#include <cstdint>\n#include <iterator>\n#include <type_traits>\n\n#if defined(_MSC_VER)\n #include <Windows.h>\n\ndouble get_usecs()\n{\n LONGLONG liTime;\n GetSystemTimeAsFileTime( &(FILETIME &)liTime );\n return (double)liTime / 10.0;\n}\n#elif defined(__unix__)\n #include <sys/time.h>\n\ndouble get_usecs()\n{\n timeval tv;\n gettimeofday( &tv, nullptr );\n return (double)tv.tv_sec * 1'000'000.0 + tv.tv_usec;\n}\n#elif\n #error no OS-support for get_usecs()\n#endif\n\nusing namespace std;\n\nvoid fill_with_random( double *p, size_t n, unsigned seed = 0 )\n{\n default_random_engine re( seed );\n uniform_real_distribution<double> distrib;\n for( double *pEnd = p + n; p != pEnd; *p++ = distrib( re ) );\n}\n\ntemplate<typename T, typename = typename enable_if<is_unsigned<T>::value, T>::type>\nstring decimal_unsigned( T t );\n\nint main()\n{\n typedef typename vector<double>::iterator it_type;\n size_t const SIZE = (size_t)1024 * 1024 * 1024 / sizeof(double);\n unsigned hc = thread::hardware_concurrency();\n vector<double> v;\n double t;\n\n hc = hc ? hc : 1;\n v.resize( SIZE );\n\n parallel_merge_sort<it_type> sd;\n\n fill_with_random( &v[0], SIZE );\n t = get_usecs();\n sd.sort( v.begin(), SIZE, SIZE / hc );\n t = get_usecs() - t;\n cout << (t / 1'000'000.0) << \" seconds parallel\" << endl;\n cout << decimal_unsigned( sd.get_buffer_size() * sizeof(double) ) << endl;\n sd.empty_buffers();\n\n fill_with_random( &v[0], SIZE );\n t = get_usecs();\n sd.sort( v.begin(), SIZE, SIZE );\n t = get_usecs() - t;\n cout << (t / 1'000'000.0) << \" seconds sequential\" << endl;\n cout << decimal_unsigned( sd.get_buffer_size() * sizeof(double) ) << endl;\n sd.empty_buffers();\n}\n\n#include <sstream>\n\nstring decify_string( string const &s );\n\ntemplate<typename T, typename>\nstring decimal_unsigned( T t )\n{\n using namespace std;\n ostringstream oss;\n return move( decify_string( (oss << t, oss.str()) ) );\n}\n\nstring decify_string( string const &s )\n{\n using namespace std;\n ostringstream oss;\n size_t length = s.length(),\n head = length % 3,\n segments = length / 3;\n if( head == 0 && segments >= 1 )\n head = 3,\n --segments;\n oss << s.substr( 0, head );\n for( size_t i = head; i != length; i += 3 )\n oss << \".\" << s.substr( i, 3 );\n return move( oss.str() );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T15:31:00.217",
"Id": "217016",
"ParentId": "216746",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217016",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T19:55:41.037",
"Id": "216746",
"Score": "8",
"Tags": [
"c++",
"beginner",
"multithreading",
"sorting",
"mergesort"
],
"Title": "C++ parallel merge sort"
} | 216746 |
<p>I wrote a simple library for reading RIFF-encoded files in C++.</p>
<p>I tried to adhere to modern practices and provide an idiomatic API, but there is one part that sticks like a sore thumb to me: the way you get the contents of a "chunk" is by calling a <code>data()</code> method, which returns a <code>std::vector<char></code>. Most of the other ways of accessing the data do not require full reading from the stream, this is the only exception.</p>
<p>I'd like to know if there is a better way of accomplishing that.</p>
<p>riffcpp.hpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#ifndef RIFFCPP_H
#define RIFFCPP_H
#include <array>
#include <cstdint>
#include <istream>
#include <iterator>
#include <vector>
namespace riffcpp {
/**
Represents a FourCC
This is a sequence of four bytes used to identify the various types of RIFF
chunks
*/
using FourCC = std::array<char, 4>;
/// The `RIFF` FourCC, used to identify toplevel chunks
constexpr FourCC riff_id = {'R', 'I', 'F', 'F'};
/// The `LIST` FourCC, used to identify chunks that contain other chunks
constexpr FourCC list_id = {'L', 'I', 'S', 'T'};
class ChunkIt;
/**
Represents a RIFF chunk
Every chunk has a four byte identifier (FourCC) and some contents.
Depending on the value of the identifier, the chunk may contain other chunks
as its contents, and in those cases a second FourCC is used to distinguish
the chunk type.
*/
class Chunk {
std::istream &m_stream;
std::streampos m_pos;
public:
/**
Reads a chunk from the specified stream position
The chunk's data is not read initially, it is only loaded when requested
via the various methods provided.
The stream needs to be able to seek to arbitrary positions.
*/
Chunk(std::istream &stream, std::streampos pos);
/// The chunk's identifier
FourCC id();
/// If the chunk contains other chunks, this is its type FourCC
FourCC type();
/// Returns the size of the chunk's contents in bytes
std::uint32_t size();
/**
If this chunk contains other chunks, returns an iterator to the first
chunk contained
`no_chunk_id` is used for chunks which have no chunk id but still contain
subchunks, like `seqt` from DirectMusic
*/
ChunkIt begin(bool no_chunk_id = false);
/**
If this chunk contains other chunks, returns an iterator pointing past the
last chunk contained
*/
ChunkIt end();
/**
Returns the raw contents of the chunk
*/
std::vector<char> data();
};
/**
Provides a way to iterate over subchunks
*/
class ChunkIt {
std::streampos m_pos; ///< Position of the chunk in the stream
std::istream &m_stream; ///< Stream of the chunk
public:
/// Creates an iterator starting from the specified stream position
ChunkIt(std::istream &stream, std::streampos pos);
/// Returns whether two iterators point to the same chunk
bool operator==(const ChunkIt &a) const;
/// Returns whether two iterators do not point to the same chunk
bool operator!=(const ChunkIt &a) const;
/// Returns the chunk pointed by the iterator
Chunk operator*() const;
/// Moves the iterator ahead, to point to the following iterator
ChunkIt &operator++();
/**
Moves the iterator ahead, to point to the following iterator and returns
an iterator to the current position
*/
ChunkIt operator++(int);
};
} // namespace riffcpp
namespace std {
template <> struct iterator_traits<riffcpp::ChunkIt> {
using value_type = riffcpp::Chunk;
using pointer = riffcpp::Chunk *;
using iterator_category = std::input_iterator_tag;
};
} // namespace std
#endif // RIFFCPP_H
</code></pre>
<p>riffcpp.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <riffcpp.hpp>
riffcpp::Chunk::Chunk(std::istream &stream, std::streampos pos)
: m_stream(stream), m_pos(pos) {}
riffcpp::FourCC riffcpp::Chunk::id() {
m_stream.seekg(m_pos);
riffcpp::FourCC read_id;
m_stream.read(read_id.data(), read_id.size());
return read_id;
}
std::uint32_t riffcpp::Chunk::size() {
std::streamoff offs{4};
m_stream.seekg(m_pos + offs);
uint32_t read_size;
m_stream.read(reinterpret_cast<char *>(&read_size), 4);
return read_size;
}
riffcpp::FourCC riffcpp::Chunk::type() {
std::streamoff offs{8};
m_stream.seekg(m_pos + offs);
riffcpp::FourCC read_type;
m_stream.read(read_type.data(), read_type.size());
return read_type;
}
std::vector<char> riffcpp::Chunk::data() {
std::streamoff offs{8};
m_stream.seekg(m_pos + offs);
std::uint32_t data_size = size();
std::vector<char> read_data;
read_data.resize(data_size);
m_stream.read(read_data.data(), data_size);
return read_data;
}
riffcpp::ChunkIt riffcpp::Chunk::begin(bool no_chunk_id) {
std::streamoff offs{no_chunk_id ? 8 : 12};
return riffcpp::ChunkIt(m_stream, m_pos + offs);
}
riffcpp::ChunkIt riffcpp::Chunk::end() {
std::uint32_t sz = size();
std::streamoff offs{sz + sz % 2 + 8};
return riffcpp::ChunkIt(m_stream, m_pos + offs);
}
riffcpp::ChunkIt::ChunkIt(std::istream &stream, std::streampos pos)
: m_stream(stream), m_pos(pos) {}
bool riffcpp::ChunkIt::operator==(const ChunkIt &a) const {
return m_pos == a.m_pos;
}
bool riffcpp::ChunkIt::operator!=(const ChunkIt &a) const {
return !(*this == a);
}
riffcpp::Chunk riffcpp::ChunkIt::operator*() const {
return riffcpp::Chunk(m_stream, m_pos);
}
riffcpp::ChunkIt &riffcpp::ChunkIt::operator++() {
riffcpp::Chunk chunk(m_stream, m_pos);
std::uint32_t sz = chunk.size();
std::streamoff offs{sz + sz % 2 + 8};
m_pos += offs;
return *this;
}
riffcpp::ChunkIt riffcpp::ChunkIt::operator++(int) {
riffcpp::ChunkIt it(m_stream, m_pos);
riffcpp::Chunk chunk(m_stream, m_pos);
std::uint32_t sz = chunk.size();
std::streamoff offs{sz + sz % 2 + 8};
m_pos += offs;
return it;
}
</code></pre>
<p>Example usage:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <riffcpp.hpp>
void print_indent(int indent) {
for (int j = 0; j < indent; j++) {
std::cout << " ";
}
}
void print_hex_dump(std::vector<char> &data, int indent) {
int i = 0;
for (char c : data) {
if (i % 16 == 0) {
print_indent(indent);
}
std::cout << std::setfill('0') << std::setw(2) << std::hex
<< (int)((unsigned char)c) << ' ';
if (i % 16 == 15) {
std::cout << '\n';
}
i++;
}
if (i % 16 != 0) {
i = i % 16;
for (; i < 16; i++) {
std::cout << "-- ";
}
}
std::cout << std::dec << '\n';
}
void print_chunks(riffcpp::Chunk &ch, int offs = 0) {
auto id = ch.id(); // Reads the chunk's id
auto size = ch.size(); // Reads the chunk's size
if (id == riffcpp::riff_id || id == riffcpp::list_id) {
// The chunk is either a 'RIFF' or a 'LIST', so it contains subchunks
print_indent(offs);
auto type = ch.type(); // Reads the chunk's type
std::cout << std::string(id.data(), 4) << " " << std::string(type.data(), 4)
<< " size: " << size << "\n";
// Iterate subchunks
for (auto ck : ch) {
print_chunks(ck, offs + 1);
}
} else {
// The chunk is an unknown type, provide an hexdump
auto data = ch.data();
print_indent(offs);
std::cout << std::string(id.data(), 4) << " size: " << size << "\n";
print_hex_dump(data, offs + 1);
}
}
int main(int argc, char *argv[]) {
std::ifstream stream(argv[1], std::ios::binary);
// Read the chunk from the current position
riffcpp::Chunk ch(stream, stream.tellg());
print_chunks(ch);
}
</code></pre>
<p>Link to GitHub repo: <a href="https://github.com/frabert/riffcpp" rel="noreferrer">https://github.com/frabert/riffcpp</a></p>
| [] | [
{
"body": "<p>There's a serious bug here:</p>\n\n<pre><code> uint32_t read_size;\n m_stream.read(reinterpret_cast<char *>(&read_size), 4);\n</code></pre>\n\n<p>When this code is compiled for a target whose endianness matches the file endianness, I can imagine this working. However, when the endianness is opposite, you'll have results that look very different to what's expected.</p>\n\n<hr>\n\n<p>Instead of specialising <code>std::iterator_traits</code>, it's usually much easier to just provide suitable member types and let the unspecialised template just do its thing:</p>\n\n<pre><code> class ChunkIt {\n using value_type = riffcpp::Chunk;\n using reference = value_type&;\n using pointer = value_type*;\n using difference_type = std::ptrdiff_t;\n using iterator_category = std::input_iterator_tag;\n ...\n };\n</code></pre>\n\n<p>It's conventional to make the iterator an inner type <code>Chunk::iterator</code>. It might be a good idea to include a <code>const_iterator</code> type, too.</p>\n\n<hr>\n\n<p>The code duplication in the iterator can be reduced. For example, we should implement post-increment in terms of pre-increment and a temporary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:15:02.640",
"Id": "419353",
"Score": "0",
"body": "The endianness bug was already known to me, but I couldn't find a workaround that was both standards-compliant and not too longwinded.\n\nRegarding the `const_iterator`, I thought about it for a minute but couldn't understrand how to implement it, given that moving the iterator involves mutating the underlying stream... Any suggestion regarding the `data()` method in Chunk?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:03:53.043",
"Id": "216789",
"ParentId": "216748",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216789",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T20:42:29.987",
"Id": "216748",
"Score": "6",
"Tags": [
"c++",
"api",
"stream"
],
"Title": "C++ API for reading RIFF files"
} | 216748 |
<p>I'm using standard jQuery Ajax to update values in the database and reflect the result in an output. This repetition seems like bad practice and I don't know enough about jQuery to consolidate this correctly.</p>
<p>jQuery</p>
<pre><code> $("#vendorticket").change(function() { //Input/Select tag
var output = ("#vendorticket-result");
$.ajax({
url: 'includes/view.func.php', // Updating database based on specified row id, column, and value
type: 'post',
data: {
vendorticket: $(this).val(),
column: 'vendorticket',
id: 15
},
success: function(result) {
$(output).html(result); //Output span either "Saved" or "Save Failed"
}
});
});
//Rinse & Repeat...
$("#priority").change(function() {
var output = ("#priority-result");
$.ajax({
url: 'includes/view.func.php',
type: 'post',
data: {
priority: $(this).val(),
column: 'priority',
id: 15
},
success: function(result) {
$(output).html(result);
}
});
});
$("#assignedto").change(function() {
var output = ("#assignedto-result");
$.ajax({
url: 'includes/view.func.php',
type: 'post',
data: {
assignedto: $(this).val(),
column: 'assignedto',
id: 15 //
},
success: function(result) {
$(output).html(result);
}
});
});
});
</code></pre>
<p>HTML</p>
<pre><code><input type="text" id="assignedto" /><span id="assignedto-result"></span>
<input type="text" id="priority" /><span id="priority-result"></span>
<input type="text" id="vendorticket" /><span id="vendordicket-result"></span>
</code></pre>
| [] | [
{
"body": "<h2>Simplifying redundancy</h2>\n<p>You could do something like iterating over the id attribute of each input element, calling a function to add the handler.</p>\n<pre><code>['priority', 'assignedTo', 'vendorticket'].forEach(addChangeHandler);\n\nfunction addChangeHandler(inputId) {\n $("#" + inputId).change(function() { //Input/Select tag\n var output = ("#" + inputId + "-result"); \n var data = {\n column: inputId,\n id: 15\n };\n data[inputId] = $(this).val()\n $.post({\n url: 'includes/view.func.php', // Updating database based on specified row id, column, and value\n data: data,\n success: function(result) {\n $(output).html(result); //Output span either "Saved" or "Save Failed"\n }\n });\n }); \n}\n</code></pre>\n<p>Note the code uses the shortcut method <a href=\"https://api.jquery.com/jQuery.post/\" rel=\"nofollow noreferrer\"><code>$.post()</code></a> to allow skipping the request type.</p>\n<p>But a simpler technique would be to add a generic change handler that would be called after any change event on any of those inputs. This can be done by combining the selectors passed to the jQuery function:</p>\n<pre><code>$('#priority, #assignedTo, #vendorticket')\n</code></pre>\n<p>This can then be used to add a generic function handler that can get the <em>id</em> of the input using <a href=\"https://api.jquery.com/attr\" rel=\"nofollow noreferrer\"><code>.attr('id')</code></a>:</p>\n<pre><code>$('#priority, #assignedTo, #vendorticket').change(changeHandler);\nfunction changeHandler() {\n var inputId = $(this).attr('id');\n var output = ("#" + inputId + "-result"); \n var data = {\n column: inputId,\n id: 15\n };\n data[inputId] = $(this).val()\n $.post({\n url: 'includes/view.func.php', // Updating database based on specified row id, column, and value\n data: data,\n success: function(result) {\n $(output).html(result); //Output span either "Saved" or "Save Failed"\n }\n }); \n}\n</code></pre>\n<p>If you had a lot more input elements to add to that list, a class could be applied and they could be selected by class name (e.g. <code>$('.inputToWatch')</code>) or else if they were all child elements of a container then a child selector might simplify things (e.g. <code>$('#containerElement input')</code>.</p>\n<h3>Simplifying the success function</h3>\n<p>The success function could be replaced with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Creating_a_bound_function\" rel=\"nofollow noreferrer\">a bound function</a> - i.e. a function bound to <code>$(output).html</code>:</p>\n<pre><code>success: $().html.bind($(output))\n</code></pre>\n<p>These changes are visible in <a href=\"http://phpfiddle.org/main/code/87gi-1vy4\" rel=\"nofollow noreferrer\">this phpfiddle</a>.</p>\n<p>You could also use the other syntax of <code>$.ajax()</code> i.e. <code>Query.post( url [, data ] [, success ] [, dataType ] )</code></p>\n<pre><code>$.post('includes/view.func.php', data, $().html.bind($(output))); \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T22:57:20.570",
"Id": "216754",
"ParentId": "216751",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T21:31:08.840",
"Id": "216751",
"Score": "0",
"Tags": [
"javascript",
"php",
"jquery",
"event-handling",
"ajax"
],
"Title": "Updating values in a database"
} | 216751 |
<p>I'm working on a <a href="https://github.com/NoahGWood/QRandom" rel="noreferrer">Quantum Random Number Generator</a> and wanted to get some feedback on the project so far.</p>
<p>I'm using PyQuil to generate machine code for the quantum computer, first to create a bell state placing our random bit into a superposition, then I measure the bit to collapse the superposition and repeat the process for N bits. </p>
<p>I'm a little concerned because I haven't been able to come across much data in terms of how long it takes to restore a qubit to a superposition so I can't really say how fast this program is going to work, but on my virtual quantum computer it runs okayish,~0.5 seconds to generate 512 bits, ~1 second for 1024 bits, ~2.09 seconds for 2048 bits.</p>
<p>The QRandom class is a subclass of the Random() class, figured it was easier to re-use than reinvent the wheel completely.</p>
<p>qrandom.py:</p>
<pre><code>"""
Random variable generator using quantum machines
"""
from math import sqrt as _sqrt
import random
import psutil
from pyquil.quil import Program
from pyquil.api import get_qc
from pyquil.gates import H, CNOT
import vm
__all__ = ["QRandom", "random", "randint", "randrange", "getstate", "setstate", "getrandbits"]
BPF = 53 # Number of bits in a float
RECIP_BPF = 2**-BPF
def bell_state():
"""Returns the Program object of a bell state operation on a quantum computer
"""
return Program(H(0), CNOT(0, 1))
def arr_to_int(arr):
"""returns an integer from an array of binary numbers
arr = [1 0 1 0 1 0 1] || [1,0,1,0,1,0,1]
"""
return int(''.join([str(i) for i in arr]), 2)
def arr_to_bits(arr):
return ''.join([str(i) for i in arr])
def int_to_bytes(k, x=64):
"""returns a bytes object of the integer k with x bytes"""
#return bytes(k,x)
return bytes(''.join(str(1 & int(k) >> i) for i in range(x)[::-1]), 'utf-8')
def bits_to_bytes(k):
"""returns a bytes object of the bitstring k"""
return int(k, 2).to_bytes((len(k) + 7) // 8, 'big')
def qvm():
"""Returns the quantum computer or virtual machine"""
return get_qc('9q-square-qvm')
def test_quantum_connection():
"""
Tests the connection to the quantum virtual machine.
attempts to start the virtual machine if possible
"""
while True:
qvm_running = False
quilc_running = False
for proc in psutil.process_iter():
if 'qvm' in proc.name().lower():
qvm_running = True
elif 'quilc' in proc.name().lower():
quilc_running = True
if qvm_running is False or quilc_running is False:
try:
vm.start_servers()
except Exception as e:
raise Exception(e)
else:
break
class QRandom(random.Random):
"""Quantum random number generator
Generates a random number by collapsing bell states on a
quantum computer or quantum virtual machine.
"""
def __init__(self):
super().__init__(self)
self.p = bell_state()
self.qc = qvm()
# Make sure we can connect to the servers
test_quantum_connection()
def random(self):
"""Get the next random number in the range [0.0, 1.0)."""
return (int.from_bytes(self.getrandbits(56, 'bytes'), 'big') >> 3) * RECIP_BPF
def getrandbits(self, k, x="int"):
"""getrandbits(k) -> x. generates an integer with k random bits"""
if k <= 0:
raise ValueError("Number of bits should be greater than 0")
if k != int(k):
raise ValueError("Number of bits should be an integer")
out = bits_to_bytes(arr_to_bits(self.qc.run_and_measure(self.p, trials=k)[0]))
if x in ('int', 'INT'):
return int.from_bytes(out, 'big')
elif x in ('bytes', 'b'):
return out
else:
raise ValueError(str(x) + ' not a valid type (int, bytes)')
def _test_generator(n, func, args):
import time
print(n, 'times', func.__name__)
total = 0.0
sqsum = 0.0
smallest = 1e10
largest = -1e10
t0 = time.time()
for i in range(n):
x = func(*args)
total += x
sqsum = sqsum + x*x
smallest = min(x, smallest)
largest = max(x, largest)
t1 = time.time()
print(round(t1 - t0, 3), 'sec,', end=' ')
avg = total/n
stddev = _sqrt(sqsum / n - avg*avg)
print('avg %g, stddev %g, min %g, max %g\n' % \
(avg, stddev, smallest, largest))
def _test(N=2000):
_test_generator(N, random, ())
# Create one instance, seeded from current time, and export its methods
# as module-level functions. The functions share state across all uses
#(both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own QRandom() instance.
_inst = QRandom()
#seed = _inst.seed
random = _inst.random
randint = _inst.randint
randrange = _inst.randrange
getstate = _inst.getstate
setstate = _inst.setstate
getrandbits = _inst.getrandbits
if __name__ == '__main__':
_test(2)
</code></pre>
<p>vm.py</p>
<pre><code>import os
def start_servers():
try:
os.system("gnome-terminal -e 'qvm -S'")
os.system("gnome-terminal -e 'quilc -S'")
except:
try:
os.system("terminal -e 'qvm -S'")
os.system("terminal -e 'quilc -S'")
except:
exit()
</code></pre>
| [] | [
{
"body": "<p>Interesting stuff. Some high-level comments:</p>\n\n<ul>\n<li>calling <code>exit()</code> when something goes wrong is fine for one-off code of your own but not very polite if you're making a library for others to use. Raise a well-named exception with a meaningful error message instead. As it is, since you're instantiating <code>QRandom</code> at the module level, if someone even imports your module and they don't have qvm/quilc installed (or if they're on a mac, which has neither <code>gnome-terminal</code> nor <code>terminal</code>!) their code will silently exit. </li>\n<li>exporting <code>getstate</code> and <code>setstate</code> from <code>random.Random</code> seems a bit misleading here, since they won't work as expected. I would override them to raise <code>NotImplementedError</code> unless you have a way of implementing them - and the same for <code>seed</code> and <code>jumpahead</code>, in fact.</li>\n</ul>\n\n<p>I have a few more minor detail comments about the code but I'll have to add those later - if you're interested, anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T06:23:11.697",
"Id": "419300",
"Score": "0",
"body": "I'd love to hear more, I'm looking into modifying start_servers() to be platform independent, so if you have any pointers I'm all ears!\n\nAs for get/setstate and seed I'm not sure whether to implement those or not, I'm still kinda iffy on it since in theory we can control the range the qubit is in and it doesn't have to be in a |0⟩ + i |1⟩ superposition, but I have overridden them as suggested. Thanks for the help :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T04:07:52.727",
"Id": "216761",
"ParentId": "216756",
"Score": "1"
}
},
{
"body": "<p>You define several helper functions out of which some are unused and some seem only related to your personal usage, so not really part of a library: <code>qvm</code> and <code>bell_state</code> should be better directly integrated into the <code>QRandom</code> constructor.</p>\n\n<p>I’m also not found of your <code>test_quantum_connection</code>; at least let the user decide if they want to run it or not. And since you’re not doing anything with the exception you are catching, you'd be better off removing the <code>try</code> completely.</p>\n\n<hr>\n\n<p>Your <code>_test_generator</code> function feels really wrong, to me. At the very least, use <a href=\"https://docs.python.org/3/library/time.html#time.perf_counter\" rel=\"nofollow noreferrer\"><code>time.perf_counter</code></a> instead of <code>time.time</code>. But ultimately you should switch to <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a>.</p>\n\n<p>Speaking of which, read the <a href=\"https://docs.python.org/3/library/timeit.html#timeit.Timer.repeat\" rel=\"nofollow noreferrer\">note about timing repeated tests</a>:</p>\n\n<blockquote>\n <p><strong>Note:</strong> It’s tempting to calculate mean and standard deviation from the result vector and report these. However, this is not very useful. In a typical case, the lowest value gives a lower bound for how fast your machine can run the given code snippet; higher values in the result vector are typically not caused by variability in Python’s speed, but by other processes interfering with your timing accuracy. So the min() of the result is probably the only number you should be interested in. After that, you should look at the entire vector and apply common sense rather than statistics.</p>\n</blockquote>\n\n<p>I, however, would remove this function entirely and perform timing tests from the command line directly:</p>\n\n<pre class=\"lang-bsh prettyprint-override\"><code>$ python3 -m timeit -s 'from qrandom import random' 'random()'\n</code></pre>\n\n<hr>\n\n<p>Your various conversion methods seems unefficient: <code>arr_to_int</code> for instance feeds strings to <code>int</code> rather than performing simple additions and bit shifts. Compare:</p>\n\n<pre><code>>>> def stringifier(arr):\n... return int(''.join([str(i) for i in arr]), 2)\n... \n>>> def mapper(arr):\n... return int(''.join(map(str, arr)), 2)\n... \n>>> def adder(arr):\n... return sum(v << i for i, v in enumerate(reversed(arr)))\n... \n>>> from functools import reduce\n>>> def add_bit(number, bit):\n... return (number << 1) + bit\n... \n>>> def reducer(arr):\n... return reduce(add_bit, arr, 0)\n... \n>>> for name in ['stringifier', 'mapper', 'adder', 'reducer']:\n... elapsed = timeit.repeat('{}(lst)'.format(name), 'from __main__ import {}; lst=[1,0,1,0,1,0,1,1,1,0,0,0,1,1,0,1,0]'.format(name), repeat=10)\n... print(name, ':', min(elapsed))\n... \nstringifier : 2.625876844045706\nmapper : 2.1048526159720495\nadder : 1.908082987065427\nreducer : 1.8361501740291715\n</code></pre>\n\n<p>Your are also performing too much conversions in <code>random</code> since you ask for bytes just to convert them to integers right away. Why don't you convert directly to integer then? Besides, this should be the return type of <code>getrandbits</code> anyway; I see little gain in adding the \"select your return type\" overhead and complexity.</p>\n\n<hr>\n\n<p>Proposed improvements:</p>\n\n<pre><code>\"\"\"\nRandom variable generator using quantum machines\n\"\"\"\n\nimport random\nfrom functools import reduce\n\nfrom pyquil.quil import Program\nfrom pyquil.api import get_qc\nfrom pyquil.gates import H, CNOT\n\n\n__all__ = [\"QRandom\", \"random\", \"randint\", \"randrange\", \"getstate\", \"setstate\", \"getrandbits\"]\n\n\nBPF = 53 # Number of bits in a float\nRECIP_BPF = 2**-BPF\n\n\nclass QRandom(random.Random):\n \"\"\"Quantum random number generator\n\n Generates a random number by collapsing bell states on a\n quantum computer or quantum virtual machine.\n \"\"\"\n\n def __init__(self):\n super().__init__(self, computer_name='9q-square-qvm', check_connection=False)\n self.p = Program(H(0), CNOT(0, 1))\n self.qc = get_qc(computer_name)\n if check_connection:\n test_quantum_connection()\n\n def random(self):\n \"\"\"Get the next random number in the range [0.0, 1.0).\"\"\"\n return (self.getrandbits(56) >> 3) * RECIP_BPF\n\n def getrandbits(self, k, x='int'):\n \"\"\"getrandbits(k) -> x. generates an integer with k random bits\"\"\"\n if k <= 0:\n raise ValueError(\"Number of bits should be greater than 0\")\n\n trials = int(k)\n if k != trials:\n raise ValueError(\"Number of bits should be an integer\")\n\n bitfield = self.qc.run_and_measure(self.p, trials=trials)[0]\n result = reduce(_add_bits, bitfield, 0)\n\n if x.lower() in ('int', 'i'):\n return result\n elif x.lower() in ('bytes', 'b'):\n return result.to_bytes((result.bit_length() + 7) // 8, 'big')\n else:\n raise ValueError(str(x) + ' not a valid type (int, bytes)')\n\n\n# Create one instance, seeded from current time, and export its methods\n# as module-level functions. The functions share state across all uses\n#(both in the user's code and in the Python libraries), but that's fine\n# for most programs and is easier for the casual user than making them\n# instantiate their own QRandom() instance.\n\n_inst = QRandom()\n#seed = _inst.seed\nrandom = _inst.random\nrandint = _inst.randint\nrandrange = _inst.randrange\ngetstate = _inst.getstate\nsetstate = _inst.setstate\ngetrandbits = _inst.getrandbits\n\n\ndef _add_bit(number, bit):\n return (number << 1) + bit\n\n\ndef test_quantum_connection():\n \"\"\"\n Tests the connection to the quantum virtual machine.\n attempts to start the virtual machine if possible\n \"\"\"\n import vm\n import psutil\n\n qvm_running = False\n quilc_running = False\n\n while True:\n for proc in psutil.process_iter():\n name = proc.name().lower()\n if 'qvm' in name:\n qvm_running = True\n elif 'quilc' in name:\n quilc_running = True\n if not qvm_running or not quilc_running:\n vm.start_servers()\n else:\n break\n\n\ndef _test_generator(function_name, *arguments, amount=1000000):\n import timeit\n return min(timeit.repeat(\n '{}{}'.format(function_name, arguments),\n 'from {} import {}'.format(__name__, function_name),\n number=amount))\n\n\nif __name__ == '__main__':\n _test_generator('random')\n</code></pre>\n\n<p>I kept <code>_test_generator</code> and the bottom half of <code>getrandbits</code> for completeness but I still advise to remove them if you plan on releasing it as a library.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:22:34.687",
"Id": "216783",
"ParentId": "216756",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T00:31:16.297",
"Id": "216756",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"random",
"quantum-computing"
],
"Title": "Quantum random number generator"
} | 216756 |
<p>I am currently creating a word search program using C. I have created 5 different arrays for subjects containing 15 different words from each. I must also create a program that creates a 2D grid of letters that contain 6 words from a subject chosen by the user prior. The words must go horizontally and vertically.</p>
<p>So far this is the code that I have. Can anyone tell me if I'm on the right track or if I'm completely wrong?</p>
<pre><code>/* ICP-1029 - Assignment 1 */
/* WordSearch Puzzle Porgram */
/* Callum Fawcett */
/* Version 1 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
const char *animalArray[20];
animalArray[0] = "lynx";
animalArray[1] = "kitten";
animalArray[2] = "cheetah";
animalArray[3] = "ape";
animalArray[4] = "doe";
animalArray[5] = "reindeer";
animalArray[6] = "whale";
animalArray[7] = "baboon";
animalArray[8] = "skunk";
animalArray[9] = "dugong";
animalArray[10] = "elephant";
animalArray[11] = "anteater";
animalArray[12] = "chameleon";
animalArray[13] = "lizard";
animalArray[14] = "horse";
const char *colourArray[20]:
colourArray[0] = "red";
colourArray[1] = "green";
colourArray[2] = "blue";
colourArray[3] = "black";
colourArray[4] = "pink";
colourArray[5] = "yellow";
colourArray[6] = "brown";
colourArray[7] = "orange";
colourArray[8] = "purple";
colourArray[9] = "black";
colourArray[10] = "white";
colourArray[11] = "cyan";
colourArray[12] = "maroon";
colourArray[13] = "magenta";
colourArray[14] = "grey";
const char *videogameArray[20];
videogameArray[0] = "fortnite";
videogameArray[1] = "fifa";
videogameArray[2] = "hytale";
videogameArray[3] = "soma";
videogameArray[4] = "prey";
videogameArray[5] = "destiny";
videogameArray[6] = "titanfall";
videogameArray[7] = "woldenstein";
videogameArray[8] = "battlefield";
videogameArray[9] = "fallout";
videogameArray[10] = "tekken";
videogameArray[11] = "skyrim";
videogameArray[12] = "dishonored";
videogameArray[13] = "uncharted";
videogameArray[14] = "anthem";
const char *sportsArray[20];
sportsArray[0] = "basketball";
sportsArray[1] = "football";
sportsArray[2] = "cricket";
sportsArray[3] = "wrestling";
sportsArray[4] = "fencing";
sportsArray[5] = "rowing";
sportsArray[6] = "volleyball";
sportsArray[7] = "baseball";
sportsArray[8] = "hockey";
sportsArray[9] = "racing";
sportsArray[10] = "golf";
sportsArray[11] = "bobsleigh";
sportsArray[12] = "curling";
sportsArray[13] = "snowboarding";
sportsArray[14] = "bowling";
const char *countryArray[20];
countryArray[0] = "england";
countryArray[1] = "ireland";
countryArray[2] = "china";
countryArray[3] = "wales";
countryArray[4] = "bangladesh";
countryArray[5] = "maldives";
countryArray[6] = "slovenia";
countryArray[7] = "uruguay";
countryArray[8] = "colombia";
countryArray[9] = "samoa";
countryArray[10] = "jamaica";
countryArray[11] = "malta";
countryArray[12] = "bulgaria";
countryArray[13] = "armenia";
countryArray[14] = "gamnbia";
}
char **create2DArray(); //function prototype
#define WIDTH 16
#define HEIGHT 16
char** myArray; //global array
void main()
{
myArray = create2DArray();
}
//Creates a 2D array of WIDTH * HEIGHT and returns a pointer to it
char **create2DArray(){
int i,j;
char **array = (char **) malloc(sizeof(char *) * WIDTH);
for(i=0; i<WIDTH; i++)
array[i] = (char *) malloc(sizeof(char) * HEIGHT);
for(i=0; i<WIDTH; i++)
for(j=0; j<HEIGHT; j++)
// array[i][j] = 65 + rand() % 25;
array[i][j] = '.';
return array;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T06:25:10.773",
"Id": "419301",
"Score": "4",
"body": "Welcome to Code Review. There is a mismatch with your title/description and code. Your code does not contain a \"word search program\" yet. Instead, it only contains some arrays with words and some 2D grid that's not printed. I suggest you to describe the *current* state of your program, not the desired one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T17:31:04.787",
"Id": "419484",
"Score": "1",
"body": "Code Review is for making suggestions to improve code that works and cleanly compiles. Suggest moving this question to `stackoverflow.com`"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T00:51:50.420",
"Id": "216757",
"Score": "0",
"Tags": [
"c"
],
"Title": "Creating a Word Search Program in C"
} | 216757 |
<p>Here are the changes I've made thanks to suggestions made by @vnp, and @Henrik Hansen. Here is the link to the previous code review: <a href="https://codereview.stackexchange.com/questions/216503/linked-list-implementation-along-with-unit-test-round-2">Linked list implementation along with unit test - Round 2</a></p>
<p>I've made some new additions that were not mentioned and added more unit tests. I really feel like I'm improving!</p>
<p>Implementation</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
namespace DataStructuresAndAlgorithms.DataStructures
{
public class LinkedList<T> : IEnumerable<T>
{
class Node
{
public T Data { get; set; }
public Node Next { get; set; }
public Node Previous { get; set; }
public Node(T data)
{
Data = data;
}
}
private Node _head, _tail;
public T Head => _head == null ? throw new NullReferenceException() : _head.Data;
public T Tail => _tail == null ? throw new NullReferenceException() : _tail.Data;
public bool IsEmpty { get { return Count > 0 ? false : true; } }
public int Count { get; private set; } = 0;
public LinkedList() { }
public LinkedList(IEnumerable<T> items)
{
foreach (var item in items)
{
AddTail(item);
}
}
public void AddHead(T item)
{
var node = new Node(item);
if (_head == null && _tail == null)
{
_head = node;
_tail = node;
Count += 1;
}
else
{
node.Next = _head;
_head.Previous = node;
Count += 1;
}
_head = node;
}
public void AddTail(T item)
{
var node = new Node(item);
if (_tail == null && _head == null)
{
_head = node;
_tail = node;
Count += 1;
}
else
{
node.Previous = _tail;
_tail.Next = node;
Count += 1;
}
_tail = node;
}
public T RemoveHead()
{
if (_head == null) return default;
else
{
var temp = _head.Next;
_head = _head.Next;
if (_head != null) _head.Previous = null;
Count -= 1;
if (temp == null) return default;
return temp.Data;
}
}
public T RemoveTail()
{
if (_tail == null) return default;
else
{
var temp = _tail.Previous;
_tail = _tail.Previous;
if (_tail != null) _tail.Next = null;
Count -= 1;
if (temp == null) return default;
return temp.Data;
}
}
public bool Find(T item)
{
if (_head == null || _tail == null) return false;
var node = _head;
while (node.Data.Equals(item) == false)
{
if (node.Next == null)
return false;
node = node.Next;
}
return true;
}
public bool Remove(int index)
{
if (_head == null || _tail == null) return false;
var node = _head;
for (int i = 0; i < Count; i++)
{
if (i == index) break;
node = node.Next;
}
// Remove the node
if (node == null) return false;
bool isRemoved = NodeAwareRemove(node);
return isRemoved;
}
private bool NodeAwareRemove(Node node)
{
if (node.Next != null && node.Previous != null)
{
// In between nodes
node.Previous.Next = node.Next;
node.Next.Previous = node.Previous;
Count -= 1;
return true;
}
if (node.Next != null && node.Previous == null)
{
// Head node
RemoveHead();
return true;
}
if (node.Previous != null && node.Next == null)
{
// Tail node
RemoveTail();
return true;
}
if (node.Next == null && node.Previous == null)
{
// Only node
_head = null;
_tail = null;
Count -= 1;
return true;
}
return false;
}
public int RemoveAll(T item)
{
if (_head == null || _tail == null) return -1;
var node = _head;
int numberRemoved = 0;
while (node != null)
{
if (node.Data.Equals(item))
{
if (NodeAwareRemove(node)) numberRemoved += 1;
}
node = node.Next;
}
return numberRemoved;
}
public T GetIndex(int index)
{
if (index < 0) throw new IndexOutOfRangeException();
if (index > Count) throw new IndexOutOfRangeException();
if (index == 0) return _head.Data;
var temp = _head;
for (int i = 0; i < Count; i++)
{
if (i == index) break;
temp = temp.Next;
}
return temp.Data;
}
public bool SetIndex(int index, T item)
{
if (index < 0) throw new IndexOutOfRangeException();
if (index > Count) throw new IndexOutOfRangeException();
if (index == 0) _head.Data = item;
var temp = _head;
for (int i = 0; i < Count; i++)
{
if (i == index) break;
temp = temp.Next;
}
temp.Data = item;
return true;
}
public object this[int i]
{
get { return GetIndex(i); }
set { SetIndex(i, (T)value); }
}
public IEnumerator<T> GetEnumerator()
{
var pointer = _head;
while (pointer != null)
{
yield return pointer.Data;
pointer = pointer.Next;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
</code></pre>
<p>Unit Test</p>
<pre><code>using System;
using Xunit;
using DataStructuresAndAlgorithms.DataStructures;
namespace DataStructuresAndAlgorithms.DataStructures.Tests
{
public class LinkedListTest
{
[Fact]
public void AddHead_Node_Should_Become_Head()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.AddHead(45);
// Assert
Assert.Equal(45, myLinkedList.Head);
}
[Fact]
public void AddTail_Node_Should_Become_Tail()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.AddTail(7777);
// Assert
Assert.Equal(7777, myLinkedList.Tail);
}
[Fact]
public void RemoveHead_Next_Node_Should_Be_Head()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.RemoveHead();
// Assert
Assert.Equal(2, myLinkedList.Head);
}
[Fact]
public void RemoveTail_Next_Node_Should_Be_Tail()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.RemoveTail();
// Assert
Assert.Equal(4, myLinkedList.Tail);
}
[Fact]
public void Find_5_Should_Return_True()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
var isFound = myLinkedList.Find(5);
// Assert
Assert.True(isFound);
}
[Fact]
public void IsEmpty_Should_Return_False_Count_Equal_5()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
var isEmpty = myLinkedList.IsEmpty;
// Assert
Assert.False(isEmpty);
}
[Fact]
public void IsEmpty_Should_Return_True_Count_Equal_0()
{
// Arrange
int[] myNums = { };
var myLinkedList = new LinkedList<int>(myNums);
// Act
var isEmpty = myLinkedList.IsEmpty;
// Assert
Assert.True(isEmpty);
}
[Fact]
public void GetIndex_4_Should_Equal_5()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
var index = myLinkedList.GetIndex(4);
// Assert
Assert.Equal(5, index);
}
[Fact]
public void SetIndex_2_10_Should_Set_Index_2_To_10()
{
// Arrange
int[] myNums = { 1, 2, 3, 4, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.SetIndex(2, 10);
// Assert
Assert.Equal(10, myLinkedList[2]);
}
[Fact]
public void RemoveAll_Should_Delete_All_5s()
{
// Arrange
int[] myNums = { 5, 5, 5, 3, 2, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
myLinkedList.RemoveAll(5);
// Assert
Assert.False(myLinkedList.Find(5));
}
[Fact]
public void Remove_1_Should_Return_True()
{
// Arrange
int[] myNums = { 5, 5, 5, 3, 2, 5 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
bool isRemoved = myLinkedList.Remove(1);
// Assert
Assert.True(isRemoved);
}
[Fact]
public void Remove_2_Should_Return_False()
{
// Arrange
int[] myNums = { 1 };
var myLinkedList = new LinkedList<int>(myNums);
// Act
bool isRemoved = myLinkedList.Remove(2);
// Assert
Assert.False(isRemoved);
}
[Fact]
public void AddHead_Should_Increment_Count()
{
// Arrange
int[] myNums = { 1 };
var myLinkedList = new LinkedList<int>(myNums);
var theCount = myLinkedList.Count;
// Act
myLinkedList.AddHead(7);
myLinkedList.AddHead(7);
myLinkedList.AddHead(7);
myLinkedList.AddHead(7);
myLinkedList.AddHead(7);
// Assert
Assert.Equal(theCount + 5, myLinkedList.Count);
}
[Fact]
public void Remove_2_Should_Decrement_Count()
{
// Arrange
int[] myNums = { 1 };
var myLinkedList = new LinkedList<int>(myNums);
var theCount = myLinkedList.Count;
// Act
myLinkedList.RemoveTail();
// Assert
Assert.Equal(theCount - 1, myLinkedList.Count);
}
}
}
</code></pre>
<p>Presentation</p>
<pre><code>using System;
using System.Collections;
using DataStructuresAndAlgorithms.DataStructures;
namespace DataStructuresAndAlgorithms.Presentation.Console
{
class Program
{
static void Main(string[] args)
{
RunLinkedList();
}
static void RunLinkedList()
{
System.Console.WriteLine("Running the LinkedList class");
System.Console.WriteLine("----------------------------");
var myLinkedList = new LinkedList<int>();
myLinkedList.AddHead(1);
myLinkedList.AddHead(2);
myLinkedList.AddHead(3);
myLinkedList.AddHead(4);
myLinkedList.AddHead(5);
myLinkedList.RemoveHead();
myLinkedList.RemoveTail();
myLinkedList.SetIndex(2, 10);
myLinkedList[2] = 2;
System.Console.WriteLine("Count = " + myLinkedList.Count);
System.Console.WriteLine("Is Empty = " + myLinkedList.IsEmpty);
PrintList<int>(myLinkedList);
}
static void PrintList<T>(LinkedList<T> myList)
{
if (myList.Head == null || myList.Tail == null) return;
var listText = "LinkedList[";
for (int i = 0; i < myList.Count; i++)
{
listText += myList[i];
if (i < myList.Count - 1)
{
listText += "<";
listText += "---";
listText += ">";
}
}
listText += "]";
System.Console.WriteLine(listText);
System.Console.WriteLine("Found Data = 66 -> " + myList.Find((T)(object)66));
System.Console.WriteLine("Found Data = 3 -> " + myList.Find((T)(object)3));
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T02:42:36.423",
"Id": "419288",
"Score": "0",
"body": "I think that `Find(T item)` is kind of useless as it is right now. I think that it should return the indecies of all matches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T10:01:21.140",
"Id": "419322",
"Score": "0",
"body": "nice stuff, but since you are doing it in C#, I would suggest following C# standards. You want to implement a list, and there is an interface [IList](https://docs.microsoft.com/en-us/dotnet/api/system.collections.ilist?view=netframework-4.7.2) along with its generic version. Instead of inventing your own names for methods and your own methods, you can implement this standard interface. Then it will nicely play along with the whole framework. Also, it can support synchronization, so that's a nice next step"
}
] | [
{
"body": "<h1>Exception</h1>\n\n<p>I know this conflicts with @Henrik Hansen's advice on your previous review, however rather than throwing <code>NullReferenceException</code>, I'd suggest throwing <code>InvalidOperationException</code>. Throwing <code>NullReferenceException</code> gives a bit too much information about the implementation details of your class. It also suggests that there's a problem with your implementation, rather than telling the client they are trying to do something wrong (get an object from an empty list). Switching to <code>InvalidOperationException</code> will also mean that your classes behaviour matches that of other standard collections such as <code>Queue</code> and <code>Stack</code>.</p>\n\n<h1>Consistency</h1>\n\n<p>You're mixing an matching single line function definitions:</p>\n\n<blockquote>\n<pre><code>public T Tail => _tail == null ? throw new NullReferenceException() : _tail.Data;\npublic bool IsEmpty { get { return Count > 0 ? false : true; } }\n</code></pre>\n</blockquote>\n\n<p>I don't see why you didn't do the same with <code>IsEmpty</code> that you've done with <code>Tail</code>/<code>Head</code>.</p>\n\n<pre><code>public bool IsEmpty => Count > 0 ? false : true; \n</code></pre>\n\n<h1>Double Checking</h1>\n\n<p>As soon as you put something into your list, you update both the <code>_head</code> and <code>_tail</code>. When you add to the head/tail at the moment, you're checking both:</p>\n\n<pre><code> if (_head == null && _tail == null)\n</code></pre>\n\n<p>This seems redundant. Either the list will have something in it (in which case <code>_head</code>/<code>_tail</code> should both not be <code>null</code>), or the list will be empty (in which case both <code>_head</code> and <code>_tail</code> should be <code>null</code>. Which brings me on to...</p>\n\n<h1>Bug(s)</h1>\n\n<p>You have a bug in your <code>RemoveHead</code> method (and a corresponding one in <code>RemoveTail</code>). If the list contains only one item, then both <code>_head</code> and <code>_tail</code> point to the same <code>Node</code>. So, when you remove that node, both references will need to be updated. At the moment, <code>RemoveHead</code> updates the head, but not the tail, which means that tail points to a node that shouldn't be there anymore. This can lead to trouble. Consider the following test, which should pass, but fails with a NullReference.</p>\n\n<pre><code>[Fact]\npublic void RemoveHead_ThenAdd_Should_Set_Head_Tail()\n{\n // Arrange\n int[] myNums = { 1 };\n var myLinkedList = new LinkedList<int>(myNums);\n Assert.Equal(1, myLinkedList.Head);\n Assert.Equal(1, myLinkedList.Tail);\n\n //Act\n myLinkedList.RemoveHead();\n myLinkedList.AddTail(5);\n\n //Assert\n Assert.Equal(5, myLinkedList.Tail);\n Assert.Equal(5, myLinkedList.Head); // This fails with NullReference\n}\n</code></pre>\n\n<h1>Misleading Behaviour / Bug</h1>\n\n<p>When removing from the head/tail, you return a <code>default</code> value if the list is empty. This feels wrong, since you throw an exception if the client tries to access the head/tail values of an empty list. It feels like removing the head/tail of an empty list should throw the same exception.</p>\n\n<p>It also looks like the remove head/tail methods are supposed to return the data value from the removed <code>Node</code>. They don't, they return the data value from the new head/tail, or <code>default</code> if there's only one item in the list. Seems like a bug. At best, it's confusing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-04T09:44:51.450",
"Id": "238353",
"ParentId": "216758",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T01:09:18.427",
"Id": "216758",
"Score": "2",
"Tags": [
"c#",
"beginner",
"linked-list",
"unit-testing"
],
"Title": "Linked list implementation along with unit test - Round 3"
} | 216758 |
<p>I wrote a solution to <a href="https://leetcode.com/problems/course-schedule-ii/" rel="nofollow noreferrer">Course Schedule II - LeetCode</a></p>
<blockquote>
<p>There are a total of <em>n</em> courses you have to take, labeled from <code>0</code> to <code>n-1</code>.</p>
<p>Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: <code>[0,1]</code></p>
<p>Given the total number of courses and a list of prerequisite <strong>pairs</strong>, return the ordering of courses you should take to finish all courses.</p>
<p>There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.</p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: 2, [[1,0]]
Output: [0,1]
Explanation: There are a total of 2 courses to take. To take course 1 you should have finished
</code></pre>
<p><strong>Example 2:</strong></p>
<pre class="lang-py prettyprint-override"><code>Input: 4, [[1,0],[2,0],[3,1],[3,2]]
Output: [0,1,2,3] or [0,2,1,3]
Explanation:
There are a total of 4 courses to take. To take course 3 you should have finished both
courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0.
So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] .
</code></pre>
<p><strong>Note:</strong></p>
<ol>
<li>The input prerequisites is a graph represented by <strong>a list of edges</strong>, not adjacency matrices. Read more about <a href="https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs" rel="nofollow noreferrer">how a graph is represented</a>.</li>
<li>You may assume that there are no duplicate edges in the input prerequisites.</li>
</ol>
</blockquote>
<p>my solution</p>
<pre><code>class Solution:
def findOrder(self,numCourses, prerequirements):
"""
:type numCourse: int
:type prerequirements: List[List[int]]
:rtype:bool
"""
#if not prerequirements: return True
# if numCourses == None and len(prerequirements) == 0: return True
L = []
in_degrees = [ 0 for _ in range(numCourses)] #index as node
#graph = [[]] * numCourses
graph = [[] for _ in range(numCourses)]
#Construct the graph
for u, v in prerequirements:
graph[v].append(u) #index as node
in_degrees[u] += 1
logging.debug(f"graph: {graph}")
logging.debug(f"in_degrees {in_degrees}")
#
Q = [i for i in range(len(in_degrees)) if in_degrees[i]==0] #collect nodes without pre-edges
logging.debug(f"Q: {Q}")
while Q: #while Q is not empty
start = Q.pop()#remove a node from Q
L.append(start) #add n to tail of L
logging.debug(f"L: {L}")
for v in graph[start]:#for each node v with a edge e
in_degrees[v] -= 1 #remove edge
if in_degrees[v] == 0:
Q.append(v)
logging.debug(f"indegree: {in_degrees}")
#check there exist a cycle
for i in range(len(in_degrees)): #if graph has edge
if in_degrees[i] > 0:
return []
logging.debug(f"L: {L}")
return L
</code></pre>
<p>TestCase:</p>
<pre><code>class MyCase(unittest.TestCase):
def setUp(self):
self.solution1 = Solution()
self.solution2 = Solution2()
def test_bfs1(self):
numCourse = 2
prerequirements = [[1,0]]
check = self.solution1.findOrder(numCourse, prerequirements)
logging.debug(f"{check}")
answer = [0, 1]
self.assertEqual(check, answer)
def test_bfs2(self):
numCourse = 4
prerequirements = [[1,0],[2,0],[3,1],[3,2]]
check = self.solution1.findOrder(numCourse, prerequirements)
logging.debug(f"{check}")
answer = [[0,1,2,3], [0,2,1,3]]
self.assertIn(check, answer)
def test_bfs3(self):
numCourse = 2
prerequirements = []
check = self.solution1.findOrder(numCourse, prerequirements)
logging.debug(f"{check}")
answer = [1,0]
self.assertEqual(check, answer)
def test_bfs4(self):
numCourse = 2
prerequirements = [[0,1],[1,0]]
check = self.solution1.findOrder(numCourse, prerequirements)
logging.debug(f"{check}")
answer = []
self.assertEqual(check, answer)
</code></pre>
<p>Get a low score</p>
<blockquote>
<p>Runtime: 56 ms, faster than 57.28% of Python3 online submissions for Course Schedule II.
Memory Usage: 14 MB, less than 51.41% of Python3 online submissions for Course Schedule II.</p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T06:59:06.910",
"Id": "419305",
"Score": "0",
"body": "Your code uses less time and less memory than a half of all submissions in the same language. It's certainly not a _low score_."
}
] | [
{
"body": "<ul>\n<li><p>The docstring is wrong. <code>findOrder</code> returns a list, not a boolean.</p></li>\n<li><p>Few inefficiencies:</p>\n\n<ul>\n<li><p>The cycle checking implementation is way suboptimal. The algorithm terminates successfully if <em>every</em> node lands in <code>L</code>. It is enough to test that <code>len(L) = len(in_degrees)</code>. No need to loop.</p></li>\n<li><p>You don't need <code>Q</code>. You may work directly with <code>L</code>. Less memory, and less copying. Admittedly, the resulting code may look a bit scary (list is modified while being iterated on), but <code>append</code> appears to be safe. You may find <a href=\"https://stackoverflow.com/a/48604036/3403834\">this discussion</a> interesting.</p></li>\n</ul></li>\n<li><p><code>[i for i in range(len(in_degrees)) if in_degrees[i]==0]</code> doesn't look Pythonic. Consider</p>\n\n<pre><code> [i for i, n in enumerate(in_degrees) if n == 0]\n</code></pre></li>\n<li><p>To my taste, the code is commented too much.</p></li>\n</ul>\n\n<p><strike> - Nitpick. Strictly speaking, the problem statement doesn't guarantee that the courses IDs are dense. A schedule may look like <code>3, [[100, 200], [200, 300]]</code>. In such case case <code>graph[v].append(u)</code> will raise an <code>IndexError</code>. Consider a dictionary instead of a list as a graph representation.</strike></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T07:06:23.377",
"Id": "419306",
"Score": "0",
"body": "Strictly speaking, the problem statement _does_ guarantee it: _**There are a total of n courses you have to take, labeled from `0` to `n-1`.**_ However, it does not specify the possible range for _n_; specifically, it doesn't guarantee _n_ will fit in the standard `int` type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T07:16:25.613",
"Id": "419308",
"Score": "0",
"body": "@CiaPan Thanks. Misread the PS. Edited."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T06:33:06.097",
"Id": "216765",
"ParentId": "216760",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216765",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T02:51:16.577",
"Id": "216760",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"programming-challenge",
"graph"
],
"Title": "Kahn's algorithms to arrange CouseSchedule"
} | 216760 |
<p>I have created a thread-safe and lock-free memory pool program using C++11 features. A couple of notable features:</p>
<ul>
<li><code>g_memStack</code> is a stack that contains the memory unit; we can allocate memory from it.</li>
<li><code>g_waitingReclaims</code> is something like a stack that contains units waiting reclaim from the memory unit.</li>
<li><code>g_allocatingCounter</code> is a counter to specify the thread number in the <code>Allocate</code> function. It will have a value of 1 to indicate that there is no other thread waiting to allocate memory from the pool. This indicates that it is safe to reclaim memory in <code>g_waitingReclaims</code>.</li>
</ul>
<p>I am looking for a review of both <em>correctness</em> and <em>style</em>. Specifically:</p>
<ul>
<li><p>Is there anything wrong with the memory ordering in <code>g_allocatingCounter.fetch_add(1, std::memory_order_relaxed</code> (the first line in the <code>Allocate</code> function?)?</p></li>
<li><p>Is it possible that the next line (<code>MemUnit *unit = g_memStack.load(std::memory_order_acquire);</code> could be re-ordered to execute first at runtime?</p></li>
<li><p>If so, how would I fix that? Could I just change the memory order to <code>std::memory_order_acquire</code>? Would that require another release operation to cooperate with it (I don't think so, because <a href="https://en.cppreference.com/w/cpp/atomic/memory_order" rel="nofollow noreferrer">cppreference</a> said <code>std::memory_order_acquire</code> will prevent read and write from reordering before it)?</p></li>
<li><p>Anything else?</p></li>
</ul>
<pre><code>#include <string>
#include <thread>
#include <vector>
#include <cstdlib>
#include <atomic>
#include <cassert>
struct MemUnit
{
MemUnit *m_next;//next unit
void *m_data;//memory for data
};
void *g_buffer{nullptr};
std::atomic<MemUnit *> g_memStack{};
std::atomic<MemUnit *> g_waitingReclaims{};
std::atomic<uint32_t> g_allocatingCounter{};
void InitMemPool(size_t poolSize, size_t blockSize);
void UninitMemPool();
MemUnit *StepToTail(MemUnit* listHead);
void Reclaim(MemUnit* listHead, MemUnit* listTail);
void GiveBackToWaitings(MemUnit* listHead, MemUnit* listTail);
MemUnit *Allocate()
{
g_allocatingCounter.fetch_add(1, std::memory_order_relaxed);//Warning: Something wrong with the memory order. It maybe reorder after the next line at runtime.
MemUnit *unit = g_memStack.load(std::memory_order_acquire);
while (unit != nullptr && !g_memStack.compare_exchange_weak(unit, unit->m_next, std::memory_order_acquire, std::memory_order_acquire));
if (g_allocatingCounter.load(std::memory_order_relaxed) == 1)
{
MemUnit *pendingList = g_waitingReclaims.exchange(nullptr, std::memory_order_acquire);
const bool canReclaim = g_allocatingCounter.fetch_sub(1, std::memory_order_relaxed) == 1;//this operation can not reorder before exchange operation Just because the 'memory_order_acquire'
//If 'canReclaim' is true, it's ABA problem free. Because there is nobody in 'Allocate' hold same pointer within pending list.
if (canReclaim && pendingList != nullptr)
{
canReclaim ? Reclaim(pendingList, StepToTail(pendingList)) : GiveBackToWaitings(pendingList, StepToTail(pendingList));
}
return unit;
}
g_allocatingCounter.fetch_sub(1, std::memory_order_relaxed);//this operation can not reorder before 'compare_exchange_weak' Just because the 'memory_order_acquire'
return unit;
}
void FreeMemUnit(MemUnit* item)
{
item->m_next = g_waitingReclaims.load(std::memory_order_relaxed);
while (!g_waitingReclaims.compare_exchange_weak(item->m_next, item, std::memory_order_release, std::memory_order_relaxed));
}
MemUnit *StepToTail(MemUnit* listHead)
{
assert(listHead != nullptr);
while (listHead->m_next) listHead = listHead->m_next;
return listHead;
}
void Reclaim(MemUnit* listHead, MemUnit* listTail)
{
listTail->m_next = g_memStack.load(std::memory_order_relaxed);
while (!g_memStack.compare_exchange_weak(listTail->m_next, listHead, std::memory_order_release, std::memory_order_relaxed));
}
void GiveBackToWaitings(MemUnit* listHead, MemUnit* listTail)
{
listTail->m_next = g_waitingReclaims.load(std::memory_order_relaxed);
while (!g_waitingReclaims.compare_exchange_weak(listTail->m_next, listHead, std::memory_order_relaxed, std::memory_order_relaxed));
//Yes, it's 'relaxed' memory order when it's success.
}
void InitMemPool(size_t poolSize, size_t blockSize)
{
const size_t unitSize = sizeof(MemUnit) + blockSize;
g_buffer = reinterpret_cast<uint8_t *>(std::malloc(unitSize * poolSize));
MemUnit* next = nullptr;
uint8_t* rawBuffer = reinterpret_cast<uint8_t*>(g_buffer);
for (size_t i = 0; i != poolSize; ++i)
{
MemUnit* pObj = reinterpret_cast<MemUnit *>(rawBuffer);
pObj->m_next = next;
next = pObj;
rawBuffer += unitSize;
}
g_memStack.store(next, std::memory_order_relaxed);
}
void UninitMemPool()
{
assert(g_allocatingCounter.load(std::memory_order_relaxed) == 0);
g_memStack.store(nullptr, std::memory_order_relaxed);
g_waitingReclaims.store(nullptr, std::memory_order_relaxed);
std::free(g_buffer);
g_buffer = nullptr;
}
void WorkThread()
{
for (size_t i = 0; i != 128; ++i)
{
MemUnit *unit = Allocate();
if (unit != nullptr)
{
//do something use unit.m_data;
FreeMemUnit(unit);
}
}
}
int main()
{
InitMemPool(128, 1024);
std::vector<std::thread> allThreads;
for (size_t i = 0; i != 8; ++i)
{
std::thread t(WorkThread);
allThreads.push_back(std::move(t));
}
for (auto &t : allThreads)
{
t.join();
}
UninitMemPool();
return 0;
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T07:13:47.263",
"Id": "419289",
"Score": "1",
"body": "Please check your [initialization of the atomics](https://stackoverflow.com/questions/20453054/initialize-static-atomic-member-variable) to be correct. I don't know if it is, but there is usually some very weird stuff going on if done wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T13:01:08.637",
"Id": "419290",
"Score": "1",
"body": "@ThomasLang: the 3 `atomic<T>` variables are all pointer-sized or 32-bit, and have static storage duration. On normal C++ implementations (like x86 gcc or MSVC, or ARM, or whatever), they will be lock-free, and thus zero-initialization of their object representation will give correct behaviour. (As far as C++ language rules, yes, it's a good idea to make sure you init them correctly, but this doesn't explain any weirdness observed on real systems.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T01:44:11.507",
"Id": "419291",
"Score": "0",
"body": "@Peter Cordes: I have completed the code. Yes, i didn't observe anything weird. The program is just a practice and i can't guarantee it works as what i think(Some times it's really hard to find bugs behind lock-free codes). So i came here and wanted to known what others thinking about this(Yes, it's really like a code review)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T04:20:30.330",
"Id": "419294",
"Score": "0",
"body": "@Cody: nice edit! Typo: `aquery` -> `acquire` (I don't have 2k rep on this .SE to fix it myself.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T03:33:52.623",
"Id": "419807",
"Score": "0",
"body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T05:33:56.527",
"Id": "421748",
"Score": "0",
"body": "I think there is something wrong in Allocate. That is a store operation about 'fetch_add' , and the store maybe reorder after the next load. The right way is change both of the fetch_add and next load to be memory_order_seq_cst operation."
}
] | [
{
"body": "<blockquote>\n <p>'g_memStack' is a stack that contains memory unit. We can allocate\n memory unit from it</p>\n</blockquote>\n\n<p>There is not a single line of code allocating <code>MemUnit</code></p>\n\n<blockquote>\n <p>This a thread safe and lock-free memory pool program</p>\n</blockquote>\n\n<p>Unfortunately this is not true. Assume two threads are executing <code>Allocate</code> on an empty stack in a fully interleaved manner.</p>\n\n<pre><code>g_allocatingCounter.fetch_add(1, std::memory_order_relaxed); //T1 : 1, T2 : 2\nMemUnit *unit = g_memStack.load(std::memory_order_acquire); //T1 : nullptr, T2 : nullptr\nwhile (unit != nullptr && !g_memStack.compare_exchange_weak(unit, unit->m_next, std::memory_order_acquire, std::memory_order_acquire));\nif (g_allocatingCounter.load(std::memory_order_relaxed) == 1)\n{\n //let's assume its fine here\n return unit; // T1 : something\n}\ng_allocatingCounter.fetch_sub(1, std::memory_order_relaxed);\nreturn unit; //T2 : nullptr\n</code></pre>\n\n<p>They reach <code>if (g_allocatingCounter.load(std::memory_order_relaxed) == 1)</code> with the variable <code>unit</code> being null. The condition is true for one thread but not the other.</p>\n\n<p>The thread for which the condition is false will return <code>nullptr</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T01:55:20.807",
"Id": "419292",
"Score": "0",
"body": "Thanks for your reply. Yes, the function is allowed to return nullptr."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T04:19:22.043",
"Id": "419293",
"Score": "1",
"body": "For future readers: this was posted as an answer to the original question, before migration from Stack Overflow. That's why it doesn't look like a code review."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T08:33:23.330",
"Id": "216763",
"ParentId": "216762",
"Score": "3"
}
},
{
"body": "<h1>Includes and types</h1>\n<blockquote>\n<pre><code>std::atomic<uint32_t>\n</code></pre>\n</blockquote>\n<p>You need to include <code><stdint.h></code> for this type. Or better, include <code><cstdint></code> and use <code>std::uint32_t</code> instead; same for <code>std::uint8_t</code>. Similarly:</p>\n<blockquote>\n<pre><code>const size_t unitSize = sizeof(MemUnit) + blockSize;\n</code></pre>\n</blockquote>\n<p>Spell that <code>std::size_t</code>. Although implementations are <em>permitted</em> to add global-namespace versions of these identifiers, they are not <em>required</em> to, so relying on that is a portability issue waiting to bite.</p>\n<hr />\n<h1>Interface</h1>\n<p>It's not clear whether all the functions are intended to be part of the public interface. Certainly there are several which aren't directly needed by the test program, so perhaps they could be moved into an anonymous namespace?</p>\n<p>The naming of the functions is somewhat unconventional - it may well be worth re-reading the <code>std::allocator</code> interface to see what's expected.</p>\n<p><code>InitMemPool</code> and <code>UninitMemPool</code> look very much like they should be an allocator's constructor and destructor, respectively. As free functions, they are vulnerable to misuse (e.g. calling either of them more than once, or using <code>Allocate()</code> before init or after uninit).</p>\n<hr />\n<h1>Use of <code>std::atomic</code></h1>\n<p>I haven't fully audited the memory barriers here, and it's less my area of expertise, so I'm hoping another reviewer will give that some scrutiny.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T03:36:54.133",
"Id": "419811",
"Score": "0",
"body": "Thanks for your code review"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:37:02.450",
"Id": "216785",
"ParentId": "216762",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216763",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T05:25:16.263",
"Id": "216762",
"Score": "9",
"Tags": [
"c++",
"c++11",
"lock-free"
],
"Title": "Creating a lock-free memory pool using C++11 features"
} | 216762 |
<h1>Improve Request to Reduce Queries</h1>
<p>I have a web application, where users can upload Documents or Emails, to what I call a Strema. The users can then define document fields email fields to the stream, that each document/email will inherit. The users can then furthermore apply parsing rules to these fields, that each document/email will be parsed after.</p>
<p>Now let's take the example, that an user uploads a new document. (I have hardcoded the ID's for simplicty).</p>
<pre><code>$stream = Stream::find(1);
$document = Document::find(2);
$parsing = new ApplyParsingRules;
$document->storeContent($parsing->parse($stream, $document));
</code></pre>
<p>Below is the function that parses the document according to the parsing rules:</p>
<pre><code> public function parse(Stream $stream, DataTypeInterface $data) : array
{
//Get the rules.
$rules = $data->rules();
$result = [];
foreach ($rules as $rule) {
$result[] = [
'field_rule_id' => $rule->id,
'content' => 'something something',
'typeable_id' => $data->id,
];
}
return $result;
}
</code></pre>
<p>So above basically just returns an array of the parsed text.</p>
<p>Now as you probably can see, I use an <code>interface $DataTypeInterface</code>. This is because the parse function can accept both Documents and Emails.</p>
<p>To get the rules, I use this code:</p>
<pre><code>//Get the rules.
$rules = $data->rules();
</code></pre>
<p>The method looks like this:</p>
<pre><code>class Document extends Model implements DataTypeInterface
{
public function stream()
{
return $this->belongsTo(Stream::class);
}
public function rules() : object
{
return FieldRule::where([
['stream_id', '=', $this->stream->id],
['fieldable_type', '=', 'App\DocumentField'],
])->get();
}
}
</code></pre>
<p>This will query the database, for all the rules that is associated with <code>Document Fields</code> and the fields, that is associated with the specific <code>Stream</code>.</p>
<p>Last, in my first request, I had this:</p>
<pre><code>$document->storeContent($parsing->parse($stream, $document));
</code></pre>
<p>The <code>storeContent</code> method looks like this:</p>
<pre><code>class Document extends Model implements DataTypeInterface
{
// A document will have many field rule results.
public function results()
{
return $this->morphMany(FieldRuleResult::class, 'typeable');
}
// Persist the parsed content to the database.
public function storeContent(array $parsed) : object
{
foreach ($parsed as $parse) {
$this->results()->updateOrCreate(
[
'field_rule_id' => $parse['field_rule_id'],
'typeable_id' => $parse['typeable_id'],
],
$parse
);
}
return $this;
}
}
</code></pre>
<p>As you can probably imagine, everytime a document gets parsed, it will create be parsed by some specific rules. These rules will all generate a result, thus I am saving each result in the database, using the <code>storeContent</code> method.</p>
<p>However, this will also generate a query <strong>for each</strong> result.</p>
<p>One thing to note: <strong>I am using the <code>updateOrCreate</code></strong> method to store the field results, because I only want to persist <strong>new</strong> results to the database. All results where the content was just updated, I want to update the existing row in the database.</p>
<p>For reference, above request generates below <strong>8</strong> queries:</p>
<pre><code>select * from `streams` where `streams`.`id` = ? limit 1
select * from `documents` where `documents`.`id` = ? limit 1
select * from `streams` where `streams`.`id` = ? limit 1
select * from `field_rules` where (`stream_id` = ? and `fieldable_type` = ?)
select * from `field_rule_results` where `field_rule_results`.`typeable_id` = ? and...
select * from `field_rule_results` where `field_rule_results`.`typeable_id` = ? and...
insert into `field_rule_results` (`field_rule_id`, `typeable_id`, `typeable_type`, `content`, `updated_at`, `created_at`) values (..)
insert into `field_rule_results` (`field_rule_id`, `typeable_id`, `typeable_type`, `content`, `updated_at`, `created_at`) values (..)
</code></pre>
<p>Above works fine - but seems a bit heavy, and I can imagine once my users starts to generate a lot of rules/results, this will be a problem.</p>
<p><strong>Is there any way that I can optimize/refactor above setup?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T07:10:51.263",
"Id": "419727",
"Score": "0",
"body": "One of the (implicit?) rules of CodeReview is that you post working code in your question. You've posted, more-or-less, abstract code. Now I can fully understand why you did this, but it makes your question quite hard to answer. Lots of details are missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:41:45.820",
"Id": "419890",
"Score": "0",
"body": "\"_to what I call a Strema_\" - did you intend to type the word _stream_ instead of _Strema_?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:46:47.420",
"Id": "420389",
"Score": "0",
"body": "`updateOrCreate` method will trigger a `select` query first in order to figure out whether it should do an `insert` or an `update` query. another way _could_ be doing an `insert` with ON DUPLICATE KEY UPDATE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-28T14:52:54.090",
"Id": "462976",
"Score": "0",
"body": "You could probably eliminate a lot of select queries using joins."
}
] | [
{
"body": "<p>This is not a complete answer, but it is too long to put in a comment, so I placed it here.</p>\n\n<p>I read your question, and given that it is unclear what the overall purpose of this code is (what kind of rules?), that's not easy. As far as I can tell there's <strong>no easy way</strong> to reduce the load on the database. Most queries simply have to be done. </p>\n\n<p>That said: The best ways to unload a database are:</p>\n\n<ul>\n<li>Get all the rows you need in one request.</li>\n<li>Don't update what hasn't changed (obviously).</li>\n<li>Do all inserts with one query (up to a certain amount of rows).</li>\n</ul>\n\n<p>Can this be applied to your code? </p>\n\n<p>I think that <code>Document::storeContent()</code> is an good method to start with, because the last two points, I mentioned above, apply to it. You do an <code>updateOrCreate()</code> for each rule result, generating two queries for each result.</p>\n\n<p>What you could do is make this more efficient by handling all the rules in a few queries, like this:</p>\n\n<ol>\n<li>Store the new results of the rules in a variable: <code>$newResults = $this->results();</code></li>\n<li>Read all existing results rows from the database with one query: <code>$oldResults = $this->\"read database()\";</code></li>\n<li>Compare these two results and: A. Eliminate what hasn't changed. B. Update what needs updating. C. Insert, with one query, all new results.</li>\n</ol>\n\n<p>It is very hard for me to give you real code examples, given the abstract nature of the code you've given, but I don't think it is beyond your capabilities to implement the above algorithm. I think a new 'rules' class, that encapsulates this behavior, would be appropriate.</p>\n\n<p>This way you assure that, when a new parse is done, only those queries are executed that are really necessary. You should, of course, never parse a document or email unnecessarily. </p>\n\n<p>I hope this helps a bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-07T06:55:20.167",
"Id": "217000",
"ParentId": "216766",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217000",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T07:01:53.487",
"Id": "216766",
"Score": "1",
"Tags": [
"php",
"laravel",
"eloquent"
],
"Title": "PHP Laravel - Improving and refactoring code to Reduce Queries"
} | 216766 |
<h2>About the Program</h2>
<p>It's a simple implementation of Observer Pattern.</p>
<p>The choice of different <code>NotifyMethod</code> will affect how those observers are notified. The <code>SimpleNotify</code> in blow just uses a simple for loop.</p>
<p>The concrete Observer is initialized with a concrete Observable that it want to observe. In the blow program concrete Observer = <code>Reader</code>, and concrete Observable = <code>Bookstore</code>.</p>
<h2>Some Problems I've Noticed in the Program</h2>
<ol>
<li><p>A <code>Bookstore</code> instance is initialized with a <code>NotifyMethod</code> instance, however to enable dynamic changing of <code>NotifyMethod</code> one have to "move" those readers from old method to new method.</p></li>
<li><p>To make a class <code>Observable</code>, one has to modify the class (constructor, Observable's contracts), is it possible to make a <code>Bookstore</code> instance unaware of that it's being observed? i.e. How to design a class which can be changed from observable to not observable at runtime? Or this isn't an issue?</p></li>
<li><p>The <code>Observer</code> interface is <code>update()</code> without any arguments, so when implementing concrete Observer it has to keep a reference to a concrete Observable(<code>Bookstore</code> in this case), and access the <code>Bookstore</code>'s data by public interface. Is this a good idea? What's the drawback of this?</p></li>
</ol>
<h2>The Feature I want</h2>
<p>From the current Observer interface, an concrete Observer can't observer multiple observables:</p>
<pre><code>Person implements
BookstoreObserver, StockmarketObserver, ... {
bookstoreUpdate() { ... }
stockmarketUpdate() { ... }
...
}
</code></pre>
<p>If there are multiple <code>Observer</code> interface then the update logic of each concrete Observable won't be lumped into the only one <code>update()</code> if only one <code>Observer</code> interface. Is this a good idea?</p>
<p>Finally, is it a good idea to make <code>Reader</code> delegate its job to observe the <code>Bookstore</code> instance to an <code>Observer</code>? i.e. The <code>Reader</code> also use composition like <code>Bookstore</code> in the below program to achieve its <code>Observer</code> effect?</p>
<hr>
<h2>The UML</h2>
<p>Sorry for not showing much details, I used BlueJ and it can't show the interface/public methods of classes, but the code below is rather simple.</p>
<p><a href="https://i.stack.imgur.com/PAzTE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PAzTE.png" alt="UML of Single Observable - Observer Pattern"></a></p>
<p>A typical Observer Pattern for reference.
<a href="https://i.stack.imgur.com/Pwkz3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pwkz3.png" alt="Standard Observer Pattern"></a></p>
<h2>Code</h2>
<pre><code>public interface Observable
{
public void register(Observer o);
public void unregister(Observer o);
public void sendNews();
}
</code></pre>
<pre><code>public interface NotifyMethod extends Observable
{}
</code></pre>
<pre><code>/**
* Use a simple for-each loop to send news to observers.
*/
public class SimpleNotify implements NotifyMethod
{
private List<Observer> observers = new ArrayList<Observer>();
public void register(Observer o) {
observers.add(o);
}
public void unregister(Observer o) {
observers.remove(o);
}
public void sendNews() {
for (Observer observer: observers) {
observer.update();
}
}
}
</code></pre>
<pre><code>/**
* An observable bookstore.
*/
public class Bookstore implements Observable
{
private NotifyMethod notificationMethod;
private Book newBook;
//
public Bookstore(NotifyMethod notificationMethod) {
this.notificationMethod = notificationMethod;
}
public void publishNewBook(Book newBook) {
this.newBook = newBook;
sendNews();
}
public Book getNewBook() {
return newBook;
}
//
public void register(Observer o) {
notificationMethod.register(o);
}
public void unregister(Observer o) {
notificationMethod.unregister(o);
}
public void sendNews() {
notificationMethod.sendNews();
}
}
</code></pre>
<pre><code>/**
* Book = "Title - Author"
*/
public class Book
{
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
}
</code></pre>
<pre><code>public interface Observer
{
public void update();
}
</code></pre>
<pre><code>/**
* A Reader wants to observe the bookstore's news.
*/
public class Reader implements Observer
{
private String name;
private Bookstore bookstore;
//
public Reader(String name, Bookstore bookstore) {
this.name = name;
this.bookstore = bookstore;
bookstore.register(this);
}
public void update() {
System.out.format("Reader %s receives a book news \"%s - %s\"%n",
name,
bookstore.getNewBook().getTitle(),
bookstore.getNewBook().getAuthor());
}
}
</code></pre>
<h2>Main Program and Output</h2>
<pre><code>public class Main
{
public static void main(String[] args) {
Bookstore myBookstore = new Bookstore(new SimpleNotify());
Reader MrA = new Reader("Mr.A", myBookstore);
Reader MrB = new Reader("Mr.B", myBookstore);
myBookstore.publishNewBook(new Book("Alice in Wonderland", "Lewis Carroll"));
}
}
</code></pre>
<pre class="lang-none prettyprint-override"><code>Reader Mr.A receives a book news "Alice in Wonderland - Lewis Carroll"
Reader Mr.B receives a book news "Alice in Wonderland - Lewis Carroll"
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T10:12:27.690",
"Id": "419323",
"Score": "0",
"body": "are you aware of existence of [java-rx](https://www.baeldung.com/rx-java)? This is already implemented"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T10:17:29.313",
"Id": "419324",
"Score": "0",
"body": "@KrzysztofSkowronek: So my questions are impossible to be solved without the library?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T10:23:37.767",
"Id": "419325",
"Score": "0",
"body": "of course they are, but after answering them you will have next ones, and next ones, and they are all already implemented. Rx has multiple observers, broadcast, timing synchronization, buffering, windowing, thread marshaling etc. It's like \"I want 10 objects in one variable, how can I improve this Array class?\" -> use ArrayList from Java. There is no need for reinventing the wheel, especially that Rx is far more powerfull: you have built in also filtering, mapping notifications, sorting, counting, timers etc. Stand on the shoulders of giants instead of digging a hole :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T10:26:58.753",
"Id": "419327",
"Score": "2",
"body": "@KrzysztofSkowronek: I understand what you want to convey, but I'm just interested about the mechanism behind it, I'm learning about observer pattern and I have many questions about it. If you think my question is inappropriate here I can delete it later, but I thought I can learn from the answer(s) to my questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T11:03:08.220",
"Id": "419330",
"Score": "0",
"body": "@KrzysztofSkowronek: Thank you very much"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T10:46:05.160",
"Id": "421025",
"Score": "0",
"body": "If you have questions about the observer pattern instead of looking for a review of your code, you might be more interested in [Software Engineering](https://softwareengineering.stackexchange.com/help/on-topic) instead."
}
] | [
{
"body": "<p>As I said in comments, take a look at Java-Rx, or any Rx implementation, they are almost the same in almost all languages. </p>\n\n<p>First of all, both <code>IObservable</code> and <code>IObserver</code> should be generic, where the type is type of the message in notification:</p>\n\n<pre><code>public interface Observable<T>\n{\n public void register(Observer<T> o);\n public void unregister(Observer<T> o);\n public void sendNews(T msg);\n}\n\npublic interface Observer<T>\n{\n public void nextNews(T msg);\n public void finished(); // called when Observable knows it will not produce anymore\n public void error(Exception ex); // for error handling\n}\n</code></pre>\n\n<p>Now, when observer is registered, observable can send to it full message, so it does not need a reference back to observable. Observable only stores a list of registered observers and when it emits something, it does:</p>\n\n<pre><code>// registration\nObserver<Book> r = new Reader();\nbookstore.register(r); // this adds r to the bookstore._registeredObservers\n\nvoid sendNews(T msg)\n{\n foreach(T i in _registeredObservers) // _registeredObservers : ArrayList<IObserver<T>>\n i.nextNews(msg);\n}\n</code></pre>\n\n<p>In your example Bookstore could be <code>Observable<BookOperation></code>, and book operation could be:</p>\n\n<pre><code>// pseudo code, I don't really know Java\n\n class BookOperation\n{\n public Book book;\n public Operation operation; // this is enum: New, Removed, etc\n}\n</code></pre>\n\n<p>Or, Bookstore could be just a class with members:</p>\n\n<pre><code>Bookstore.BookAdded : Observable<Book>\nBookstore.BookRemoved : Observable<Book>\n</code></pre>\n\n<p>In Rx in most cases you don't really implement Observers, you use register overload that takes lambas.</p>\n\n<p>Real Observers are mostly implemented as operators: observers that are also observables.</p>\n\n<p>For example, <code>observable.filter(x => x > 5)</code> will return another observable, but only with elements from the first one that are greater than 5.</p>\n\n<p>This approach would also let you do:</p>\n\n<pre><code>Reader r = new Reader();\n\nobs1.register(r);\nobs2.register(r); // one reader observes two obervables\n</code></pre>\n\n<p>Also, when observer is done, it should uregister - this is managed via <code>IDisposable</code> interface in C#, I'm pretty sure that there is something similar in Java.</p>\n\n<p>This answers all 3 of your questions, I hope. </p>\n\n<p>Now, my coffee is empty, so if you have further questions, I will try to answer them later :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T10:57:44.020",
"Id": "216773",
"ParentId": "216767",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T08:24:43.270",
"Id": "216767",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"observer-pattern"
],
"Title": "How to observe multiple Observables?"
} | 216767 |
<p>I am trying to create a Repository & UnitOfWork for Data Access Layer. In my current implementation I have to modify my UnitOfWork everytime I create a new repository. I would like to avoid that and also keep the functionality to extend my repository abstract class.</p>
<p>Following is my generic Repository & UnitOfWork interface & classes</p>
<pre><code> public interface IRepositoryBase<T> where T : class
{
IList<T> FindAll();
T FindByCondition(Expression<Func<T, bool>> expression);
void Create(T entity);
void Update(T entity);
void Delete(T entity);
}
public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class
{
protected DBContext _dbContext { get; set; }
public RepositoryBase(DBContext dbContext)
{
_dbContext = dbContext;
}
//other methods removed
public void Create(T entity)
{
_dbContext.Set<T>().Add(entity);
}
}
public interface IUnitOfWork
{
IReminderRepository Reminder { get; }
void Save();
}
public class UnitOfWork : IUnitOfWork, IDisposable
{
private IReminderRepository _reminderRepository;
public UnitOfWork(DBContext dbContext)
{
_dbContext = dbContext;
}
public IReminderRepository Reminder
{
get
{
return _reminderRepository = _reminderRepository ?? new ReminderRepository(_dbContext);
}
}
public void Save()
{
_dbContext.SaveChanges();
}
public void Dispose()
{
_dbContext.Dispose();
}
}
</code></pre>
<p>Here I can extend my Repository as per my specific needs by implementing the specific Repository as</p>
<pre><code>public interface IReminderRepository : IRepositoryBase<Reminder>
{
IList<Reminder> GetAllReminders();
Reminder GetReminderById(Guid id);
Reminder GetReminderByName(string name);
void CreateReminder(Reminder reminder);
void UpdateReminder(Reminder reminder);
void DeleteReminder(Reminder reminder);
}
public class ReminderRepository : RepositoryBase<Reminder>, IReminderRepository
{
public ReminderRepository(DBContext dbContext)
: base(dbContext)
{
_dbContext = dbContext;
}
//other methods removed
public Reminder GetReminderByName(string name)
{
return FindAll()
.OrderByDescending(r => r.Name)
.FirstOrDefault(r => r.Name == name);
//return FindByCondition(r => r.Name == name);
}
}
</code></pre>
<p>This is ok but when ever I will create a new Specific Repository I will have to modify the UnitOfWork class as well by adding a new property for the new Repository.</p>
<p>While searching online I found following but it does not work in my case as my RepositoryBase is an abstract class. </p>
<pre><code> public interface IUnitOfWork : IDisposable
{
Dictionary<Type, object> _repositories;
void Save();
}
public class UnitOfWork : IUnitOfWork
{
private readonly DBContext _dbContext { get; set; }
private readonly Dictionary<Type, object> _repositories = new Dictionary<Type, object>();
public Dictionary<Type, object> Repositories
{
get { return _repositories; }
set { Repositories = value; }
}
public UnitOfWork(DBContext dbContext)
{
_dbContext = dbContext;
}
public IRepositoryBase<T> Repository<T>() where T : class
{
if (Repositories.Keys.Contains(typeof(T)))
{
return Repositories[typeof(T)] as IRepositoryBase<T>;
}
IRepositoryBase<T> repo = new RepositoryBase<T>(_dbContext);//This does not work
Repositories.Add(typeof(T), repo);
return repo;
}
public void Save()
{
_dbContext.SaveChanges();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:35:25.750",
"Id": "420272",
"Score": "0",
"body": "Please don't edit your code after having received an answer. This violates the question-and-answer style of the site. If you think that your code needs more review, just post a follow-up question, linking back to this one. Have a look at our [help center](https://codereview.stackexchange.com/help/someone-answers) for more information about what you can and cannot do after having received an answer."
}
] | [
{
"body": "<h2>Unneeded complexity</h2>\n\n<p>There is unnecessary complexity because of two reasons: the unit of work wants to be a <strong>repository locator</strong> and because the repositories are <strong>generic</strong> on the wrong side.</p>\n\n<p>Remove the repositories references from the <code>UoW</code> and you will be fine. Let's see now a way to have a better generic way for your CRUD.</p>\n\n<pre><code>public interface IRepositoryBase\n{\n IList<T> FindAll<T>();\n T FindByCondition<T>(Expression<Func<T, bool>> expression);\n void Create<T>(T entity);\n void Update<T>(T entity);\n void Delete<T>(T entity);\n}\n</code></pre>\n\n<p>So what did I just do here was to make the interface non-generic and move the generic type to the methods. Imagine now how easy is to do following</p>\n\n<pre><code> public class RemindersService\n {\n private readonly IRepositoryBase _repository;\n private readonly IUnitOfWork _unitOfWork;\n public RemindersService(IRepositoryBase repository, IUnitOfWork uow) \n { \n _repository = repository; \n _uow = uow\n }\n\n public Reminder AddNewReminder(DateTime moment, string note, Guid receiver, string name)\n {\n var user = _repository.FindById(receiver);\n var reminder = new Reminder {ReceiverId = receiver, Moment = momoent, Note = note };\n _repository.Create(reminder);\n\n _uow.Save();\n }\n }\n</code></pre>\n\n<p>The main gain here is for very simplistic CRUD operations you don't need to create an interface and an implementation for each of entity in the DbContext.</p>\n\n<p>The downside of this approach is that now suddenly all the entities will have this generic way for the CRUD operations. Maybe you don't what that, but I consider this a non-issue in most of the applications. One potential issue is when you want to implement here and there let's say a soft-delete and the generic method does a hard delete. There are ways to overcome that.</p>\n\n<h2>Use the valuable API from DbContext</h2>\n\n<p>I used in the <code>RemindersService.AddNewReminder</code> a new method, <code>FindById</code>, that was not in the original <code>IRepositoryBase</code> definition. This can be easily added and dispatched to <code>dbContext.Find(id)</code>. This method returns so you'll probably have to check for that in your Application Services.</p>\n\n<h2>Simplify abstractions, remove duplication</h2>\n\n<p>Let's move next to the more specific repository. With the non-generic <code>IRepositoryBase</code> it will look like this:</p>\n\n<pre><code>public interface IReminderRepository : IRepositoryBase\n {\n IList<Reminder> GetAllReminders();\n Reminder GetReminderById(Guid id); \n Reminder GetReminderByName(string name); \n void CreateReminder(Reminder reminder); \n void UpdateReminder(Reminder reminder); \n void DeleteReminder(Reminder reminder); \n }\n</code></pre>\n\n<p>The first issue with this interface is the abstraction duplication: you have two ways to create a Reminder: <code>CreateReminder</code> and <code>Create<Reminder></code> (or Create in the original). Same for Update, Delete and for FindAll. As an API consumer I would have a hard time to pick one because I will feel insecure about the fact I might have picked the wrong one. As an Implementation developer I will have to implement the same functionality twice or to just delegate to the base class.</p>\n\n<p>You have two options: either remove the interface inheritance or remove the the <code>CreateReminder</code>. If you remove the inheritance and keep the <code>CreateXXX</code> methods then you transmit the idea that the those <code>XXX</code>s are not handled as everything else by the repository, but the have a custom logic. I doubt that, since the repositories need to take care only for the store access. So remove these methods and let only the <code>GetByName</code> in the <code>IReminderRepository</code>. You might also decide to remove the interface inheritance and <code>IRepositoryBase<Reminder></code> when you need those generic methods and <code>IReminderRepository</code> when you need the <code>GetByName</code> method.</p>\n\n<p>Like I said you don't need to tie the UoW with the repositories interfaces. Follow this convention with the Repository suffix and you'll be fine to discover the repositories you need. Once you have that, there is no need to transform the UoW into a ServiceLocator - Repositories Factory.</p>\n\n<h2>Avoid newing dependencies</h2>\n\n<p>Which brings the next: use an <code>IoC</code> for you dependencies. .Net Core? - built in. .Net Framework: a bunch of them. Still WebForms? Use Property Injection. </p>\n\n<h2>Avoid disposing what you didn't create</h2>\n\n<pre><code>public class UnitOfWork : IUnitOfWork, IDisposable\n</code></pre>\n\n<p>Did UnitOfWork create the DbContext? Then don't dispose. Let the creator of the DbContext to decide when and if wants to dispose it.</p>\n\n<h2>Naming:</h2>\n\n<pre><code>void Create(T entity);\nvoid Update(T entity);\nvoid Delete(T entity);\n</code></pre>\n\n<p>It's a repository, by defintion: <em>Mediates between the domain and data mapping layers using a <strong>collection-like</strong> interface for accessing domain objects.</em>\nTake a look at the <code>IList</code> API and you'll find better naming:</p>\n\n<pre><code>void Add(T entity);\nvoid Remove(T entity);\n</code></pre>\n\n<p>A list doesn't have an <em>Update</em> method so frankly you don't need this method because of this:</p>\n\n<pre><code>{\n var reminder = _repository.FindById(reminderId);\n reminder.AddNote(note); // probably AddNote will do something like this.Notes.Add(note);\n uow.Save();\n}\n</code></pre>\n\n<p>See? No <code>Update</code> method. The <code>DbContext</code> takes care of the changes made to the returned reminder and will commit them when <code>uow.Save</code> is called.</p>\n\n<h2>Async - Await</h2>\n\n<p>Use this API as EntityFramework provides the asynchronous way to handle the databases. You'll be scalable, your threads you will be free to do something else (like handling new requests) and won't be blocked until the SQL Server decides to returns its results.</p>\n\n<h2>Big performance issue</h2>\n\n<pre><code>public class ReminderRepository : RepositoryBase<Reminder>, IReminderRepository\n{\n public ReminderRepository(DBContext dbContext)\n : base(dbContext)\n {\n _dbContext = dbContext;\n }\n //other methods removed\n public Reminder GetReminderByName(string name)\n {\n return FindAll()\n .OrderByDescending(r => r.Name)\n .FirstOrDefault(r => r.Name == name);\n\n //return FindByCondition(r => r.Name == name);\n }\n}\n</code></pre>\n\n<p>The <code>FindAll</code> returns an <code>IList</code> which means the <code>DbContext</code> will send the query to the SQL server and then will map the results to the Reminder objects. After that the <code>ReminderRepository</code> object will search this in memory collection for the first reminder. What if you have 100.000 reminders? Probably you don't want to do that, but to generate the SQL that will have in it the WHERE clause. So avoid ToList().FirstOrDefault() or any indirection to that if you know you will need just a subset of these records/objects.</p>\n\n<h2>More about API</h2>\n\n<pre><code>IList<T> FindAll();\n</code></pre>\n\n<p>IList has methods like Remove, Clear etc. Most likely the repository clients won't need that and even if they use them, the outcome won't be the expected one. The FindAll should return something that with they can only iterate/read. So use <code>IReadonlyCollection</code>.</p>\n\n<h2>How generic should be?</h2>\n\n<p>The <code>FindByCondition</code> has the drawback that you'll lose some encapsulation and abstraction and you open the gate for code duplication. I personally like it, but if I see that I tend to copy the predicate in a new place, then I'll add a new method in the repository, like you just did with <code>FindByName</code>. People are usually lazy (including myself) and sooner or later you'll get in trouble with it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T10:00:06.440",
"Id": "420231",
"Score": "0",
"body": "1) When u made IRepositoryBase interface non-generic then how will this interface compile as T is not defined anywhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T11:53:45.477",
"Id": "420237",
"Score": "0",
"body": "Welcome, see that I move the T into the methods"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:06:03.483",
"Id": "420263",
"Score": "0",
"body": "2) In RemindersService if I have IRepositoryBase repository then I can't access GetReminderByName so I am assuming that I need to pass IReminderRepository repository"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:26:02.020",
"Id": "420265",
"Score": "0",
"body": "As this is just a sample ASP.NET core project so using the built in IoC. Also I have in my task list to make repository also support async but first I wanted the implementation to be in a good shape. I have made few changes based on ur suggestions, can u plz take a look."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:31:16.887",
"Id": "420266",
"Score": "0",
"body": "3) Regarding naming I understood that I can use better names but I don't understood why not to have Update. What if I need to update the Description of a Reminder. I know in certain cases I can do Delete & Add instead of Update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:45:38.510",
"Id": "420268",
"Score": "0",
"body": "4) I don't know why I wrote FindAll.condition in GetReminderByName, It is supposed to return a single record and should have used FindByCondition which I have commented. On the other hand if I have scenario where I need to return a list based on some condition then would u suggest using IQueryable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T19:17:18.290",
"Id": "420318",
"Score": "0",
"body": "2. Yes, but if IReminderRepository inherits IRepositoryBase, then you don't need to. 3. In my replace reminder.AddNote(note); with reminder.Description = description and that's it, the reminder is updated in the database on uow.Save(). 4. Don't return IQueryable, encapsulate the query and return the list as an IReadonlyCollection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T01:18:26.560",
"Id": "439509",
"Score": "0",
"body": "@Adriad, 1)When you move the generic type to the methods of repository, you will need to call \"_dbContext.Set<T>()\" in every repository method so it can effect the performance in a bad way. Am I right? ( But you can call \"_dbContext.Set<T>()\" in constructor if you made generic repository class )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-16T08:15:15.630",
"Id": "439563",
"Score": "0",
"body": "Performance can be measured, but I doubt there would be any differences"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T21:31:28.573",
"Id": "217160",
"ParentId": "216768",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T08:25:40.957",
"Id": "216768",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"entity-framework"
],
"Title": "Generic UnitOfWork"
} | 216768 |
<p>I have a sniffer tool which populates my DB with data found after parsing the packets and filling them in. Since each row in my table deals with one packet, I had to make a procedure that provides the correlation between packets. I fill that using the <code>stream_index</code> column.</p>
<pre><code>+--------------+------------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| src_ip | int(10) unsigned | YES | | NULL | |
| dst_ip | int(10) unsigned | YES | | NULL | |
| src_port | int(10) | YES | | NULL | |
| dst_port | int(10) | YES | | NULL | |
| data | int(11) | YES | | NULL | |
| Created | datetime | NO | MUL | CURRENT_TIMESTAMP | |
| smalicious | int(10) | YES | | NULL | |
| sgeoLoc | int(11) | YES | | NULL | |
| seq | int(10) unsigned | YES | | NULL | |
| app_id | int(11) | YES | | NULL | |
| tcp_flag | varchar(25) | YES | | NULL | |
| dgeoLoc | int(11) | YES | | NULL | |
| dmalicious | int(10) | YES | | NULL | |
| conn_state | int(11) | YES | | NULL | |
| src_mac | varchar(20) | YES | | NULL | |
| dst_mac | varchar(20) | YES | | NULL | |
| seq_num | varchar(25) | YES | | NULL | |
| ack_num | varchar(25) | YES | | NULL | |
| protocol | int(3) | YES | | NULL | |
| app | varchar(300) | YES | | NULL | |
| app_sub | varchar(300) | YES | | NULL | |
| source_user | text | YES | | NULL | |
| stream_index | int(11) | YES | | NULL | |
+--------------+------------------+------+-----+-------------------+----------------+
</code></pre>
<p>And here is my code that fills up the <code>stream_index</code> data inside the Database:</p>
<pre><code>import mysql.connector
import re
import AuthDB
import random
def fetch_stream():
cnx = mysql.connector.connect(**AuthDB.config)
cursor = cnx.cursor(buffered=True)
query_get = "select * from user_activity_load where protocol = 6 and tcp_flag = 'SYN' and stream_index is NULL or protocol = 17 and stream_index is NULL limit 100"
cursor.execute(query_get)
row_data = cursor.fetchone()
while row_data is not None:
print(row_data)
ip1 = row_data[1]
ip2 = row_data[2]
port1 = row_data[3]
port2 = row_data[4]
seq = row_data[17]
seq_num = ' '.join(seq.split(' ')[:2])
protocol = row_data[19]
if protocol == 6:
get_tcp_stream(ip1, ip2, port1, port2, seq_num)
elif protocol == 17:
get_udp_stream(ip1, ip2, port1, port2)
row_data = cursor.fetchone()
cursor.close()
cnx.close()
def get_tcp_stream(ip1,ip2,port1,port2,seq):
id_list = []
cnx = mysql.connector.connect(**AuthDB.config)
cursor = cnx.cursor(buffered=True)
query_get = "select * from user_activity_load where src_ip ='"+str(ip1)+"' and dst_ip = '"+str(ip2)+"' and src_port = "+str(port1)+" and dst_port = "+str(port2)+" and seq_num like '"+seq+"%' or dst_ip ='"+str(ip1)+"' and src_ip = '"+str(ip2)+"' and dst_port = "+str(port1)+" and src_port = "+str(port2)+" and ack_num like '"+seq+"%'"
cursor.execute(query_get)
row_data = cursor.fetchone()
while row_data is not None:
print(row_data)
id_list.append(row_data[0])
row_data = cursor.fetchone()
update_index(id_list)
cursor.close()
cnx.close()
def get_udp_stream(ip1,ip2,port1,port2):
id_list = []
cnx = mysql.connector.connect(**AuthDB.config)
cursor = cnx.cursor(buffered=True)
query_get = "select * from user_activity_load where src_ip ='"+str(ip1)+"' and dst_ip = '"+str(ip2)+"' and src_port = "+str(port1)+" and dst_port = "+str(port2)+" or dst_ip ='"+str(ip1)+"' and src_ip = '"+str(ip2)+"' and dst_port = "+str(port1)+" and src_port = "+str(port2)
print(query_get)
cursor.execute(query_get)
row_data = cursor.fetchone()
while row_data is not None:
print(row_data)
id_list.append(row_data[0])
row_data = cursor.fetchone()
update_index(id_list)
cursor.close()
cnx.close()
def update_index(id_list):
index = random.randint(1, 100000000)
cnx = mysql.connector.connect(**AuthDB.config)
cursor = cnx.cursor(buffered=True)
for row_id in id_list:
query_insert = "update user_activity_load set stream_index = "+str(index)+" where id = "+str(row_id)
cursor.execute(query_insert)
cnx.commit()
cursor.close()
cnx.close()
fetch_stream()
</code></pre>
<p>There's a separate code that fills out the rest of the values in the table but that is not of my concern right now. This works fine for both TCP and UDP packets but I think the quality of the code can be improved. </p>
<p>I'd kindly ask you to review so as to bring light upon how the quality of this can be improved and make it better, faster and more optimised. Thanks in advance</p>
| [] | [
{
"body": "<p>First things first, always have an entry point with your Python code - </p>\n\n<pre><code>if __name__ == \"__main__\":\n fetch_stream()\n</code></pre>\n\n<p>As this will allow code documenting tools to auto-generate documents without executing your code (and it's obvious where your code runs from for other developers).<br>\nNext, I see lots of code duplication (DRY/Don't repeat yourself), it's important to extract all these into their own separate functions, for instance, you open and close the database connection a few times, which is expensive. Let's extract that out, and make the db an injectable parameter: </p>\n\n<pre><code>def open_database():\n return mysql.connector.connect(**AuthDB.config)\n\n def fetch_stream(db):\n cursor = db.cursor(buffered=True)\n # ....\n\nif __name__ == \"__main__\":\n db = open_database()\n fetch_stream(db)\n db.close()\n</code></pre>\n\n<p>However, now looking across all the functions, we can see that the cursor creation is the same, and we also see the same pattern - create cursor, run query, get results - yet you have code which manipulates the data per-database row - this too is an expensive process because you can tie up the database memory holding your query results, and you perform <code>fetch_one()</code> operations instead of a <code>fetch_all()</code> operation. </p>\n\n<p>Unfortunately my suggestions will now break your existing code structure - but let's continue. We extract the database query process into a faster method (Python2 map returns a list automatically, Python3 we need to wrap the map with a list): </p>\n\n<pre><code>def execute_query(db, query):\n cursor = db.cursor(buffered=True)\n cursor.execute(query)\n results = cursor.fetch_all()\n col_names = [column[0] for column in cursor.description]\n rows_dict = list(map(lambda row: dict(zip(col_names, row)), results))\n cursor.close()\n return rows_dict\n</code></pre>\n\n<p>We now have a function which will grab the data quickly and return an object which is easily iterated. This would result in a change to your <code>fetch_stream()</code> function, into something like this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n db = open_database()\n query = \"SELECT * FROM user_activity_load WHERE protocol = 6 AND tcp_flag = 'SYN' AND stream_index IS NULL OR protocol = 17 AND stream_index IS NULL LIMIT 100\"\n all_user_activity_load = execute_query(db, query)\n</code></pre>\n\n<p>This is important to bring the query out of the function, because having \"magic numbers\" and SQL queries inside functions violates the Open/Close Principal - being that your code should be Open for extension but Closed for modification. \nDatabase structures will always change, and if you want to modify the query to get different columns instead - you'd have to open up the code and edit the code, then run it again to see if it resulted in your expected outcome, correct?<br>\nThat means you're always modifying the code and you might make a mistake and push to production, etc. We have S.O.L.I.D as it's a way of writing code to avoid common pitfalls. So, you can see we've moved the query out of the function, and make it an injectable parameter into <code>execute_query()</code>. Personally, I'd have the queries in an .ini file, and load them based on section heading. That way the code can be deployed as read-only, but other IT people can edit the .ini file to modify the query if the database changes.</p>\n\n<p>Of course, the <code>fetch_stream()</code> function is now broken completely. Looking at that function, it iterates through the initial results, and separates TCP and UDP based on protocol. Given we now have names for each field in the dictionary from the <code>execute_query()</code> function, we can easily filter the original results into a new list:</p>\n\n<pre><code>def filter_by_protocol(results, protocol_number):\n return [x for x in results if x['protocol'] == protocol_number]\n</code></pre>\n\n<p>So you'd filter those based on protocol == 6 for the TCP etc. with a set of lines like:</p>\n\n<pre><code>all_user_activity_load = execute_query(db, query)\ntcp_results = filter_by_protocol(all_user_activity_load, 6)\nudp_results = filter_by_protocol(all_user_activity_load, 17)\n</code></pre>\n\n<p>Now we can throw those lists at both <code>get_tcp_stream(tcp_results)</code> and <code>get_udp_stream(udp_results)</code> - but digging into the code for those functions, if I'm reading your intention correctly - it appears we're going back to the database to pull the exact same information which we've already got? Is that right? If so, we don't need those functions, just to clean up the current <code>tcp_results</code> and <code>udp_results</code> with the sequence number, for the <code>update_index()</code> function. You should end up with a main something like this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n db = open_database()\n query = \"SELECT * FROM user_activity_load WHERE protocol = 6 AND tcp_flag = 'SYN' AND stream_index IS NULL OR protocol = 17 AND stream_index IS NULL LIMIT 100\"\n all_user_activity_load = execute_query(db, query)\n tcp_results = filter_by_protocol(all_user_activity_load, 6)\n udp_results = filter_by_protocol(all_user_activity_load, 17)\n update_index(filter_id_from_data(tcp_results))\n update_index(filter_id_from_data(udp_results))\n db.close()\n</code></pre>\n\n<p>I'll leave that as an exercise to you, but it should be quite straight forward. I hope this small review helps somewhat, with an introduction into one of the SOLID concepts (which you can learn to improve your coding), and suggestions to remove code duplication (DRY).<br>\nGood luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:15:24.080",
"Id": "419402",
"Score": "0",
"body": "The DB query comes from https://stackoverflow.com/questions/6923930/mapping-dictionary-with-rows-values - it has a modified column name depending on the database type should you have any issues in using that function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:49:39.790",
"Id": "419411",
"Score": "0",
"body": "This is honestly one of the best reviews anybody has ever done for my code, and I thank you for that. I will surely implement whatever you've told, and these being the best practices employed by professional developers, will also help in sharpening my skills. Thanking you again _/\\\\_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T08:02:27.593",
"Id": "419421",
"Score": "0",
"body": "Also, the `get_tcp_stream` and `get_udp_stream` take my row-data as parameters and fetch all the rows that have the same data, almost, in order to update the `stream_index` throughout the fetched rows after calling the `get_tcp/udp_stream`. This is done in order to label the tcp/udp communication happening between two endpoints. Because `fetch_stream` returns a single row that points to a single packet being transmitted between the endpoints and `get_tcp_stream` updates all these packets/rows returned and labels them as one communication"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T06:12:51.003",
"Id": "216833",
"ParentId": "216769",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216833",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T08:30:50.970",
"Id": "216769",
"Score": "2",
"Tags": [
"python"
],
"Title": "Identifying TCP and UDP streams using a database populated from a sniffer tool"
} | 216769 |
<p>I'm new to C language and want to read a string line by line, I made this function and want to know what do you think about it, can I rely on it a production environment ? </p>
<pre><code>/**
* this function is not thread safe,
*/
char* strReadLine(char* text)
{
static char* text2;
static int start = 0;
static int length = 0;
int startTemp;
int lineLength = 0;
char* line = (char*) 0;
startTemp = start;
//not thread safe but at least make an error
if(start != 0 && text2 != text){
fprintf(stderr, "thread safe guerd fired by strReadLine function\n");
exit(EXIT_FAILURE);
}
text2 = text;
//thread safty end
//if new string
if(length == 0 || start == 0) length = strlen(text);
if(!length) return (char*) 0;//the string is 0 length
for(int x = startTemp; x < length; x++){
start++;
lineLength++;
if( text[x] == '\n'){
line = malloc(lineLength);//not lineLength+1 because I will remove the \n with \0
strncpy(line, text + (startTemp) , lineLength);
line[lineLength - 1] = '\0';
break;
}
}
//if end of file && not the last line
if(start == length && !line){
start = 0;
line = (char*) 0;
}
return line;
}
</code></pre>
<p>I have tested it with this text file</p>
<pre><code>line1
line2
line3
line5
سطر6
line7
</code></pre>
<p>(<em>line 4 is empty and line 6 contains non Latin characters stored in more than 1 byte in UTF-8 encoding</em>)</p>
<p>like this, and it worked as expected</p>
<pre><code>//char* input;this points to the string that is read from the file(I omitted the reading code)
char* line;
int x = 0;
while( (line = strReadLine(input)) ){
x++;
printf("%s\n",line);
if(x == 300){printf("emergency break\n");break;}
}
x = 0;
while( (line = strReadLine(input)) ){
x++;
printf("%s\n",line);
if(x == 300){printf("emergency break\n");break;}
}
</code></pre>
| [] | [
{
"body": "<h2>Code format</h2>\n\n<p>Your use of spaces, braces and parantheses is unconventional in some places.</p>\n\n<p>For example:</p>\n\n<blockquote>\n<pre><code>while( (line = strReadLine(input)) ){\n x++;\n printf(\"%s\\n\",line);\n if(x == 300){printf(\"emergency break\\n\");break;}\n}\n</code></pre>\n</blockquote>\n\n<p>Conventionally this would look more like this:</p>\n\n<pre><code>while (line = strReadLine(input)) {\n x++;\n printf(\"%s\\n\", line);\n if (x == 300) {\n printf(\"emergency break\\n\");\n break;\n }\n}\n</code></pre>\n\n<p>You could try using your IDE's auto-format feature and see how it arranges the code. Also you might want to have a look at some C coding conventions that can be found online, to see how people commonly format their C code in a readable way.</p>\n\n<h2>Thread safety</h2>\n\n<p>It seems like you are trying to guard the function against multiple threads executing it at the same time. However, the function's purpose is to read a string line by line, not to write to it. So as long as the function is only reading from its input, there should be no need to prevent multiple concurrent executions.</p>\n\n<p>If multiple threads really did execute it at the same time, you could still get a race condition between checking the variables and overwriting it, and thus not get the error message when you would expect it.</p>\n\n<h2>Abusing booleanness</h2>\n\n<p>When checking whether an integer has the value <code>0</code>, it is more readable if you compare it to 0, as you do in the first of the following two lines. It reads more intuitively, because a length cannot be true or false, as the second line implies, even though the compiler can handle both. Then you also wouldn't need the comment explaining what <code>!length</code> is supposed to mean. <code>if (length == 0)</code> says it explicitly.</p>\n\n<pre><code>if(length == 0 || start == 0) length = strlen(text);\nif(!length) return (char*) 0;//the string is 0 length\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T19:49:17.727",
"Id": "421907",
"Score": "0",
"body": "Thanks, regarding the thread safety, this function is not safe however it only reads, because of it's internal **static variable** `start`, when 2 threads are using it at the same time , the static variable `start` will be changing by the 2 threads in a wrong way, *(e.g: first thread changes the start for him self, then the second thread use it and the function will start from the start of the string of the first thread)*, or I missed something ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-25T07:41:40.557",
"Id": "423136",
"Score": "1",
"body": "What I meant is that you might completely avoid that problem by not relying on the static variable, and instead adding another parameter for that, which you pass as a pointer or reference. Then every thread that might call that function would track its own state, rather than relying on some hidden state inside of the function, and you could remove the whole \"thread safety\" checking code altogether."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T11:09:27.270",
"Id": "217946",
"ParentId": "216775",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217946",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T11:48:34.893",
"Id": "216775",
"Score": "1",
"Tags": [
"beginner",
"c",
"strings"
],
"Title": "strReadLine function (read line by line from a string)"
} | 216775 |
<p>I need to heavily optimize the following sql stored procedure (MySQL 5.6). Requirements:</p>
<ul>
<li>Should be as fast as possible (this is a key)</li>
<li>Lots of records (10 M now, possibly more)</li>
<li>Stored procedure should allow any custom filtering, including on the tables that are not part of this question. Custom filtering filters only <code>Test Results</code> (see further), but with any rules (for example <code>filter those test runs that happen during this time, on this machine etc.</code>)</li>
</ul>
<p>There are <code>Test Results</code>, each contains <code>Test Case Results</code>. Each <code>Test Case Result</code> corresponds to a <code>Test Case</code> that ran during a test. Sometimes <code>Test Case</code>fails and sometimes it can be repeated producing several <code>Test Case Results</code> for a single <code>Test Case</code> in a single <code>Test Result</code>. In such cases field <code>RetryRun</code> is increased with each try, meaning that the maximum <code>RetryRun</code> in each group of <code>Test Result</code> and <code>Test Case</code> is the only one significant.
If one <code>Test Case</code> fails several times, further <code>Test Case</code>s usually are not executed (in fact they can, but only in debug scenario and we do not care much about that)</p>
<p><strong>Produce the query that shows for each <code>Test Case</code> how many times it has caused a failure of <code>Test Result</code> and how many times each <code>Test Case</code> ran totally.</strong></p>
<p>The database schema is not under review. It has issues, but it is long established now and cannot be changed.</p>
<p>Of course, I'm writing only important for the question fields and tables here.</p>
<p>Tables:</p>
<pre><code>CREATE TABLE `testresult` (
`TestResultPK` int(11) NOT NULL AUTO_INCREMENT,
`Passed` tinyint(1) NOT NULL,
`CreatedDate` datetime DEFAULT NULL,
PRIMARY KEY (`TestResultPK`),
UNIQUE KEY `TestResultPK` (`TestResultPK`),
KEY `CreatedDateIndex` (`CreatedDate`)
) ENGINE=InnoDB AUTO_INCREMENT=94755 DEFAULT CHARSET=latin1;
CREATE TABLE `testcasedataresult` (
`TestCaseDataResultPK` int(11) NOT NULL AUTO_INCREMENT,
`Passed` tinyint(1) DEFAULT NULL,
`RetryRun` int(11) DEFAULT NULL,
`TestCaseDataFK` int(11) DEFAULT NULL,
`TestResultFK` int(11) DEFAULT NULL,
PRIMARY KEY (`TestCaseDataResultPK`),
UNIQUE KEY `TestCaseDataResultPK` (`TestCaseDataResultPK`),
KEY `TestCaseDataFK` (`TestCaseDataFK`),
KEY `TestResultFK` (`TestResultFK`),
#CONSTRAINT `FK469417F32EBE75FE` FOREIGN KEY (`TestCaseDataFK`) REFERENCES `testcasedata` (`TestCaseDataPK`),
CONSTRAINT `FK469417F3C87DE8C6` FOREIGN KEY (`TestResultFK`) REFERENCES `testresult` (`TestResultPK`)
) ENGINE=InnoDB AUTO_INCREMENT=20193325 DEFAULT CHARSET=latin1;
</code></pre>
<p>Please note that <code>Test Case Result</code> does not have a time stamp. So in normal circumstances, the <code>Test Case Result</code> that has failed the <code>Test</code> is the one that has <code>Passed = 0</code> and maximum <code>RetryRun</code> (there is no record of the same <code>Test Case</code> that is <code>Passed = 1</code> and has bigger <code>RetryRun</code> for the given <code>Test Result</code>).</p>
<p>My procedure:</p>
<pre><code>DELIMITER $$
CREATE DEFINER=`system`@`%` PROCEDURE `failedtestcasestatistics`(in trWhere LONGTEXT)
BEGIN
DROP TABLE if EXISTS failedtcdr_foreach_tr;
DROP TABLE if EXISTS alltcdr;
SET @failedtcdrSql = CONCAT('
create temporary table failedtcdr_foreach_tr
select tcdr.TestResultFK, max(tcdr.TestCaseDataResultPK) MaxTestCaseDataResultPK
from testcasedataresult tcdr, testresult tr, (', trWhere, ') trWhereTable
where
tcdr.TestResultFK = tr.TestResultPK and
tr.Passed = 0 and
trWhereTable.TestResultPK = tcdr.TestResultFK
group by tcdr.TestResultFK');
PREPARE failedTcdrStmt FROM @failedtcdrSql;
EXECUTE failedTcdrStmt;
DEALLOCATE PREPARE failedTcdrStmt;
SET @alltcdrSql = CONCAT('
create temporary table alltcdr
select tcdr.TestCaseDataFK as TestCaseDataFK, count(*) as total from testcasedataresult tcdr, (', trWhere, ') trWhereTable
where tcdr.TestResultFK = trWhereTable.TestResultPK
group by tcdr.TestCaseDataFK
');
PREPARE allTcdrStmt FROM @alltcdrSql;
EXECUTE allTcdrStmt;
DEALLOCATE PREPARE allTcdrStmt;
#select * from alltcdr;
select
failedGroup.TestCaseDataFK,
failedGroup.failures,
allt.total as total
from
(select
tcdr.TestCaseDataFK TestCaseDataFK, count(*) failures
from
failedtcdr_foreach_tr trs, testcasedataresult tcdr
where
trs.MaxTestCaseDataResultPK = tcdr.TestCaseDataResultPK
group by tcdr.TestCaseDataFK) failedGroup,
alltcdr as allt
where
failedGroup.TestCaseDataFK = allt.TestCaseDataFK;
DROP TABLE failedtcdr_foreach_tr;
DROP TABLE alltcdr;
END$$
DELIMITER ;
</code></pre>
<p>How do I call it:</p>
<pre><code>CALL `failedtestcasestatistics`('select tr.TestResultPK from testresult tr');
</code></pre>
<p>I'm using a trick with <code>PREPARE stmt</code> and <code>CONCAT</code> to be able to apply any custom filtering on the stored procedure</p>
<p>How can I optimize the procedure?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T12:52:37.060",
"Id": "419338",
"Score": "0",
"body": "Are you saving program test results into a database?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T12:56:06.100",
"Id": "419340",
"Score": "0",
"body": "@dustytrash The stored procedure should be executed from the external code"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T12:49:59.140",
"Id": "216777",
"Score": "0",
"Tags": [
"sql",
"mysql"
],
"Title": "Optimize slow SQL stored procedure that calculate Test Case failures in a non-optimal schema"
} | 216777 |
<p>This is for some quantum mechanics software so there will be references to molecules/atoms etc but the core issue is a python logging one, unrelated to all that.</p>
<p>I have a couple of logging decorators, one for logging what the program is doing, another to log exceptions (along with their full stack trace and some class object details to help with debugging).</p>
<p>To save me decorating every single method, I also have a class decorator which just applies a decorator to all methods of a class. This is:</p>
<pre class="lang-py prettyprint-override"><code>def for_all_methods(decorator):
"""
Applies a decorator to all methods of a class (includes sub-classes and init; it is literally all callables).
This class decorator is applied using '@for_all_methods(timer_func)' for example.
"""
@wraps(decorator)
def decorate(cls):
# Examine all class attributes.
for attr in cls.__dict__:
# Check if each class attribute is a callable method.
if callable(getattr(cls, attr)):
# Set the callables to be decorated.
setattr(cls, attr, decorator(getattr(cls, attr)))
return cls
return decorate
</code></pre>
<p>The logging decorators are similar, the following is used to log method timings, while also giving the docstring, qualname and some other info:</p>
<pre class="lang-py prettyprint-override"><code>def log_dec_factory(file_name):
"""
Logs the various timings of a function in a dated and numbered file.
Writes the start time, function / method qualname and docstring when function / method starts.
Then outputs the runtime and time when function / method finishes.
"""
def timer_logger(orig_func):
@wraps(orig_func)
def wrapper(*args, **kwargs):
start_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
t1 = time()
with open(file_name, 'a+') as log_file:
log_file.write(f'{orig_func.__qualname__} began at {start_time}.\n\n')
log_file.write(f'Docstring for {orig_func.__qualname__}:\n {orig_func.__doc__}\n\n')
time_taken = time() - t1
mins, secs = divmod(time_taken, 60)
hours, mins = divmod(mins, 60)
secs, remain = str(float(secs)).split('.')
time_taken = f'{int(hours):02d}h:{int(mins):02d}m:{int(secs):02d}s.{remain[:5]}'
end_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_file.write(f'{orig_func.__qualname__} finished in {time_taken} at {end_time}.\n\n')
# Add some separation space between function / method logs.
log_file.write(f'{"-" * 50}\n\n')
return orig_func(*args, **kwargs)
return wrapper
return timer_logger
</code></pre>
<p>So, when I want to get some log info for a particular method of a class, I decorate the class with <code>for_all_methods()</code> which takes the function / method decorator as an argument. The function / method decorator then takes the argument of the log file name, like so:</p>
<pre class="lang-py prettyprint-override"><code>@for_all_methods(log_dec_factory('log_file.txt'))
class Engine:
def __init__(self, molecule):
self.molecule = molecule
self.name = molecule.name
self.log_file = molecule.log_file
def print_name_to_terminal(self):
print(self.name)
...
</code></pre>
<p>So now, whenever a method from the class <code>Engine</code> is invoked, the details of the invocation will be written to <code>log_file.txt</code>. Great!</p>
<p><em>To be clear, the molecule argument is a class which is getting passed around and stores all important information (atoms, coordinates, etc).</em></p>
<p>This is completely fine, except rather than providing a string for the log file name, I just want to get that from the molecule argument. In other words, I want to pass <code>self.log_file</code> into the decorator.</p>
<p>Now, I can do this with a quick and dirty global in the undecorated base class:</p>
<pre class="lang-py prettyprint-override"><code>class Engine:
def __init__(self, molecule):
self.molecule = molecule
self.name = molecule.name
self.log_file = molecule.log_file
log_file = self.log_file
global log_file
...
@for_all_methods(log_dec_factory(log_file))
class PSI4(Engine):
def __init__(self, molecule):
super().__init__(molecule)
...
</code></pre>
<p>Now, this works but, it feels like a hacky workaround. (I've literally never needed to use a global in Python, there's always been a better / proper way.) This also only works if I have a base class which I don't want to log the methods for. Otherwise I have to go back to manually putting in the log file name.</p>
<p>So finally, my question is, is there a proper way of doing something like this? I use the logging module for my exception logger decorator but couldn't find what I wanted for this particular use case.</p>
<p>Many thanks in advance and apologies for the rather long post.</p>
| [] | [
{
"body": "<p>I'm not certain how you even got this to work. The decoration of the class occurs when the class is declared, not when an instance of the class is created, so setting of <code>log_file</code> will not have happened by the <code>Engine</code> constructor. You must have also declared the <code>log_file</code> elsewhere, and that is what is being used to decorate the class methods.</p>\n\n<p>If I understand what you want to do properly, you will have multiple <code>molecule</code> instances, which each have their own <code>log_file</code>. During a <code>PSI4</code> method, you want the logger (which was used to decorate the class) to reach into the instance's data, retrieving the <code>molecule</code>, and use the molecule's <code>log_file</code>.</p>\n\n<p>Fortunately, the instance is passed as the first argument <code>self</code> to the wrapped method. You can use that to retrieve <code>self.molecule</code>, from which <code>self.molecule.log_file</code> can be found. Except the first argument is not always <code>self</code> (static and class methods), and <code>self.molecule</code> doesn't exist until partway through the constructor's execution. So the method decorator better check if the first argument exists, and whether it has a <code>molecule</code> member.</p>\n\n<pre><code>from functools import wraps\n\ndef all_methods(decorator):\n @wraps(decorator)\n def decorate(cls):\n for attr in cls.__dict__:\n if callable(getattr(cls, attr)):\n setattr(cls, attr, decorator(getattr(cls, attr)))\n return cls\n return decorate\n\ndef method_logger(method):\n @wraps(method)\n def wrapper(*args, **kwargs):\n log_file = 'nowhere'\n if len(args) >= 1 and hasattr(args[0], 'molecule'):\n #if len(args) >= 1 and isinstance(args[0], PSI4):\n log_file = args[0].molecule.log_file\n print(f\"Logging {method.__name__}(...) to {log_file}\")\n return method(*args, **kwargs)\n return wrapper\n\nclass Molecule:\n def __init__(self, log_file):\n self.log_file = log_file\n\n@all_methods(method_logger)\nclass PSI4:\n def __init__(self, molecule):\n self.molecule = molecule\n\n def f(self): pass\n def g(self): pass\n\n @staticmethod\n def sm(): pass\n\n @classmethod\n def cm(cls): pass\n\ne1 = PSI4(Molecule('file1'))\ne2 = PSI4(Molecule('file2'))\n\ne1.f()\ne2.g()\nPSI4.sm()\nPSI4.cm()\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Logging __init__(...) to nowhere\nLogging __init__(...) to nowhere\nLogging f(...) to file1\nLogging g(...) to file2\nLogging sm(...) to nowhere\nLogging cm(...) to nowhere\n</code></pre>\n\n<p>Instead of checking for <code>hasattr(args[0], 'molecule')</code>, I'd love to use <code>isinstance(args[0], PSI4)</code>, but <code>args[0]</code> is a <code>PSI4</code> instance during the <code>PSI4.__init__()</code> call, but since the constructor hasn't run yet, <code>self.molecule</code> is still unassigned, even though the type of the instance is correct.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T17:30:35.017",
"Id": "419368",
"Score": "0",
"body": "Your interpretation of what I want to do is exactly right; this is a great solution. Thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:23:11.123",
"Id": "216796",
"ParentId": "216778",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "216796",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T13:05:27.077",
"Id": "216778",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"logging",
"closure"
],
"Title": "Logging with decorators (passing log file name as argument)"
} | 216778 |
<p>I created a brainfuck interpreter in javascript. It works good to me as I have seen no bugs in my compiler. I like to get a suggestion and review from you to what should this compiler improve. </p>
<p>Here's the short code:</p>
<pre><code>function bf(str, input){
var array = str.split("");
var memory = [0];
var pointer = 0;
var result = [];
var open = [];
for(var i = 0; i < array.length; i++){
if(array[i] == ">"){
pointer++;
if(memory.length-1 < pointer){
memory.push(0);
}
}else if(array[i] == "<"){
if(pointer > 0){
pointer--;
}else{
throw "Overflow Error at " + i
}
}else if(array[i] == "+"){
if(memory[pointer] < 255){
memory[pointer]++;
}else{
memory[pointer] = 0;
}
}else if(array[i] == "-"){
if(memory[pointer] > 0){
memory[pointer]--;
}else{
memory[pointer] = 255;
}
}else if(array[i] == "."){
result.push(String.fromCharCode(memory[pointer]));
}else if(array[i] == ","){
memory[pointer] = input.shift().charCodeAt(0);
}else if(array[i] == "["){
if(open.length){
if(open[open.length-1] != i){
open.push(i);
}
}else{
open.push(i);
}
}else if(array[i] == "]"){
if(open.length){
if(memory[pointer]){
i = open[open.length - 1];
}else{
open.pop();
}
}
}
}
return result;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:47:30.620",
"Id": "419350",
"Score": "1",
"body": "Is there a purpose for the compiler? Or just for the challenge?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:31:28.543",
"Id": "419356",
"Score": "0",
"body": "Can you test it on my [FizzBuzz code](https://codereview.stackexchange.com/q/57382/31562) ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:05:04.377",
"Id": "419357",
"Score": "1",
"body": "There is a serious bug, you have not implemented the \"[\" command correctly. \"[\" is missing `if memory[pointer] === 0 goto matching \"]\"`"
}
] | [
{
"body": "<p>Some comments in the code could go a long way.</p>\n\n<p>A switch statement might be more readable here than the if/else chain.</p>\n\n<p>If possible, rename the 'bf' function to something more readable, same for the 'str' parameter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:47:03.757",
"Id": "216786",
"ParentId": "216779",
"Score": "0"
}
},
{
"body": "<h2>General style points</h2>\n<ul>\n<li><p>No need to split the <code>str</code> into an <code>array</code>, you can access the character directly using bracket notation. eg <code>str[i] === ">"</code></p>\n</li>\n<li><p>If you want a number to cycle over a range use the remainder operator <code>%</code> to do that. Example to add 1 <code>memory[pointer] = (memory[pointer] + 1) % 255</code> and to subtract <code>memory[pointer] = (memory[pointer] + 254) % 255</code>.</p>\n<p>However as you want to simulate memory as bytes you may as well use a typed array that has an Unsigned Char. The bytes in the array behave the same as they would on the VM that runs BF commands. Example <code>const memory = new Uint8Array(1024)</code></p>\n</li>\n<li><p>Not sure why you throw overflow for "<" when you don't throw the same error <code>></code>. <code><</code> should just cycle to highest byte in memory.</p>\n</li>\n<li><p>Use "const" for variables that do not change.</p>\n</li>\n<li><p>Use <code>===</code> and <code>!==</code> rather than <code>==</code> and <code>!=</code></p>\n</li>\n<li><p>Don't double space (every other line empty). It makes the code hard to read as it will not fit to one screen.</p>\n</li>\n<li><p>Naming is rather poor.</p>\n<p>-<code>result</code> could be better as "output"</p>\n<ul>\n<li><code>str</code> maybe <code>commands</code> or <code>program</code></li>\n<li><code>i</code> maybe <code>programCounter</code> or <code>commandIndex</code>. I am old school so would use <code>pc</code></li>\n</ul>\n</li>\n<li><p>Rather than index into an array over and over, as you do with array[i], store it in a variable <code>const command = array[i];</code> and then <code>if(command === ">") {</code> makes the code more compact and easier to follow.</p>\n</li>\n</ul>\n<h2>Design.</h2>\n<p>You can use a lookup to get the action required for each command. (see example <code>commandList</code>) rather than one long <code>if() {}else if()...</code>. This is a lot quicker to run as you don't need to step over <code>else if</code> statements to find the matching block. Also make it easy to add or change commands, and easier to read.</p>\n<h2>The Bug</h2>\n<p>As I pointed out in the comments there is a bug. You have not implemented the "[" command correctly. This is a big issue as many programs will fail. To solutions are non trivial.</p>\n<p>There are two solutions.</p>\n<ol>\n<li>When you need to skip ahead search for the matching close. This can cost a lot of performance.</li>\n<li>Compile the code and locate matching open and close <code>[</code> and <code>]</code> so that you can quickly locate the match and move to it if required.</li>\n</ol>\n<h2>Ease of use</h2>\n<p>The input and output would be better as strings rather than arrays. Makes the BF easier to use.</p>\n<h2>The halting problem.</h2>\n<p>There is a fundamental requirement you have missed. You can never know if the program you are running will exit.</p>\n<p>As JavaScript is blocking this means there is no way to stop the execution if the bf code goes into infinite loop. You should protect against this problem.</p>\n<p>The easiest is to put a limit on the number of instructions, and throw error if reached.</p>\n<p>Or you could have the commands execute on a timer.</p>\n<h2>Example</h2>\n<p>The function name is <code>bfVM</code> for brainFuckVirtualMachine and requires a compiled program. (as that is how I fixed your bug).</p>\n<p>I included the compiler, all it does is find matching blocks and maps them to each other. returns a compiled object.</p>\n<p>And two programs as testing fodder.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Run two comnpiled BF programes.\nsetTimeout(() => {\nconsole.log(bfVM(helloWorld))\nconsole.log(bfVM(addNums))\n},0);\n/* Old school naming pc is program counter, ptr is a pointer, and\n inPtr is input pointer */\nfunction bfVM(compiled, input) {\n const program = compiled.program;\n const blocks = compiled.blocks;\n const RAM = compiled.RAM;\n const memory = new Uint8Array(RAM);\n const commandList = {\n \">\"(){ ptr = (ptr + 1) % RAM },\n \"<\"(){ ptr = (ptr + RAM - 1) % RAM },\n \"+\"(){ memory[ptr]++ },\n \"-\"(){ memory[ptr]-- },\n \".\"(){ output += String.fromCharCode(memory[ptr]) },\n \",\"(){ memory[ptr] = input.charCodeAt(inPtr++) },\n \"[\"(){ pc = !memory[ptr] ? blocks.get(pc)[0] : pc },\n \"]\"(){ pc = memory[ptr] ? blocks.get(pc)[0] : pc },\n }; \n \n var cycles = 0, ptr = 0, pc = 0, inPtr = 0, output = \"\"; \n while (pc < program.length && cycles++ < MAX_CYCLES) {\n const cmd = commandList[program[pc]];\n cmd && cmd();\n pc ++; \n }\n if (cycles=== MAX_CYCLES) { throw new Error(\"Cycle limit reached at PC: \" + pc) }\n return output;\n}\n\nconst MAX_CYCLES = 1024 * 1024; // Limit of execution steps.\nfunction compileBF(program, RAM) {\n var pc = 0;\n const blocks = new Map();\n const blockStack = [];\n while (pc < program.length) {\n if (program[pc] === \"[\") {\n blocks.set(pc, [])\n blockStack.push(pc);\n } else if(program[pc] === \"]\") {\n const open = blockStack.pop();\n const block = blocks.get(open);\n if (block === undefined) {\n throw new Error(\"Syntax error: No matching block for ']' at \" + pc);\n }\n block[0] = pc;\n blocks.set(pc, [open]);\n }\n pc++;\n }\n if (blockStack.length) {\n throw new Error(\"Syntax error: Block missmatch at \" + pc);\n }\n return {program, blocks, RAM};\n}\n\nconst nums = [\"\", \"+\", \"++\", \"+++\", \"++++\", \"+++++\", \"++++++\", \"+++++++\", \"++++++++\", \"+++++++++\"]\nconst toASCIINum = \"++++++++[<++++++>-]<\"\nconst helloWorld = compileBF((\"++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.\"), 14)\nconst addNums = compileBF(nums[5]+\">\"+nums[4]+\"[<+>-]\"+toASCIINum+\".\",2);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T18:17:56.933",
"Id": "216806",
"ParentId": "216779",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T13:22:39.523",
"Id": "216779",
"Score": "2",
"Tags": [
"javascript",
"interpreter",
"brainfuck"
],
"Title": "Brainfuck interpreter improvement"
} | 216779 |
<p><strong>Purpose:</strong></p>
<blockquote>
<p>I wanted a way to improve event clarity and event code organization. I
observed that every single event flow went through the following
steps: </p>
<ul>
<li>Trigger -> UI Change -> (Async) Action -> UI Change</li>
</ul>
</blockquote>
<p>Here is a <a href="https://jsfiddle.net/Angryr/86oecufq/" rel="nofollow noreferrer">JSFiddle</a>.</p>
<p><strong>Notes & Concerns</strong></p>
<ul>
<li>Something about the name of the class seems bad, but I can't come up with something better.</li>
<li>Are there ways to make the usage more clear to someone who didn't write the class?</li>
<li>Is there a way to make it where the user doesn't have to call the <code>callback</code> function in <code>preAction</code> and <code>action</code> and not have them fire before the user's function has completed?</li>
</ul>
<p><strong>Class Definition: UIEvent</strong></p>
<pre><code>// PURPOSE:
// I wanted a way to improve event clarity and event code organization.
// I observed that every single event flow went through the following steps:
// Trigger -> UI Change -> (Async) Action -> UI Change
// EXAMPLES:
// Add button Click -> Disable add button -> Add new row -> Enable add button
// Save button click -> Disable save button -> Save row -> Replace row
// Edit button click -> Change button visibility -> Enable Controls -> Do Nothing.
// PARAMETERS:
// This function takes an object of settings with the following fields.
// 'eventElement':
// A function for selecting the element that will trigger the event from the container element provided to the Initialize() function.
// e.g. (container) => container.querySelector(".some-class")
// 'eventType':
// The event triggered by the element above.
// e.g. "click", "change", etc.
// 'preAction':
// A function that is fired when the event in triggered.
// Has the parameters (e, callback) where e is the eventArgs from the original event and callback is the function to be called when this function has completed.
// Remember to call the 'callback' when done or the 'action' and 'postAction' won't be called.
// 'action':
// A function that is fired after the preAction has completed.
// Has the parameters (e, callback) where e is the eventArgs from the original event and callback is the function to be called when this function has completed.
// Remember to call the 'callback' when done or the 'postAction' won't be called.
// 'postAction':
// A function that is fired after the action has completed.
// Has the parameter (e) which is the eventArgs of the original event.
// INITIALIZTION:
// The Initialize(container) function sets up the event listener on the 'eventElement' given a container.
// If no container is provided, it will default to document.
function UIEvent(settings) {
var thisUIEvent = this;
this.GetElement = (container) => settings.eventElement(container);
this.EventType = settings.eventType;
// Executed before the 'Action'.
// If you provide your own event handler you must call the 'callback' function when done.
this.PreAction = function (e) {
if (settings.preAction) {
settings.preAction(e, thisUIEvent.Action)
} else {
thisUIEvent.Action(e);
}
};
// Executed after the 'PreAction'.
// If you provide your own event handler you must call the 'callback' function when done.
this.Action = function (e) {
if (settings.action) {
settings.action(e, thisUIEvent.PostAction);
} else {
thisUIEvent.PostAction(e);
}
};
// Executed after the 'Action'.
this.PostAction = function (e) {
if (settings.postAction) {
settings.postAction(e);
}
};
// Must be called to create the event listener.
this.Initialize = (container) => {
var element = thisUIEvent.GetElement(container || document);
if (element === null) { return; }
element.addEventListener(thisUIEvent.EventType, function (e) {
thisUIEvent.PreAction(e);
});
};
}
</code></pre>
<p><strong>Example Usage: Add Row Button</strong></p>
<pre><code>var AddRowEvent = new UIEvent({
eventType: "click",
eventElement: (container) => container.querySelector(".add-new-row"),
preAction: (e, callback) => {
document.querySelector(".add-new-row").setAttribute("disabled", "disabled");
if (callback) {
callback(e);
}
},
action: (e, callback) => {
var defaultOrder = { Messages: [{ Text: "This is a new row", Color: "green" }, { Text: "This is a new row", Color: "green" }], DeliveryDate: new Date().toLocaleDateString() };
var newRowHtml = Render.Once("row-template", defaultOrder);
var row = Grid.InsertRowBeforeIndex(advanceOrdersTableSelector, newRowHtml);
initializeRow(row);
toggleCanEditRow(row, true);
if (callback) {
callback(e);
}
},
postAction: (e) => {
document.querySelector(".add-new-row").removeAttribute("disabled")
}
});
AddRowEvent.Initialize(); // Same as AddRowEvent.Initialize(document) thanks to defaults.
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T13:25:17.017",
"Id": "216780",
"Score": "2",
"Tags": [
"javascript",
"event-handling",
"callback"
],
"Title": "UI Event Flow class"
} | 216780 |
<p><strong>Approach</strong></p>
<p>All data is submitted into my DynamoDB from another <strong><em>Lambda > API Integration</em></strong> function whereas the <code>lastUpdated</code> row gets inserted as <code>null</code> and then the function below basically polls my database every 1 minute looking for new rows that have a <code>null</code> value & performs actions on them until the <code>lastUpdated</code> can then be updated (once an action is performed elsewhere)</p>
<p>I have the following Node.JS (runtime v8.10) executing on AWS Lambda:</p>
<pre><code>const AWS = require("aws-sdk");
const game = require('game-api');
const uuid = require("uuid");
AWS.config.update({
region: "us-east-1"
});
exports.handler = async (event, context) => {
//set db
var documentClient = new AWS.DynamoDB.DocumentClient();
//find matches
var params = {
TableName: 'matches',
FilterExpression:'updated_at = :updated_at',
ExpressionAttributeValues: {
":updated_at": 0,
}
};
var rows = await documentClient.scan(params).promise();
//game object
let gameAPI = new game(
[
"admin@game.com",
"password"
]
);
await gameAPI.login();
for (let match of rows.Items) {
var player_params = {
TableName: 'players',
Key: { "match_id": match.id }
};
let player_row = await documentClient.get(player_params).promise();
//grab stats and compare
var stats = await gameAPI.getStatsBR(
player_row.Item.player_1_name,
player_row.Item.player_1_network
);
var new_data = compareModiified(
match.match_type,
player_row.Item.player_1_last_updated,
stats
);
if(new_data === true) {
//we have new data
let kills;
let matches;
let kills_completed;
let matches_completed;
let modified;
switch(match.match_type) {
case 'myself':
kills = stats.group.solo.kills;
kills_completed = (kills - player_row.Item.player_1_kills);
matches = stats.group.solo.matches;
matches_completed = (matches - player_row.Item.player_1_matches);
modified = stats.group.solo.lastModified;
break;
case 'solo':
kills = stats.group.duo.kills;
kills_completed = (kills - player_row.Item.player_1_kills);
matches = stats.group.duo.matches;
matches_completed = (matches - player_row.Item.player_1_matches);
modified = stats.group.duo.lastModified;
break;
case 'duo':
kills = stats.group.squad.kills;
kills_completed = (kills - player_row.Item.player_1_kills);
matches = stats.group.squad.matches;
matches_completed = (matches - player_row.Item.player_1_matches);
modified = stats.group.squad.lastModified;
break;
}
var update_params = {
TableName:"matches",
Key: { "id": match.id },
UpdateExpression: "SET #status = :status, updated_at = :modified",
ExpressionAttributeNames:{
"#status":"status"
},
ExpressionAttributeValues:{
":status": 1,
":modified": modified
}
};
await documentClient.update(update_params).promise();
var report_params = {
Item: {
'match_id': match.id,
'kills': kills_completed,
'matches': matches_completed,
'completed_at': new Date().getTime()
},
TableName : 'reports'
};
await documentClient.put(report_params).promise();
} else {
//we don't have new data.
console.log("We don't have new data, let's not do anything..");
}
}
return {
statusCode: 200
};
};
function compareModiified(match_type, db_modifiied, stats) {
var stats_modified;
switch(match_type) {
case 'myself':
stats_modified = stats.group.solo.lastModified;
break;
case 'solo':
stats_modified = stats.group.duo.lastModified;
break;
case 'duo':
stats_modified = stats.group.squad.lastModified;
break;
}
return (stats_modified > db_modifiied);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:42:42.263",
"Id": "419349",
"Score": "3",
"body": "The calculation for `kills_completed` and `matches_completed` could be done after the switch statement since they're all identical. Then you'd have 4 less lines of code and the same functionality."
}
] | [
{
"body": "<p>Welcome to Code Review! Hopefully this experience will be useful and positive for you.</p>\n\n<h2>Your statement about polling</h2>\n\n<blockquote>\n <p>and then the function below basically polls my database every 1 minute looking for new rows that have a <code>null</code> value & performs actions on them until the <code>lastUpdated</code> can then be updated (once an action is performed elsewhere)</p>\n</blockquote>\n\n<p>I haven't used AWS and DynamoDB but perhaps you could use a trigger or some other hook to receive a notification instead of polling each minute. With this approach, the server doesn’t waste resources checking for an update but rather processes incoming data when necessary. Perhaps <a href=\"https://aws.amazon.com/blogs/aws/dynamodb-update-triggers-streams-lambda-cross-region-replication-app/\" rel=\"nofollow noreferrer\">this page</a> would be useful.</p>\n\n<h2>General feedback</h2>\n\n<p>Overall the handler function looks a bit too long. The suggestions below should help you reduce the length of it, though if it is still too long then it may be advisable to break it up into smaller atomic functions that handle a single part of getting data. </p>\n\n<p>The variable <code>update_params</code> could be moved outside the handler function without the <code>id</code> property of the <code>Key</code> property and <code>:modified</code> property of <code>ExpressionAttributeValues</code> set - those can be set when needed.</p>\n\n<pre><code>const update_params = {\n TableName:\"matches\",\n Key: {},\n UpdateExpression: \"SET #status = :status, updated_at = :modified\",\n ExpressionAttributeNames:{\n \"#status\":\"status\"\n },\n ExpressionAttributeValues:{\n \":status\": 1\n }\n};\n</code></pre>\n\n<p>Then when before passing it to the call to <code>documentClient.update(update_params).promise();</code>:</p>\n\n<pre><code>update_params.Key.id = match.id;\nupdate_params.ExpressionAttributeValues[\":modified\"] = modified;\n</code></pre>\n\n<hr>\n\n<p>Your code could make more use of <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> - especially for values that are never reassigned - e.g. <code>documentClient</code>, <code>params</code>, <code>rows</code>, <code>gameAPI</code>, <code>player_params</code>, etc. Some developers believe it is wise to default to using <code>const</code> and then if the need to re-assign presents itself, switch to using <code>let</code>.'</p>\n\n<p>I would also question whether you intentionally used <code>var</code> instead of <code>let</code> within the <code>for</code> loop... </p>\n\n<hr>\n\n<p>Let's look at that function <code>compareModiified()</code>:</p>\n\n<blockquote>\n<pre><code>function compareModiified(match_type, db_modifiied, stats) {\n var stats_modified;\n switch(match_type) {\n case 'myself':\n stats_modified = stats.group.solo.lastModified;\n break;\n case 'solo':\n stats_modified = stats.group.duo.lastModified;\n break;\n case 'duo':\n stats_modified = stats.group.squad.lastModified;\n break;\n }\n return (stats_modified > db_modifiied);\n}\n</code></pre>\n</blockquote>\n\n<p>Did you intentionally spell the function name as <code>compareModiified</code> and the second parameter as <code>db_modifiied</code>, or are those double <code>i</code>'s typos?</p>\n\n<p>This could be simplified using a mapping of match_type to the property of <code>stats.group</code> to access:</p>\n\n<pre><code>const matchTypeGroupMapping = {\n 'myself' => 'solo',\n 'solo' => 'duo', \n 'duo' => 'squad'\n};\n</code></pre>\n\n<p>A <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\"><code>Map</code></a> could also be used instead of a plain old JavaScript Object - useful if the keys were not serializable.</p>\n\n<p>That mapping could be used to simplify the function:</p>\n\n<pre><code>function compareModiified(match_type, db_modifiied, stats) {\n if (match_type in matchTypeGroupMapping) {\n const mappedKey = matchTypeGroupMapping[match_type];\n return stats.group[mappedKey].lastModified > db_modifiied;\n }\n //do we need to handle other values of match_type?\n}\n</code></pre>\n\n<p>As the comment at the end alludes to: what should happen for other values of <code>match_type</code>?</p>\n\n<hr>\n\n<p>That mapping define above could also be used to simplify the cases within the <code>switch</code> statement of the <code>for</code> loop inside the handler function. And <a href=\"https://codereview.stackexchange.com/questions/216782/aws-lambda-function-to-update-newly-added-dynamodb-records#comment419349_216782\">Shelby115's comment</a> is correct - the assignment statements in all three cases of the <code>switch</code> statement are identical and could be moved out of the <code>switch</code> statement. But the code below can be used to replace the <code>switch</code> statement entirely.</p>\n\n<pre><code>if (new_data === true && match.match_type in matchTypeGroupMapping) {\n const mappedKey = matchTypeGroupMapping[match.match_type];\n const kills = stats.group[mappedKey].kills;\n const matches = stats.group[mappedKey].matches;\n\n update_params.ExpressionAttributeValues[\":modified\"] == stats.group[mappedKey].lastModified;\n\n await documentClient.update(update_params).promise();\n\n const report_params = {\n Item: {\n 'match_id': match.id,\n 'kills': (kills - player_row.Item.player_1_kills),\n 'matches': (matches - player_row.Item.player_1_matches),\n 'completed_at': new Date().getTime()\n },\n TableName : 'reports'\n };\n await documentClient.put(report_params).promise();\n}\n</code></pre>\n\n<p>Notice how above the variables <code>kills_completed</code> and <code>matches_completed</code> have been eliminated, but if you want to keep them for clarity you could.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T16:17:43.117",
"Id": "420682",
"Score": "0",
"body": "Absolutely fantastic answer! it's exactly what I was looking for so I couldn't thank you enough for this"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T16:43:04.220",
"Id": "217087",
"ParentId": "216782",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217087",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:05:05.177",
"Id": "216782",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"amazon-web-services",
"nosql"
],
"Title": "AWS Lambda function to update newly added DynamoDB records"
} | 216782 |
<p>I am trying to improve my code to find the tennis court line intercepts so that I can find the boundaries of the different quadrants of the court. </p>
<p><a href="https://i.stack.imgur.com/NlLrx.jpg" rel="noreferrer">This is the tennis court image I am trying to analyze</a></p>
<p><a href="https://i.stack.imgur.com/1vjzx.png" rel="noreferrer">This is the final result</a></p>
<p>I achieved this by first finding the white pixels in the image, then applying canny edge detection with some preprocessing such as Gaussian blur. Then the canny edge output is dilated to help prepare it for hough lines detection.</p>
<p>Then taking the hough lines output I used the python implementation of the <a href="https://github.com/ideasman42/isect_segments-bentley_ottmann" rel="noreferrer">Bentley–Ottmann algorithm</a> by github user ideasman42 to find the hough line intercepts. </p>
<p>This seems to work pretty well, but I'm struggling to tune my system to find the last 4 intercept points. If anyone could give me advice to improve or tune this implementation or even offer up some ideas for a better way to solve the problem of finding the court boundaries I would appreciate it.</p>
<pre><code># import the necessary packages
import numpy as np
import argparse
import cv2
import scipy.ndimage as ndi
import poly_point_isect as bot
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", help = "path to the image")
args = vars(ap.parse_args())
# load the image
image = cv2.imread(args["image"])
# define the list of boundaries
boundaries = [
([180, 180, 100], [255, 255, 255])
]
# loop over the boundaries
for (lower, upper) in boundaries:
# create NumPy arrays from the boundaries
lower = np.array(lower, dtype = "uint8")
upper = np.array(upper, dtype = "uint8")
# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(image, lower, upper)
output = cv2.bitwise_and(image, image, mask = mask)
# show the images
cv2.imshow("images", np.hstack([image, output]))
cv2.waitKey(0)
gray = cv2.cvtColor(output,cv2.COLOR_BGR2GRAY)
kernel_size = 5
blur_gray = cv2.GaussianBlur(gray,(kernel_size, kernel_size),0)
low_threshold = 10
high_threshold = 200
edges = cv2.Canny(gray, low_threshold, high_threshold)
dilated = cv2.dilate(edges, np.ones((2,2), dtype=np.uint8))
cv2.imshow('dilated.png', dilated)
cv2.waitKey(0)
rho = 1 # distance resolution in pixels of the Hough grid
theta = np.pi / 180 # angular resolution in radians of the Hough grid
threshold = 10 # minimum number of votes (intersections in Hough grid cell)
min_line_length = 40 # minimum number of pixels making up a line
max_line_gap = 5 # maximum gap in pixels between connectable line segments
line_image = np.copy(output) * 0 # creating a blank to draw lines on
# Run Hough on edge detected image
# Output "lines" is an array containing endpoints of detected line segments
lines = cv2.HoughLinesP(dilated, rho, theta, threshold, np.array([]), min_line_length, max_line_gap)
points = []
for line in lines:
for x1, y1, x2, y2 in line:
points.append(((x1 + 0.0, y1 + 0.0), (x2 + 0.0, y2 + 0.0)))
cv2.line(line_image, (x1, y1), (x2, y2), (255, 0, 0), 5)
cv2.imshow('houghlines.png', line_image)
cv2.waitKey(0)
lines_edges = cv2.addWeighted(output, 0.8, line_image, 1, 0)
print(lines_edges.shape)
intersections = bot.isect_segments(points)
print(intersections)
for idx, inter in enumerate(intersections):
a, b = inter
match = 0
for other_inter in intersections[idx:]:
c, d = other_inter
if abs(c-a) < 8 and abs(d-b) < 8:
match = 1
if other_inter in intersections:
intersections.remove(other_inter)
intersections[idx] = ((c+a)/2, (d+b)/2)
if match == 0:
intersections.remove(inter)
for inter in intersections:
a, b = inter
for i in range(6):
for j in range(6):
lines_edges[int(b) + i, int(a) + j] = [0, 0, 255]
# Show the result
cv2.imshow('line_intersections.png', lines_edges)
cv2.imwrite('line_intersections.png', lines_edges)
cv2.waitKey(0)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-05T05:13:11.420",
"Id": "419514",
"Score": "4",
"body": "Is this code finished? The images you posted makes it look like it is, but your last paragraph indicates that it is incomplete and you are looking for help to get the last few intercepts, in which case it would be off topic here."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:27:27.343",
"Id": "216784",
"Score": "5",
"Tags": [
"python"
],
"Title": "Detecting tennis court lines intercepts"
} | 216784 |
<p>this is a really short code, but I'm trying to improve my Python skills. I've got a DataFrame, with a <code>week</code> variable, for every week I want to know the number of different <code>id</code>'s in that week, and then get the maximum number of id's among all weeks. I achieve that doing this:</p>
<pre><code>listt=[]
for i in range(df.week.max()):
listt.append(df[df.week==i].id.nunique())
np.array(listt).max()
</code></pre>
<p>It feels to me that this can probably be done in a one-liner. How would you do it? Thanks</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:16:10.200",
"Id": "419354",
"Score": "0",
"body": "Thanks @MathiasEttinger, should have read that before posting. Is the title okay right now?"
}
] | [
{
"body": "<p>Instead of iterating through each possible week and filtering your dataframe, you should use <a href=\"http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\" rel=\"nofollow noreferrer\"><code>df.groupby</code></a> and work from there using convenience methods on the results:</p>\n\n<pre><code>df.groupby('week').id.nunique().max()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:24:47.897",
"Id": "419355",
"Score": "0",
"body": "I knew it could be done way easily. Thanks again, Mathias"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:21:45.527",
"Id": "216791",
"ParentId": "216787",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216791",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T14:53:10.640",
"Id": "216787",
"Score": "1",
"Tags": [
"python"
],
"Title": "Finding the maximum number of id's among all weeks available"
} | 216787 |
<p>I am making a data-driven bond screening and I have as input a big dataset of 1526 columns and 2412 rows. For 10 columns it takes 2 minutes processing time at the moment, which is too much. The following function takes 90% of the time:</p>
<p>Input of the function is df: a pandas series, where the index is a time series and the first column has floats, like this:</p>
<p><a href="https://imgur.com/a/3pQSQZC" rel="nofollow noreferrer">https://imgur.com/a/3pQSQZC</a></p>
<pre><code>def future_returns(df):
grid_columns = np.arange(len(df))
grid = pd.DataFrame(index=df.index, columns=grid_columns)
# fill grid with copies of df, shifted 1 element forward for each column
for no, idx in enumerate(grid.columns):
grid.loc[:, idx] = df.shift(-no)
# calculate future returns from every point in the index
future_returns = grid.divide(grid.iloc[:, 0], axis=0) - 1
return future_returns
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:45:13.863",
"Id": "419362",
"Score": "3",
"body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226) Also, question titles should reflect the purpose of the code, not how you wish to have it reworked. See [ask] for examples."
}
] | [
{
"body": "<h1>code</h1>\n\n<p>Your code itself is clear, with and has only a few improvements</p>\n\n<h2><code>df</code></h2>\n\n<p>your parameter <code>df</code> expects actually a <code>Series</code>, and not a <code>DataFrame</code>, so I would rename this.</p>\n\n<h2>composition</h2>\n\n<p>now you first make an empty <code>DataFrame</code> and then change the values. More clear would be to generate it directly with the correct data:</p>\n\n<pre><code>def future_returns_2(data):\n grid = pd.DataFrame(\n index=data.index, \n columns=np.arange(len(data)), \n data=[data.shift(-i).values for i in range(len(data))],\n )\n return grid.divide(data, axis=0) - 1\n</code></pre>\n\n<p>Conveniently, this is also about faster</p>\n\n<h1>numpy</h1>\n\n<p>If you really want it a lot faster, you should stay in the <code>numpy</code> space for as long as possible, and only generate the <code>DataFrame</code> at the last possible time.</p>\n\n<p>You can use <code>numpy.roll</code></p>\n\n<pre><code>arr = data.values\nresult = np.array(\n [np.roll(arr, -i) for i in range(len(arr))],\n copy=False,\n) / arr - 1 \n</code></pre>\n\n<p>Since <code>numpy.roll</code> doesn't make the lower triangle of the result <code>NaN</code>, You should add this yourself:</p>\n\n<pre><code>mask = np.rot90(np.tri(l,), k=-1)\nmask[np.where(1 - mask)] = np.nan\nmask\n</code></pre>\n\n<blockquote>\n<pre><code>array([[ 1., 1., 1., 1., 1.],\n [ 1., 1., 1., 1., nan],\n [ 1., 1., 1., nan, nan],\n [ 1., 1., nan, nan, nan],\n [ 1., nan, nan, nan, nan]])\n</code></pre>\n</blockquote>\n\n<p>Now you can deduct this <code>mask</code> instead of <code>1</code></p>\n\n<pre><code>def future_returns_numpy(data):\n arr = data.values\n l = len(arr)\n\n mask = np.rot90(np.tri(l), k=-1)\n mask[np.where(1 - mask)] = np.nan\n\n result = np.array(\n [np.roll(arr, -i) for i in range(l)], \n copy=False,\n ) / arr - mask\n\n return pd.DataFrame(data = result.T, index = data.index)\n</code></pre>\n\n<p>I find this code less clear than the <code>pandas</code> algorithm, but if speed is important, I would use this.</p>\n\n<h1>timings</h1>\n\n<p>For this dummy data</p>\n\n<pre><code>size=1000\nnp.random.seed(0)\ndata = pd.Series(\n np.random.random(size), \n index= pd.date_range(start='20190101', freq='1d', periods = size),\n)\n</code></pre>\n\n<blockquote>\n<pre><code>OP: 10.4 s ± 528 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\nfuture_returns_2: 722 ms ± 29.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\nfuture_returns_numpy: 79 ms ± 7.62 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-04T08:21:02.050",
"Id": "216841",
"ParentId": "216790",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:06:55.780",
"Id": "216790",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "speed up/optimize pandas code"
} | 216790 |
<p>So I wrote this to simulate a program that would have a start and stop feature, and has a <code>tab design</code>. Right now there is a tab that has a <code>RichEdit</code> object intended to be a running log.</p>
<p>As you can see, after we "start" the program I put just some milliseconds of <code>sleep</code> to simulate running instructions. I created a function to check for requests that would be called on a larger scale randomly throughout code to ping the <code>GUI</code> per say.</p>
<pre><code>#include <GUIConstantsEx.au3>
#include <GuiRichEdit.au3>
#include <WindowsConstants.au3>
Global Const $h_numOfTabs = 2
Global Enum $H_TAB_1, $H_TAB_2, $H_TAB_END
Global $hGui, $h_logRichEdit, $iMsg, $h_tabs, $h_startButton, $h_stopButton
Example()
Func Example()
$hGui = GUICreate("Example (" & StringTrimRight(@ScriptName, StringLen(".exe")) & ")", 400, 550, -1, -1)
; ADD START AND STOP BUTTONS
$h_startButton = GUICtrlCreateButton( "Start", 50, 450 )
$h_stopButton = GUICtrlCreateButton( "Stop", 150, 450 )
$h_tabs = GUICtrlCreateTab( 5, 5, 390,375 )
; LOG TAB
GUICtrlCreateTabItem( "Log" )
$h_logRichEdit = _GUICtrlRichEdit_Create ( $hGui, "", 8, 30, 384, 347, BitOR( $ES_MULTILINE, $WS_VSCROLL, $ES_AUTOVSCROLL, $ES_READONLY ) )
; STATS TAB
GUICtrlCreateTabItem( "Stats" )
; Close TABS
GUICtrlCreateTabItem( "" )
GUISetState( @SW_SHOW ) ; initialize the gui
While True
CheckRequests()
WEnd
EndFunc ;==>Example
Func Start()
while true
Sleep(100)
CheckRequests()
WEnd
EndFunc
Func Stop()
EndFunc
Func CheckRequests()
$iMsg = GUIGetMsg()
while $iMsg <> 0
Select
Case $iMsg = $GUI_EVENT_CLOSE
_GUICtrlRichEdit_Destroy($h_logRichEdit) ; needed unless script crashes
; GUIDelete() ; is OK too
Exit
Case $iMsg = $h_tabs
Switch GUICtrlRead( $h_tabs )
Case $H_TAB_1
ControlShow( $hGui, "", $h_logRichEdit )
Case Else
ControlHide( $hGui, "", $h_logRichEdit )
EndSwitch
Case $iMsg = $h_startButton
Start()
Case $iMsg = $h_stopButton
Stop()
EndSelect
$iMsg = GUIGetMsg()
WEnd
EndFunc
</code></pre>
<p><strong>At about 500ms sleep, the lag when switching tabs is visible.</strong></p>
<p><strong>My question:</strong> On a larger scale, is this how we would handle/update things that are specific to a tab while running a larger program? If not, what would be a more efficient way of updating tab specific properties while running a larger overall program. </p>
<p>I have also seen a design recently where all the tabs and related components were their own <code>GUI's</code> but I am not sure the relevance of everything being its own <code>GUI</code> and if it pertains to this question.</p>
<p>Any help or clarification is greatly appreciated, I am new to AutoIT and trying to figure out some do's and dont's as well as efficiency.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:34:33.473",
"Id": "216792",
"Score": "1",
"Tags": [
"performance",
"autoit"
],
"Title": "Optimizing Tab Control With AutoIT"
} | 216792 |
<p>I am trying to write <code>is_device_mounted</code> script, which in turn will serve a greater purpose in my home Linux system.</p>
<p>It does not even have an error reporting function included and as you can see, I have made it clean for readers. My intention here is to review the code for general Linux. But if you are on a *BSD, I would appreciate your feedback too!</p>
<hr>
<p><strong>The first version</strong> of the script follows:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/sh
set -eu
is_empty_string() { [ -z "${1}" ]; }
sanitize_device_string() { printf '%s' "${1}" | grep '^/dev/' | head -n 1; }
is_block_device() { [ -b "${1}" ]; }
is_device_uuid_identified() { printf '%s' "${1}" | grep -F '/by-uuid/'; }
translate_uuid_to_device_name() { readlink -f -n /dev/disk/by-uuid/"${1}"; }
is_device_mounted()
{
if [ -n "${device_name}" ]; then
# 1. basic regex should be working across platfotms
# tested on FreeBSD, OpenBSD, NetBSD with success
# I prefer the starting with (^) rather than filtering throung all text
# 2. /proc/mounts is not available on all *BSDs, needs revision
proc_mounts=$( grep "^${device_name} " /proc/mounts )
[ -n "${proc_mounts}" ]
fi
}
[ "${#}" -ne 1 ] && { echo "Invalid number of arguments."; exit 1; }
readonly raw_input_string=${1}
is_empty_string "${raw_input_string}" && { echo "The given argument is empty."; exit 1; }
readonly device_string=$( sanitize_device_string "${raw_input_string}" )
is_empty_string "${device_string}" && { echo "The given argument is not a device path."; exit 1; }
! is_block_device "${device_string}" && { echo "The given argument is not a block device."; exit 1; }
readonly block_device=${device_string}
if is_device_uuid_identified "${block_device}"
then
readonly device_name=$( translate_uuid_to_device_name "${block_device}" )
else
readonly device_name=${block_device}
fi
if is_device_mounted "${device_name}"
then
echo "The device: ${block_device} IS mounted."
else
echo "The device: ${block_device} IS NOT mounted."
fi
</code></pre>
| [] | [
{
"body": "<p>Nice work. I approve of <code>set -eu</code>, and the script pleases Shellcheck.</p>\n\n<p>Here's the things I'd consider changing.</p>\n\n<hr>\n\n<p>I think error messages should go to the error stream. Example:</p>\n\n<pre><code>[ \"${#}\" -ne 1 ] && { echo \"Invalid number of arguments.\" >&2; exit 1; }\n# ^^^ here\n</code></pre>\n\n<hr>\n\n<p>Instead of using the negation operator, I'd replace the form <code>! test && error</code> with plain <code>test || error</code> like this:</p>\n\n<pre><code>is_block_device \"${device_string}\" || { echo \"The given argument is not a block device.\" >&2; exit 1; }\n</code></pre>\n\n<hr>\n\n<p>The script <strong>doesn't work</strong> when I use other links to block devices, such as those in <code>/dev/disk/by-label</code>. I'd fix that by abandoning the <code>/by-uuid/</code> test, and instead following symlinks until a real file or dangling link is found:</p>\n\n<pre><code>resolve_symlink() {\n f=\"$1\"\n while [ -h \"$f\" ]\n do f=$(readlink -f -n \"$f\")\n done\n printf '%s' \"$f\"\n}\n</code></pre>\n\n\n\n<pre><code>is_empty_string \"${device_string}\" && { echo \"The given argument is not a device path.\" >&2; exit 1; }\nis_block_device \"${device_string}\" || { echo \"The given argument is not a block device.\" >&2; exit 1; }\n\nreadonly device_name=$(resolve_symlink \"$device_string\")\n\nif is_device_mounted \"$device_name\"\nthen\n</code></pre>\n\n<hr>\n\n<p>Why does <code>is_device_mounted</code> ignore its argument and use <code>$device_name</code> instead?</p>\n\n<hr>\n\n<p>Minor issue: we assume that the block device name contains no regex metacharacters here:</p>\n\n<pre><code>grep \"^${device_name} \"\n</code></pre>\n\n<p>That's probably a fair assumption on a non-weird Linux system; I normally use Awk for robust versions such tests (<code>$1 = $device_name</code>, with a suitable <code>-v</code> option) but I don't know how well that meets your portability goals.</p>\n\n<p>If using <code>grep</code> (without the non-standard <code>-q</code> option), then it's usual to discard the output, and use <code>grep</code>'s exit status directly, rather than capturing the output and testing it's non-empty.</p>\n\n<hr>\n\n<p>Minor/style: I'm not a big fan of using braces for every variable expansion. I prefer to reserve them for when they are really needed, and that seems to be the usual idiom.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T16:43:05.593",
"Id": "216799",
"ParentId": "216794",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "216799",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-03T15:46:42.500",
"Id": "216794",
"Score": "3",
"Tags": [
"linux",
"posix",
"sh"
],
"Title": "Is device mounted? Both UUID and device names accepted"
} | 216794 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.