body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>So I've been learning about MVVM and I had a problem. I often had to start a thread to download or do some longer task in background and when it is done change some properties so the UI updates. The problem is that the UI will update only if I changed it from the main thread. So I often had to create DispatchTimers to wait for the thread to finish and then execute some code in main. Well this is my solution to it.</p>
<p>With this class you can simply go to your ViewModel constructor and do something like this:</p>
<pre><code>ViewModelEventHandler.RegisterEventListener("EventName", EventAction);
</code></pre>
<p>EventAction being an action that is executed when the event is raised.
You can simply create an async Task that does its work in the background and it raises the event "EventName" and then EventAction() is executed in main thread. You just have to put <code>new ViewModelEventHandler();</code> inside your main function.</p>
<p>I also use it a lot for communication between view models. You can raise an event in view model A and a completely unrelated view model B can execute code.</p>
<p>Here is my code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Threading;
namespace MVVM {
public class EventData < T1, T2 > {
public T1 eventState {
get;
set;
}
public T2 subs {
get;
set;
}
}
class ViewModelEventHandler {
// holds all events and their subscribed actions, the string is the event name, bool keeps track of if the event is currently raised, and List<Action> holds all the functions that will be executed when the event is raised
private static Dictionary < string, EventData < bool, List<Action> >> eventList = new Dictionary < string, EventData <bool,List<Action> >> ();
public ViewModelEventHandler() {
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(1);
timer.Tick += eventListen_Tick;
timer.Start();
}
public static void RaiseEvent(string eventName) {
try {
eventList[eventName].eventState = true;
}
catch {}
}
public static void RegisterEventListener(string eventName, Action eventMethod) {
foreach(var regEvent in eventList) {
if (regEvent.Key == eventName) {
eventList[eventName].subs.Add(eventMethod);
return;
}
}
eventList[eventName] = new EventData < bool, List < Action >> ();
eventList[eventName].eventState = false;
eventList[eventName].subs = new List < Action > ();
eventList[eventName].subs.Add(eventMethod);
}
public static void RemoveEventListener(string eventName, Action eventMethod) {
try {
eventList[eventName].subs.Remove(eventMethod);
}
catch {}
}
public static void RemoveEvent(string eventName) {
try {
eventList.Remove(eventName);
}
catch {}
}
private void eventListen_Tick(object sender, EventArgs e) {
foreach(var ev in eventList) {
if (ev.Value.eventState) {
ev.Value.eventState = false;
foreach(Action eventSub in ev.Value.subs) {
eventSub();
}
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T14:09:58.273",
"Id": "485502",
"Score": "0",
"body": "Why not use Dispatcher.BeginInvoke? I'm not a big fan of events like this as it make the code flow harder to see what is happening. You can just await or even do a continguewith and then once done trigger the Dispatcher.BeginInvoke passing in the same method you would have added to your event."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-16T07:12:51.317",
"Id": "488929",
"Score": "0",
"body": "Get rid of those empty try catch blocks. It's a terrible habit. If an exception happens you will want to know about it. Consuming the exception and doing nothing will not make the code resilient; after an exception the state of the application might be incomplete or corrupt. Could lead to cascading failure and data corruption while also being difficult to pinpoint the problem."
}
] |
[
{
"body": "<p>Your approach is wrong. It creates too complex code for a very simple and common problem. To use a sort of event aggregator to report progress is overkill.</p>\n<p>First notice that you generally distinguish between IO bound tasks and CPU bound tasks. CPU bound tasks are executed on a background thread. The performance of CPU bound tasks can be improved by using multi threading. For example calculations are CPU bound.<br />\nCPU bound tasks should be executed in parallel using background threads.</p>\n<p>Reading from a file or download data are IO bound tasks. The performance of IO bound tasks cannot be improved using multiple threads, but by improving the IO devices. For example a download's performance is not limited by available CPU resources, but transfer rate or other network conditions and hardware. Using a thread for IO bound tasks is a waste of resources, since IO bound operations generally require almost no CPU resources.<br />\nIO bound tasks should be executed asynchronously or event-driven.</p>\n<p>This means you should check the library you are using to download resources for asynchronous methods and await them e.g. <code>await DownloadAsync()</code>. Alternatively subscribe to corresponding API events e.g. <code>DownloadProgressChanged</code>. Every modern UI related API exposes asynchronous methods.</p>\n<p>Since all <code>DispatcherObject</code> objects are associated with a <code>Dispatcher</code> and each thread has its own <code>Dispatcher</code>, you can't use or access a <code>DispatcherObject</code> on a different thread then the thread the <code>DispatcherObject</code> was created on. Except the <code>DispatcherObject</code> derives from <code>Freezable</code> and is in a frozen state.<br />\nTo access a <code>DispatcherObject</code> from a different thread you must use the associated <code>Dispatcher</code>.</p>\n<p>The following examples show how to update e.g., a <code>Progressbar</code> from a background thread:</p>\n<p><strong>MainWindow.xaml</strong></p>\n<pre><code><Window>\n <Progressbar x:Name="CompressionProgressbar" />\n</Window>\n</code></pre>\n<p><strong>MainWindow.xaml.cs</strong></p>\n<pre><code>private async Task CompressData()\n{\n // Start a background thread\n await Task.Run(() =>\n {\n // Access the DispatcherObject from a background thread \n // using the associated Dispatcher\n this.Dispatcher.InvokeAsync(() => this.CompressionProgressbar.Value = 33.33);\n });\n}\n</code></pre>\n<p>Since .NET 4.5 the recommended approach is to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.iprogress-1?view=netcore-3.1\" rel=\"nofollow noreferrer\"><code>IProgress<T></code></a> to report progress (or delegate data back to the UI thread). The library offers a ready to use implementation, the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.progress-1?view=netcore-3.1\" rel=\"nofollow noreferrer\"><code>Progress<T></code></a> class. The constructor captures the current <code>SynchronizationContext</code> to post the registered callback to it. Therefore it is important to create the instance on the UI thread and then pass it to the background thread.</p>\n<pre><code>private async Task CompressData()\n{\n // Create an instance of Progress<T> using the constructor\n // to register the callback which will be executed on the current thread e.g. to report the progress\n var progressReporter = new Progress<double>(progressValue => this.CompressionProgressbar.Value = progressValue);\n\n // Start a background thread\n await Task.Run(() =>\n {\n // Access the DispatcherObject from a background thread \n // using the IProgress<T> instance\n progressReporter.Report(33.33);\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T22:13:55.567",
"Id": "498637",
"Score": "0",
"body": "A reference for CPU/IO-bound - [Asynchronous Programming](https://docs.microsoft.com/en-us/dotnet/csharp/async)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-02T22:18:33.303",
"Id": "498639",
"Score": "0",
"body": "I don't recommend `Dispatcher` because it makes code weird (unless the code is fully SRP-designed but it's pretty rare thing). `IProgress` is best, snd as slternative some Producer/Consumer implementation, especially modern async one e.g. `IAsyncEnumerable` or `System.Threading.Channels`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-03T13:53:12.387",
"Id": "498709",
"Score": "1",
"body": "I agree. I also recommend the `IProgress<T>` over the `Dispatcher` (see my answer). I have added the `Dispatcher` example for completeness. The fact that the `Dispatcher` (for the main STA thread) is globally available via the static `Application.Current` reference can lead to bad code design. But there are situations where the `Dispatcher` provides more flexibility. It allows to dispatch delegates using a priority, which can be handy at times. Channels are quite efficient, but they don't solve the problem of referencing `DispatcherObject` instances across threads."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T21:05:30.927",
"Id": "247968",
"ParentId": "247884",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T07:13:00.920",
"Id": "247884",
"Score": "0",
"Tags": [
"c#",
"event-handling",
"wpf",
"mvvm"
],
"Title": "C# Event handler for WPF MVVM"
}
|
247884
|
<p>The Django ModelAdmin offers a <code>filter_horizontal</code> (or <code>filter_vertical</code>) <a href="https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.filter_horizontal" rel="nofollow noreferrer">interface</a> for many-to-many relations, which allows the user to filter a list of available related objects.</p>
<p>My goal is to limit the set of choices for this interface, dynamically, based on the value of another form field.</p>
<p>This is somewhat similar to <a href="https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_manytomany" rel="nofollow noreferrer">filtering the form field queryset</a> or using <a href="https://docs.djangoproject.com/en/3.1/ref/models/fields/#django.db.models.ManyToManyField.limit_choices_to" rel="nofollow noreferrer">limit_choices_to</a> on the server side, but I want to do it dynamically, on the client side.</p>
<p>The implementation is supposed to be generic, because it is re-used on a variety of admin forms.</p>
<p>An example of the <code>filter_horizontal</code> interface is shown below (together with a normal select box).</p>
<p><a href="https://i.stack.imgur.com/JIqNv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JIqNv.png" alt="the filter_horizontal interface" /></a></p>
<p>Based on the source for Django's JavaScript filter interface, viz. <a href="https://github.com/django/django/blob/stable/3.1.x/django/contrib/admin/static/admin/js/SelectFilter2.js" rel="nofollow noreferrer">SelectFilter2.js</a> and <a href="https://github.com/django/django/blob/stable/3.1.x/django/contrib/admin/static/admin/js/SelectBox.js" rel="nofollow noreferrer">SelectBox.js</a>, I came up with the following JavaScript function:</p>
<pre><code>function updateOptionsDisplay(fieldId, allowableOptions) {
// fieldId is the id of the original <select> element, typically 'id_<model field name>'
// allowableOptions is an array of allowable object id strings
for (let side of ['_from', '_to']) {
// window.SelectBox is set in django's SelectBox.js
for (let option of window.SelectBox.cache[fieldId + side]) {
// option is an object with value, text, and displayed properties, not an HTMLOptionElement
// type of option.displayed in django source is int, not boolean, hence the Number()
option.displayed = Number(allowableOptions.includes(option.value));
}
window.SelectBox.redisplay(fieldId + side);
}
}
</code></pre>
<p>This function shows existing <code><option></code> elements if their value is in the <code>allowableOptions</code> array, and hides them otherwise.</p>
<p>The content of the <code>allowableOptions</code> array is a function of the value of another form element, e.g. another select box, and is obtained using AJAX in some cases, or from template context in other cases.</p>
<p>This seems to work well, and it also "remembers" previously selected choices.</p>
<p>However, I wonder if there may be some unexpected side effects. Also, any comments with respect to the JavaScript itself would be very welcome.</p>
<p>The whole thing is implemented by extending the admin <code>change_form.html</code> template, as described in the <a href="https://docs.djangoproject.com/en/3.1/ref/contrib/admin/javascript/#javascript-customizations-in-the-admin" rel="nofollow noreferrer">documentation</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T09:18:23.690",
"Id": "247889",
"Score": "1",
"Tags": [
"javascript",
"django"
],
"Title": "Limit choices for Django admin filter_horizontal interface"
}
|
247889
|
<h2>Intro</h2>
<p>If you want to know, then about 10+ years ago, I started a journey on the (<em>best</em> in my country) color picker for WinXP, later Win7. Since now it is hardly compatible with Win10 and HiDPI (work in progress), and in no way compilable in Linux using Lazarus, it would take quite an effort to create a decent desktop color picker with zoom and everything on Linux. But first things first - in this question I would like to start with basic color class, i.e. class capable of holding single color, and providing easy access to each color component, except for hue sat lum, which I'm not able to program, and am not asking you to point me to any direction. At the bottom I attached this code to existing color picker for windows just to show what it is doing. I want to start from scratch and maybe re-invent the wheel just to practice my brain.</p>
<hr />
<h2>TBasicColor class</h2>
<pre class="lang-delphi prettyprint-override"><code>unit basic_color;
interface
uses
Graphics;
type
TBasicColor = class
strict private
FColorRef: TColor;
protected
function GetColorRef: Integer;
function GetRed: Byte;
function GetGreen: Byte;
function GetBlue: Byte;
function GetCyan: Byte;
function GetMagenta: Byte;
function GetYellow: Byte;
public
constructor Create; reintroduce;
constructor CreateRandom;
constructor CreateColorUsingRGB(const ARed, AGreen, ABlue: Byte);
constructor CreateColorUsingCMY(const ACyan, AMagenta, AYellow: Byte);
property ColorRef: Integer read GetColorRef;
property Red: Byte read GetRed;
property Green: Byte read GetGreen;
property Blue: Byte read GetBlue;
property Cyan: Byte read GetCyan;
property Magenta: Byte read GetMagenta;
property Yellow: Byte read GetYellow;
end;
implementation
constructor TBasicColor.Create;
begin
inherited Create;
// implicitly initialize to white color
CreateColorUsingRGB(255, 255, 255);
end;
constructor TBasicColor.CreateRandom;
begin
inherited Create;
FColorRef := Random($FFFFFF + 1);
end;
constructor TBasicColor.CreateColorUsingRGB(const ARed, AGreen, ABlue: Byte);
begin
inherited Create;
FColorRef := ARed or (AGreen shl 8) or (ABlue shl 16);
end;
constructor TBasicColor.CreateColorUsingCMY(const ACyan, AMagenta, AYellow: Byte);
begin
CreateColorUsingRGB(255 - ACyan, 255 - AMagenta, 255 - AYellow);
end;
function TBasicColor.GetColorRef: Integer;
begin
Result := Integer(FColorRef);
end;
function TBasicColor.GetRed: Byte;
begin
Result := Byte(FColorRef);
end;
function TBasicColor.GetGreen: Byte;
begin
Result := Byte(FColorRef shr 8);
end;
function TBasicColor.GetBlue: Byte;
begin
Result := Byte(FColorRef shr 16);
end;
function TBasicColor.GetCyan: Byte;
begin
Result := 255 - GetRed;
end;
function TBasicColor.GetMagenta: Byte;
begin
Result := 255 - GetGreen;
end;
function TBasicColor.GetYellow: Byte;
begin
Result := 255 - GetBlue;
end;
end.
</code></pre>
<hr />
<h2>Screenshot from Windows</h2>
<p><a href="https://i.stack.imgur.com/qhkGa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qhkGa.png" alt="Screenshot from Windows" /></a></p>
<hr />
<p>Whatever you answer, I value all input. Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-01T10:00:07.390",
"Id": "516063",
"Score": "0",
"body": "A bit late, but here it goes ;-) I wouldn't make this a class but an advanced record a.ka. a record with methods."
}
] |
[
{
"body": "<h1>Self-review</h1>\n<hr />\n<h2><code>Randomize</code> missing</h2>\n<p>Since I use <code>Random</code> to generate pseudo-random color, it is, I lightly remember, a must to call <code>Randomize</code> once program or unit in this case is being created; <a href=\"http://www.delphibasics.co.uk/RTL.asp?Name=Randomize\" rel=\"nofollow noreferrer\">more information</a>.</p>\n<pre><code>// ...\n\ninitialization\n Randomize;\n\nend.\n</code></pre>\n<hr />\n<h2>Get... Red, Green, Blue, Cyan, Magenta, Yellow</h2>\n<p>These seem to operate as expected.</p>\n<hr />\n<h2><code>constructor</code>s</h2>\n<p>The biggest error I already see I have made is the <code>constructor</code> <em>thing</em>. The problem is I did not write one for direct <code>TColor</code> assignment. It could be re-written for instance like this in the <code>interface</code>:</p>\n<pre><code>type\n TBasicColor = class\n // ...\n public\n // default direct TColor assignment constructor\n constructor Create(const AColor: TColor); overload;\n // reintroduce is hiding TObject constructor\n constructor Create; reintroduce; overload;\n // create using RGB values\n constructor CreateRGB(const ARed, AGreen, ABlue: Byte);\n // create using CMY values\n constructor CreateCMY(const ACyan, AMagenta, AYellow: Byte);\n // create pseudo-random color constructor\n constructor CreateRandom;\n // ...\n</code></pre>\n<p>Plus, like this in the <code>implementation</code>:</p>\n<pre><code>constructor TBasicColor.Create(const AColor: TColor);\nbegin\n // in here it is just plain assignment\n inherited Create;\n FColorRef := AColor;\nend;\n\nconstructor TBasicColor.Create;\nbegin\n // in case anyone just calls Create() we assign white color\n Create($FFFFFF);\nend;\n\nconstructor TBasicColor.CreateRGB(const ARed, AGreen, ABlue: Byte);\nbegin\n Create(ARed or (AGreen shl 8) or (ABlue shl 16));\nend;\n\nconstructor TBasicColor.CreateCMY(const ACyan, AMagenta, AYellow: Byte);\nbegin\n CreateRGB(255 - ACyan, 255 - AMagenta, 255 - AYellow);\nend;\n\nconstructor TBasicColor.CreateRandom;\nbegin\n Create(Random($FFFFFF + 1));\nend;\n</code></pre>\n<p>As you can see, all, in the end, are calling the <em>default</em> <code>constructor</code>, which I see as much better implementation.</p>\n<hr />\n<h2><code>overload</code> keyword</h2>\n<p>Note on <code>overload</code> keyword, I originally did not need it in Lazarus, but Delphi requires it.</p>\n<hr />\n<h2>Comments</h2>\n<p>By the way, I should really use more comments, they will prove useful one day, once I read it after years.</p>\n<hr />\n<h2>Why read-only ColorRef?</h2>\n<p>On second thought, I see no reason for the ColorRef not being able to change at runtime, I find it hard to see what reason I had before, but no matter, it should stay a private member with properties to safely read and write, also the typecast might be <em>wrong</em>, cannot confirm or disprove at this point, best to typecast when necessary in-place.</p>\n<p>For example with private method <code>Assign</code>:</p>\n<pre><code>procedure TBasicColor.Assign(const ColorRef: TColor);\nbegin\n if (ColorRef < 0) or (ColorRef > $FFFFFF)\n then raise ERangeError.Create('ERangeError in TBasicColor class.' + sLineBreak +\n 'It supports only subset of TColor range.' + sLineBreak +\n 'Valid range is <0; $FFFFFF>.')\n else FColorRef := ColorRef;\nend;\n</code></pre>\n<p>which can in turn be used in the SetColorRef <em>setter</em>:</p>\n<pre><code>procedure TBasicColor.SetColorRef(const ColorRef: TColor);\nbegin\n Assign(ColorRef);\nend;\n</code></pre>\n<hr />\n<h2><code>ARed</code> change to <code>Red</code>, etc.</h2>\n<p>I believe it's a habit or style point, but anyway.</p>\n<p>I removed, and am no longer a fan of an <code>A</code> prefixing, changed to this:</p>\n<pre><code>constructor TBasicColor.CreateRGB(const Red, Green, Blue: Byte);\nconstructor TBasicColor.CreateCMY(const Cyan, Magenta, Yellow: Byte);\n</code></pre>\n<hr />\n<h2>Modified code</h2>\n<p>After a few other adjustments, I will name only the use of <em>setters</em> in all color components, this unit could be re-written finally to this state:</p>\n<pre><code>unit basic_color;\n\ninterface\n\nuses\n Graphics, SysUtils;\n\ntype\n TBasicColor = class\n strict private\n FColorRef: TColor;\n private\n // TColor assignment with range check <0; $FFFFFF>\n procedure Assign(const ColorRef: TColor);\n // independent function needed (Delphi/Lazarus; Windows/Linux)\n function RGBToColor(const Red, Green, Blue: Byte): TColor;\n protected\n function GetColorRef: TColor;\n procedure SetColorRef(const ColorRef: TColor);\n function GetRed: Byte;\n procedure SetRed(const NewRed: Byte);\n function GetGreen: Byte;\n procedure SetGreen(const NewGreen: Byte);\n function GetBlue: Byte;\n procedure SetBlue(const NewBlue: Byte);\n function GetCyan: Byte;\n procedure SetCyan(const NewCyan: Byte);\n function GetMagenta: Byte;\n procedure SetMagenta(const NewMagenta: Byte);\n function GetYellow: Byte;\n procedure SetYellow(const NewYellow: Byte);\n public\n // default direct TColor assignment\n constructor Create(const ColorRef: TColor); overload;\n // reintroduce is hiding TObject default constructor\n constructor Create; reintroduce; overload;\n // create color using RGB values\n constructor CreateRGB(const Red, Green, Blue: Byte);\n // create color using CMY values\n constructor CreateCMY(const Cyan, Magenta, Yellow: Byte);\n // create pseudo-random color\n constructor CreateRandom;\n property ColorRef: TColor read GetColorRef write SetColorRef;\n property Red: Byte read GetRed write SetRed;\n property Green: Byte read GetGreen write SetGreen;\n property Blue: Byte read GetBlue write SetBlue;\n property Cyan: Byte read GetCyan write SetCyan;\n property Magenta: Byte read GetMagenta write SetMagenta;\n property Yellow: Byte read GetYellow write SetYellow;\n end;\n\nimplementation\n\nprocedure TBasicColor.Assign(const ColorRef: TColor);\nbegin\n if (ColorRef < 0) or (ColorRef > $FFFFFF)\n then raise ERangeError.Create('ERangeError in TBasicColor class.' + sLineBreak +\n 'It supports only subset of TColor range.' + sLineBreak +\n 'Valid TBasicColor range is <0; $FFFFFF>.')\n else FColorRef := ColorRef;\nend;\n\nfunction TBasicColor.RGBToColor(const Red, Green, Blue: Byte): TColor;\nbegin\n Result := Red or (Green shl 8) or (Blue shl 16);\nend;\n\nconstructor TBasicColor.Create(const ColorRef: TColor);\nbegin\n // in here it is just plain assignment\n inherited Create;\n Assign(ColorRef);\nend;\n\nconstructor TBasicColor.Create;\nbegin\n // in case anyone just calls Create() we assign white color\n Create($FFFFFF);\nend;\n\nconstructor TBasicColor.CreateRGB(const Red, Green, Blue: Byte);\nbegin\n Create(RGBToColor(Red, Green, Blue));\nend;\n\nconstructor TBasicColor.CreateCMY(const Cyan, Magenta, Yellow: Byte);\nbegin\n CreateRGB(255 - Cyan, 255 - Magenta, 255 - Yellow);\nend;\n\nconstructor TBasicColor.CreateRandom;\nbegin\n Create(Random($FFFFFF + 1));\nend;\n\nfunction TBasicColor.GetColorRef: TColor;\nbegin\n Result := FColorRef;\nend;\n\nprocedure TBasicColor.SetColorRef(const ColorRef: TColor);\nbegin\n Assign(ColorRef);\nend;\n\nfunction TBasicColor.GetRed: Byte;\nbegin\n Result := Byte(FColorRef);\nend;\n\nprocedure TBasicColor.SetRed(const NewRed: Byte);\nbegin\n Assign(RGBToColor(NewRed, GetGreen, GetBlue));\nend;\n\nfunction TBasicColor.GetGreen: Byte;\nbegin\n Result := Byte(FColorRef shr 8);\nend;\n\nprocedure TBasicColor.SetGreen(const NewGreen: Byte);\nbegin\n Assign(RGBToColor(GetRed, NewGreen, GetBlue));\nend;\n\nfunction TBasicColor.GetBlue: Byte;\nbegin\n Result := Byte(FColorRef shr 16);\nend;\n\nprocedure TBasicColor.SetBlue(const NewBlue: Byte);\nbegin\n Assign(RGBToColor(GetRed, GetGreen, NewBlue));\nend;\n\nfunction TBasicColor.GetCyan: Byte;\nbegin\n Result := 255 - GetRed;\nend;\n\nprocedure TBasicColor.SetCyan(const NewCyan: Byte);\nbegin\n SetRed(255 - NewCyan);\nend;\n\nfunction TBasicColor.GetMagenta: Byte;\nbegin\n Result := 255 - GetGreen;\nend;\n\nprocedure TBasicColor.SetMagenta(const NewMagenta: Byte);\nbegin\n SetGreen(255 - NewMagenta);\nend;\n\nfunction TBasicColor.GetYellow: Byte;\nbegin\n Result := 255 - GetBlue;\nend;\n\nprocedure TBasicColor.SetYellow(const NewYellow: Byte);\nbegin\n SetBlue(255 - NewYellow);\nend;\n\ninitialization\n Randomize;\n\nend.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T12:44:24.703",
"Id": "247899",
"ParentId": "247890",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247899",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T09:45:08.437",
"Id": "247890",
"Score": "3",
"Tags": [
"classes",
"delphi",
"object-pascal"
],
"Title": "Basic Color class for both Delphi and Lazarus"
}
|
247890
|
<p>I am starting up a project with some people, because there will be developed for and on multiple platforms we chose to use CMake to build our project. Because the project will get quite large we are trying to have a good setup but we lack the experience needed in CMake to make well thought out decisions.</p>
<p>We are using vcpkg for installing and using package as described as best practice to use it as submodule in combination with cmake.</p>
<p>We are mostly looking for the following answers.</p>
<ul>
<li>Does the directory structure hold up when the project gets larger.</li>
<li>Should all header files be in the includes directory or only the public ones.</li>
<li>Does this project use the proper modern CMake conventions.</li>
<li>Is vcpkg a the right choice for these kind of projects(multi-platform)</li>
<li>for now we have 2 libraries(Cheetah.Engine and Cheetah.Editor) we suspect it will be a lot more, could it be smart to seperate these libraries to their own projects?</li>
</ul>
<p><strong>Our directory structure</strong>:<br />
<a href="https://i.stack.imgur.com/zmo3a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zmo3a.png" alt="image of directory srtucture" /></a></p>
<p><strong>Root CMakeLists.txt</strong>:</p>
<pre><code># CMakeList.txt : Top-level CMake project file, do global configuration
# and include sub-projects here.
#
cmake_minimum_required (VERSION 3.18)
project ("Cheetah")
# Platform defines for all projects
IF (WIN32)
add_compile_definitions(CH_PLATFORM_WINDOWS)
ELSE()
# set stuff for other systems
ENDIF()
# Set ouput projects so no need to copy dll's after build
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Include sub-projects.
add_subdirectory ("Cheetah.Engine")
add_subdirectory ("Cheetah.Editor")
add_subdirectory ("Sandbox")
</code></pre>
<p><strong>Subdirectory CMakeLists.txt of Cheetah.Engine</strong>:</p>
<pre><code>cmake_minimum_required (VERSION 3.18)
add_library (Cheetah.Engine SHARED "")
# add sources
add_subdirectory("src")
add_subdirectory("includes")
# add includes
target_include_directories(Cheetah.Engine PRIVATE "${CMAKE_CURRENT_LIST_DIR}/includes")
# add macros
target_compile_definitions(Cheetah.Engine PRIVATE "CH_BUILD_DLL")
# add libraries
find_package(glad CONFIG REQUIRED)
target_link_libraries(Cheetah.Engine PRIVATE glad::glad)
find_package(glfw3 CONFIG REQUIRED)
target_link_libraries(Cheetah.Engine PRIVATE glfw3)
</code></pre>
<p><strong>Example of includes folder CMakeLists.txt</strong>:</p>
<pre><code>cmake_minimum_required (VERSION 3.18)
target_sources(Cheetah.Engine
INTERFACE
"Application.h"
"EntryPoint.h"
PRIVATE
"Core.h"
)
</code></pre>
<p>We are still debating if the core.h should be with the source files outside of the includes folder because it is a private header file.</p>
<p><strong>Example of source folder CMakeLists.txt</strong>:</p>
<pre><code>cmake_minimum_required (VERSION 3.18)
target_sources(Cheetah.Engine PRIVATE "Application.cpp")
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T10:07:29.550",
"Id": "247892",
"Score": "3",
"Tags": [
"c++",
"cmake"
],
"Title": "Modern CMake/c++ and vcpkg project setup for large projects"
}
|
247892
|
<p>Below is a json schema I have in elastic search</p>
<pre><code>{
"fullName": "",
"avatar": "",
"email": "",
"resumeLink": "",
"phone": "",
"role": "",
"noticePeriod": "",
"dateOfBirth": "",
"gender": "",
"maritalStatus": "",
"address": "",
"location": "",
"industryType": "",
"personalSummary": "",
"workSummary": "",
"functionalArea": "",
"currentPosition": "",
"currentEmployer": "",
"keySkills": [],
"otherSkills": [],
"iTSkill": [
{
"skill": "",
"version": ""
}
],
"highestEducationDetails": "",
"educationDetails": {
"Under graduation": {
"school": "",
"degreeType": ""
},
"Post graduation": {
"school": "",
"degreeType": ""
}
}
}
</code></pre>
<p>Below is a boolean query i wrote in java to search for keywords, and also search individual fields like Location, Role, addresses, skills and other fields in the json schema returnning a random_score for the documents</p>
<pre><code> if (Strings.isEmpty(searchQueryRequest.getText())) {
query = QueryBuilders.functionScoreQuery(QueryBuilders.matchAllQuery(), ScoreFunctionBuilders.randomFunction());//This line does not return random result;
} else {
query = QueryBuilders.boolQuery()
//.minimumShouldMatch(1)
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("location")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("location", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("role")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("role", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("functionalArea")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("functionalArea", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("workHistory.organization")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("workHistory.organization", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("workHistory.designation")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("workHistory.designation", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("keySkills")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("otherSkills")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("itSkill.skill")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText()).field("industryType")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("industryType", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText())
.field("educationDetails.Under graduation.school")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("educationDetails.Under graduation.school", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText())
.field("educationDetails.Under graduation.degreeType")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("educationDetails.Under graduation.degreeType", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText())
.field("educationDetails.Post graduation.school")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("educationDetails.Post graduation.school", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.simpleQueryStringQuery(searchQueryRequest.getText())
.field("educationDetails.Post graduation.degreeType")
.defaultOperator(Operator.OR), ScoreFunctionBuilders.randomFunction()))
.should(QueryBuilders.functionScoreQuery(QueryBuilders.matchPhraseQuery("educationDetails.Post graduation.degreeType", searchQueryRequest.getText()),
ScoreFunctionBuilders.randomFunction()));
}
</code></pre>
<p>How can i make this better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T11:49:50.417",
"Id": "485487",
"Score": "2",
"body": "By using a loop over all the strings, for which you do exactly the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T13:00:03.040",
"Id": "485497",
"Score": "0",
"body": "alright thanks, can you give me a `snippet` on how to go about it?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T11:28:35.430",
"Id": "247897",
"Score": "2",
"Tags": [
"java",
"spring",
"elasticsearch"
],
"Title": "Elastic search Java"
}
|
247897
|
<p>I wrote my first benchmark using Google Benchmark to check what is faster between the use of <code>std::string::length</code> and <code>strlen</code> to compute the length of a <code>std::string</code>.</p>
<p>I would like to know what I can improve in my code to use it as a base for future benchmarks. My main concerns are about:</p>
<ul>
<li>the creation of the <code>std::string</code> at the beginning of my functions: is it the right place to do it? Should I use fixtures? Or create a global <code>std::vector<std::string></code> that contains every strings I'll use for my benchmark?</li>
<li>the use of <code>benchmark::DoNotOptimize</code> and <code>benchmark::ClobberMemory</code>: I'm not sure I use these functions as I should. The idea is the following: I want to be sure the <code>std::string s</code> is created and stored into memory before entering in my loop and I want to be sure the functions <code>std::string::length</code> and <code>strlen</code> are really called and not optimized. Is it the good way to do it?</li>
<li>the use of <code>DenseRange</code> to create a benchmark with multiple length of string. At first, I wanted to pass an <code>std::string</code> directly to my function but, apparently, only <code>int</code> can be returned by <code>state.range</code>. Is there another way to pass a string to my functions?</li>
</ul>
<p>Here is my code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <benchmark/benchmark.h>
#include <string>
#include <cstring>
static void BM_InneficientBasicStringLength(benchmark::State& state)
{
std::string s;
for (int i = 0; i < state.range(0); i++)
s += 'a';
benchmark::DoNotOptimize(s.data());
benchmark::ClobberMemory();
size_t size;
for (auto _ : state)
{
benchmark::DoNotOptimize(size = strlen(s.c_str()));
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_InneficientBasicStringLength)->DenseRange(0, 100, 10);
static void BM_InneficientBasicStringLength_Fix(benchmark::State& state)
{
std::string s;
for (int i = 0; i < state.range(0); i++)
s += 'a';
benchmark::DoNotOptimize(s.data());
benchmark::ClobberMemory();
size_t size;
for (auto _ : state)
{
benchmark::DoNotOptimize(size = s.length());
benchmark::ClobberMemory();
}
}
BENCHMARK(BM_InneficientBasicStringLength_Fix)->DenseRange(0, 100, 10);
BENCHMARK_MAIN();
</code></pre>
<p>It compiles with: <code>g++ -o example example.cpp -lbenchmark -lpthread</code>.</p>
<hr />
<p><strong>EDIT:</strong> For your information, the results are better with <code>std::string::length</code> which have a constant complexity while <code>strlen</code> have
a linear complexity:</p>
<pre><code>> ./example
2020-08-14T14:48:17+02:00
Running ./example
Run on (12 X 3900 MHz CPU s)
CPU Caches:
L1 Data 32 KiB (x6)
L1 Instruction 32 KiB (x6)
L2 Unified 1024 KiB (x6)
L3 Unified 8448 KiB (x1)
Load Average: 5.18, 6.05, 6.32
----------------------------------------------------------------------------------
Benchmark Time CPU Iterations
----------------------------------------------------------------------------------
BM_InneficientBasicStringLength/0 4.79 ns 4.79 ns 150060775
BM_InneficientBasicStringLength/10 4.66 ns 4.66 ns 151148682
BM_InneficientBasicStringLength/20 5.39 ns 5.39 ns 136288403
BM_InneficientBasicStringLength/30 5.36 ns 5.35 ns 135353692
BM_InneficientBasicStringLength/40 5.19 ns 5.18 ns 137059957
BM_InneficientBasicStringLength/50 5.22 ns 5.22 ns 134737400
BM_InneficientBasicStringLength/60 5.32 ns 5.32 ns 134098029
BM_InneficientBasicStringLength/70 6.65 ns 6.65 ns 107061965
BM_InneficientBasicStringLength/80 6.85 ns 6.85 ns 109856173
BM_InneficientBasicStringLength/90 6.78 ns 6.78 ns 106762788
BM_InneficientBasicStringLength/100 6.66 ns 6.66 ns 98081332
BM_InneficientBasicStringLength_Fix/0 3.01 ns 3.01 ns 231875548
BM_InneficientBasicStringLength_Fix/10 3.06 ns 3.06 ns 221447369
BM_InneficientBasicStringLength_Fix/20 2.96 ns 2.96 ns 237989703
BM_InneficientBasicStringLength_Fix/30 2.98 ns 2.98 ns 234755616
BM_InneficientBasicStringLength_Fix/40 2.99 ns 2.98 ns 231015140
BM_InneficientBasicStringLength_Fix/50 2.94 ns 2.94 ns 223906062
BM_InneficientBasicStringLength_Fix/60 3.04 ns 3.04 ns 225199556
BM_InneficientBasicStringLength_Fix/70 3.07 ns 3.07 ns 230208201
BM_InneficientBasicStringLength_Fix/80 3.02 ns 3.02 ns 219373040
BM_InneficientBasicStringLength_Fix/90 3.10 ns 3.10 ns 219921248
BM_InneficientBasicStringLength_Fix/100 3.10 ns 3.10 ns 238076969
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T13:25:09.507",
"Id": "485500",
"Score": "2",
"body": "What did you find, could you post your results? I would expect string.length() to be much faster since it may only need to access an internal count that is made while the string is created."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T17:08:51.957",
"Id": "485525",
"Score": "1",
"body": "Are you trying to imitate perl? `for (auto _ : state)`. Don't be obtuse in your code it is supposed to be human readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T08:11:45.543",
"Id": "485560",
"Score": "1",
"body": "@MartinYork Almost all of the examples given on the GitHub of the project follow this pattern: https://github.com/google/benchmark#usage Whatever, what alternatives could I use?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:09:04.420",
"Id": "485580",
"Score": "0",
"body": "Benchmarking calculating the string length is not representative of real world code. Compilers will be able to optimize this if they know anything about the string. See [this example](https://godbolt.org/z/6zd814). I also wouldn't trust any results that only take a few nanoseconds, it's likely that despite Google Benchmark's best efforts to avoid that, these low numbers will include overhead from benchmarking itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T18:54:49.703",
"Id": "485595",
"Score": "0",
"body": "@G.Sliepen One of my concern is to avoid optimizations of the compiler. That's why I use `benchmark::DoNotOptimize` and `benchmark::ClobberMemory`. However, this is one of my questions: am I using this functions correctly in order to have a correct measure of `strlen` and `std::string::length`.\nAbout the duration of my benchmark, that's all the problem with microbenchmarking. The idea is to take a very little piece of code outside of its context to measure its efficiency. To prevent any issue about the reproducibility, we can see each measures are performed at least 98081332 times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T02:38:46.300",
"Id": "485699",
"Score": "0",
"body": "@Pierre I don't think appealing to google is a good argument for doing it. Google in my experience has never been good at defining the best C++ practices (though they eventually catch up to the industry). I would do something that expressed the intent of my actions. Every situation would be unique, but in this case maybe: `for (auto loopOver: state)` (expressing in english that we are looping over `state`. The point of code is to express your intent clearly to the next person that read the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T19:01:52.503",
"Id": "486460",
"Score": "0",
"body": "This benchmark is meaningless because `string::length()` simply returns stored counter while `strlen` has to go through the whole string to determine its length."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T19:12:25.283",
"Id": "486461",
"Score": "0",
"body": "@ALX23z I agree. My point was to write a first dummy benchmark to reuse the pattern for other and meaningful benchmarks."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T13:12:34.437",
"Id": "247900",
"Score": "3",
"Tags": [
"c++",
"benchmarking"
],
"Title": "std::string::length vs strlen using Google Benchmark"
}
|
247900
|
<p>this was my first thing i made on my own without any help. im sure theres a lot of improvement that could be made, i dont feel too confident about this. how can i make it shorter and more efficient? should this entire thing be rewritten in some other way? refactored? keep in mind if i wanted to add more birds to the list later. im also confused on when to use public, static, and void.</p>
<pre><code>class Bird
{
public string name;
public string size;
public string color;
public string habitat;
public Bird(string name, string size, string color, string habitat)
{
this.name = name;
this.size = size;
this.color = color;
this.habitat = habitat;
}
}
class Program
{
public static List<Bird> birds = new List<Bird>();
public static void CreateList()
{
birds.Add(new Bird("Bald Eagle", "large", "white", "America"));
birds.Add(new Bird("American Kestrel", "small", "brown", "America"));
birds.Add(new Bird("Mississippi Kite", "medium", "grey", "America"));
birds.Add(new Bird("Red Kite", "medium", "brown", "Europe"));
birds.Add(new Bird("Secretary Bird", "large", "grey", "Africa"));
birds.Add(new Bird("Shoebill Stork", "large", "grey", "Africa"));
birds.Add(new Bird("Cockatoo", "medium", "white", "Australia"));
}
public static void Start()
{
Console.WriteLine("Welcome to the Bird of prey identification helper.");
Console.WriteLine("(1) List of all birds and their descriptions\n(2) Identification help.\n");
string input;
do
{
Console.Write("Enter 1 or 2: ");
input = Console.ReadLine();
if (input == "1")
{
BirdList();
}
if (input == "2")
{
BirdQuestions();
}
} while (input != "1" && input != "2");
}
public static void BirdList()
{
Console.Clear();
foreach (var bird in birds)
Console.WriteLine("Name: {0} | Size: {1} | Main Color: {2} | Habitat Location: {3}", bird.name, bird.size, bird.color, bird.habitat);
}
public static string colorInput;
public static string sizeInput;
public static string habitatInput;
public static void BirdQuestions()
{
Console.Clear();
Console.WriteLine("This process will help you through identifying a bird you have seen.");
do
{
Console.WriteLine("\nWhat was the birds main color? Enter brown, grey, or white.");
Console.Write("Enter: ");
colorInput = Console.ReadLine();
} while (colorInput != "brown" && colorInput != "grey" && colorInput != "white");
do
{
Console.WriteLine("\nHow large or small was the bird? Enter small, medium, or large.");
Console.Write("Enter: ");
sizeInput = Console.ReadLine();
} while (sizeInput != "small" && sizeInput != "medium" && sizeInput != "large");
do
{
Console.WriteLine("\nWhere did you see the bird? Enter America, Australia, Europe, or Africa.");
Console.Write("Enter: ");
habitatInput = Console.ReadLine();
} while (habitatInput != "America" && habitatInput != "Australia" && habitatInput != "Africa" && habitatInput != "Europe");
BirdId();
}
public static void BirdId()
{
foreach (var bird in birds)
{
if (colorInput == bird.color && sizeInput == bird.size && habitatInput == bird.habitat)
{
Console.WriteLine("\n" + bird.name);
}
else
{
Console.WriteLine("\nNo birds found.");
break;
}
}
}
static void Main(string[] args)
{
CreateList();
Start();
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Welcome there new programmer :-)</p>\n<p>For the first piece of code it's looking good and of course a lot can be rewritten or done in a different way, but a lot of it also depends on someone's programming style/experience. Don't worry about it too much since this will improve more and more the longer you craft software.</p>\n<p>What I did is rewrite some parts of your code and put in some comments for you to learn from. Take a look at it and if you have questions just ask.</p>\n<p>What editor do you use? If you take a close look on what hints it gives you can also learn/improve your code!</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Bird\n{\n // Use properties instead of members. This is safer. Also start publics with a capital.\n // Most of the times the properties are public in (POCO) classes like this\n //\n // set; is also availble, but since we set it from the constructor we want this to be controlled like this.\n public string Name { get; }\n public string Size { get; }\n public string Color { get; }\n public string Habitat { get; }\n\n public Bird(string name, string size, string color, string habitat)\n {\n Name = name;\n Size = size;\n Color = color;\n Habitat = habitat;\n }\n}\n\nclass Program\n{\n // Use a collection initializer - it is cleaner code\n // Mark it as readonly so Birds cannot be overwritten somewhere (except in constructor)\n static readonly List<Bird> Birds = new List<Bird>\n {\n new Bird("Bald Eagle", "large", "white", "America"),\n new Bird("American Kestrel", "small", "brown", "America"),\n new Bird("Mississippi Kite", "medium", "grey", "America"),\n new Bird("Red Kite", "medium", "brown", "Europe"),\n new Bird("Secretary Bird", "large", "grey", "Africa"),\n new Bird("Shoebill Stork", "large", "grey", "Africa"),\n new Bird("Cockatoo", "medium", "white", "Australia")\n };\n\n // The list of possible actions I've put in a dictionary. This eliminates the manual writing of a lot of ifs\n static readonly Dictionary<string, Action> Actions = new Dictionary<string, Action>\n {\n {"1", BirdList}, \n {"2", BirdQuestions},\n };\n\n // Use private access modifier when only the containing class is using the method or property\n // Since this all is initiated in a static Main method you are bound to the static context\n // unless you instantiate a new object (class) inside that Main method; this can have plain public and private methods.\n // Check https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers\n // and https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members\n // for more info on this topic.\n private static void Start()\n {\n Console.WriteLine("Welcome to the Bird of prey identification helper.");\n Console.WriteLine("(1) List of all birds and their descriptions\\n(2) Identification help.\\n");\n\n string input;\n do\n {\n Console.Write("Enter 1 or 2: ");\n input = Console.ReadLine();\n if (Actions.ContainsKey(input))\n {\n Actions[input](); // call the action that belongs to the input (in Dictionary)\n }\n } while (!Actions.ContainsKey(input));\n }\n\n static void BirdList()\n {\n Console.Clear();\n foreach (var bird in Birds)\n Console.WriteLine(\n // Use string interpolation (with the $ before the ") so you can directly put in the variables in the string\n $"Name: {bird.Name} | Size: {bird.Size} | Main Color: {bird.Color} | Habitat Location: {bird.Habitat}");\n }\n\n static void BirdQuestions()\n {\n // Pass local variables to the next method - makes it more clear how the code flow is, instead of magically setted\n // values in some method and reads in other methods.\n string colorInput;\n string sizeInput;\n string habitatInput;\n\n Console.Clear();\n Console.WriteLine("This process will help you through identifying a bird you have seen.");\n\n // Prevent a lot of 'hard coded variables' - the options are based on the Birds list I assume\n // Let's get a distinct list of colors from the birds collection\n var colors = Birds.Select(s => s.Color).Distinct();\n \n // create a comma separated string of all the colors\n var colorsString = string.Join(", ", colors);\n do\n {\n Console.WriteLine($"\\nWhat was the birds main color? Enter {colorsString}.");\n Console.Write("Enter: ");\n colorInput = Console.ReadLine();\n } while (!colors.Contains(colorInput));\n\n // Now all the possible colors hard codings have been eliminated \n \n \n var sizes = Birds.Select(s => s.Size).Distinct();\n var sizesString = string.Join(", ", sizes);\n do\n {\n Console.WriteLine($"\\nHow large or small was the bird? Enter {sizesString}.");\n Console.Write("Enter: ");\n sizeInput = Console.ReadLine();\n } while (!sizes.Contains(sizeInput));\n\n var habitats = Birds.Select(s => s.Habitat).Distinct();\n var habitatsString = string.Join(", ", habitats);\n do\n {\n Console.WriteLine($"\\nWhere did you see the bird? Enter {habitatsString}.");\n Console.Write("Enter: ");\n habitatInput = Console.ReadLine();\n } while (!habitats.Contains(habitatInput));\n\n BirdId(colorInput, sizeInput, habitatInput);\n }\n\n static void BirdId(string colorInput, string sizeInput, string habitatInput)\n {\n // Use LINQ to iterate over a collection - increases readability in cases you have a big if condition on properties\n var foundBirds = Birds.Where(bird =>\n bird.Color == colorInput &&\n bird.Size == sizeInput &&\n bird.Habitat == habitatInput).Select(bird => bird.Name);\n\n if (foundBirds.Any())\n {\n Console.WriteLine("\\n" + string.Join('\\n', foundBirds));\n }\n else\n {\n Console.WriteLine("\\nNo birds found.");\n }\n }\n\n static void Main(string[] args)\n {\n Start();\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T17:51:47.077",
"Id": "485530",
"Score": "1",
"body": "+1 but small nit - that's a [collection initializer](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers) not an object initializer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T17:58:24.743",
"Id": "485532",
"Score": "0",
"body": "@RobH you’re absolutely right! I’ll change the comment, even though it’s an object in the end ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T21:29:17.393",
"Id": "485542",
"Score": "0",
"body": "Awesome review. Another small nit, the foundBirds enumeration is being enumerated twice (partially first time). Perhaps by design but worth noting. Doing a ToList or ToArray would avoid it, especially given the known small resultset."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T22:33:35.947",
"Id": "485549",
"Score": "0",
"body": "Thanks :-) I know, that’s why I asked him what editor he uses. Some give hints, like Rider. It’s a review to challenge him to learn more about C#, and since he didn’t use LINQ in his code I assume he doesn’t know (much) about it (yet). Going into all details would have been too much imho."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:33:16.850",
"Id": "247909",
"ParentId": "247902",
"Score": "6"
}
},
{
"body": "<p>Well 321X has a good review, I'm just adding some other points that would benefit you since you're new. I'll give you some points, then I'll link it to your code so you get the full picture.</p>\n<p>First, designing your application <strong>MUST</strong> be <strong>flexible</strong> for any future changes. Not all applications needs to be flexible as some applications might be fixed (do it once and forget it), however, it is important as a programmer to consider changes in the long-term even for fixed applications (or as I call them static applications). This means, you need to separate your logic from the application environment (in your case Console). Which would add more flexibility to your application and easier to maintain and adapt or convert to another environment (such as converting from Console to Windows Form) .</p>\n<p>Constants <code>MUST</code> be declared as <code>const</code> or <code>enum</code> or <code>readonly</code> objects. That is, if you have some options in your application (like colors, size, and habitats) always initiate them as <code>const</code> or <code>enum</code> or <code>readonly</code> and keep them inside their related class (or struct if so).</p>\n<p>Global variables (public or private) always declare them at the top of the class for better readability.</p>\n<p>Always use the correct datatype, and use string only for output. So, in your case, user input will be string always, you need to parse that input to the correct datatype. For instance, at start you list 2 options to the user, and user needs to input either 1 or 2. You should try parse it to an actual <code>int</code> which is the correct data type for this input.</p>\n<p>Always use access modifiers (private, public, protected, internal ..etc). Keep it visible, as it would increase your code readability.</p>\n<p>Always use PascalCase in class, struct, method, Functions and Properties. And camelCase for the rest.</p>\n<p>Now to the actual code :</p>\n<pre><code>class Bird\n {\n public string name;\n public string size;\n public string color;\n public string habitat;\n public Bird(string name, string size, string color, string habitat)\n {\n this.name = name;\n this.size = size;\n this.color = color;\n this.habitat = habitat;\n }\n }\n</code></pre>\n<p>Color, Size, and Habitat are constants strings, you should use <code>enum</code> instead.</p>\n<pre><code>public enum BirdColor\n{\n Default,\n Brown,\n Grey,\n White\n}\n\npublic enum BirdSize\n{\n Default,\n Small,\n Medium,\n Large\n}\n\npublic enum BirdHabitat\n{\n Default,\n America,\n Australia,\n Africa,\n Europe\n}\n</code></pre>\n<p>Then your model would be :</p>\n<pre><code>public class Bird\n{\n public string Name { get; }\n public BirdSize Size { get; }\n public BirdColor Color { get; }\n public BirdHabitat Habitat { get; }\n\n /// .. rest \n}\n</code></pre>\n<p>This :</p>\n<pre><code>public static void BirdList()\n{\n Console.Clear();\n foreach (var bird in birds)\n Console.WriteLine("Name: {0} | Size: {1} | Main Color: {2} | Habitat Location: {3}", bird.name, bird.size, bird.color, bird.habitat);\n}\n</code></pre>\n<p>there is <code>ToString()</code> method, you should use it instead. override the <code>Bird</code> class <code>ToString()</code> to return the string you need. Like this :</p>\n<pre><code>public class Bird\n{\n //code ...\n public override string ToString()\n {\n return $"Name: {Name} | Size: {Size} | Main Color: {Color} | Habitat Location: {Habitat}";\n }\n}\n\n\npublic static void BirdList()\n{\n Console.Clear();\n foreach (var bird in birds)\n Console.WriteLine(bird.ToString());\n}\n</code></pre>\n<p>For the datatype point, see this line :</p>\n<pre><code>do\n{\n Console.Write("Enter 1 or 2: ");\n input = Console.ReadLine();\n if (input == "1")\n {\n BirdList();\n }\n if (input == "2")\n {\n BirdQuestions();\n }\n} while (input != "1" && input != "2");\n</code></pre>\n<p>The input is string integer, I know it's not an issue in your current code, however, with this code, it would opens some security risks. It might be not important here, but it would give you heads-up to avoid that in real applications.</p>\n<p>your loop will process every user-input, and then validate that input, while you're expecting only integers (1 or 2). In other word, you're saying to the application, keep processing user inputs until the results either 1 or 2. Even if it's simple application. The concept itself to process every input until your condition is met it would be a huge risk in real applications. Avoid doing that, and always narrow down the inputs processing to the task requirements only. In this case, you need to restrict the input to integers only, then validate the given integer.</p>\n<p>instead use this :</p>\n<pre><code>// restricting the input to only integers this way is a guaranteed that you will only process a valid integer. \n// also, it would be flixable for adding more options in the future. \nwhile(!int.TryParse(Console.ReadLine() , out int result))\n{\n // code here ... \n}\n</code></pre>\n<p>no matter how many inputs the user enters, it'll only get inside the loop if it's integer, otherwise it'll skip and re-evaluate the next input. This change would make it difficult to the user to do any hacky inputs (either bugs that would stops the application, or some security exploits).</p>\n<p>Your code is really good for a beginner, however, you made everything in one place, which throw away the prettiness of OOP. Your application has a model (this is a plus), and needs to have a class to manage the model collections (Business Layer). Then, Another class to work with the environment itself (Presentation Layer).</p>\n<p>Let's say we have created <code>BirdApplication</code> and <code>BirdConsole</code>.</p>\n<p><code>BirdApplication</code> would contain the <code>List<Bird></code> data, along with some methods that would be reused to get the data and parse them.</p>\n<p><code>BirdConsole</code> would contain the business logic for the Console Environment and would used <code>BirdApplication</code> internally.</p>\n<p>If we implement them like that, we would endup doing this :</p>\n<pre><code>public static class Program \n{\n static void Main(string[] args)\n {\n BirdConsole.Start();\n }\n}\n</code></pre>\n<p>This means, you moved all your application logic into independent classes, which would be easier to maintain, and also to convert to another environment. with minimum changes possible. For instance, if you wanted to move to Windows Form, you only need to create another class <code>BirdForm</code> for instance, and then convert <code>BirdConsole</code> to the approperate objects for <code>Windows Forms</code>.</p>\n<p>These are some of the points that I see, I have re-written your code applying the points that I've mentioned above to give you a better picture on them. I hope it would be useful to you.</p>\n<pre><code>public class Bird\n{\n public string Name { get; }\n public BirdSize Size { get; }\n public BirdColor Color { get; }\n public BirdHabitat Habitat { get; }\n\n public Bird(string name , BirdSize size , BirdColor color , BirdHabitat habitat)\n {\n Name = name;\n Size = size;\n Color = color;\n Habitat = habitat;\n }\n\n public override string ToString()\n {\n return $"Name: {Name} | Size: {Size} | Main Color: {Color} | Habitat Location: {Habitat}";\n }\n\n}\n\npublic enum BirdColor\n{\n Default,\n Brown,\n Grey,\n White\n}\n\npublic enum BirdSize\n{\n Default,\n Small,\n Medium,\n Large\n}\n\npublic enum BirdHabitat\n{\n Default,\n America,\n Australia,\n Africa,\n Europe\n}\n\npublic class BirdApplication\n{\n private readonly List<Bird> _birds;\n\n public BirdApplication()\n {\n _birds = InitiateList();\n }\n\n private List<Bird> InitiateList()\n {\n return new List<Bird>\n {\n new Bird("Bald Eagle", BirdSize.Large, BirdColor.White, BirdHabitat.America),\n new Bird("American Kestrel", BirdSize.Small, BirdColor.Brown, BirdHabitat.America),\n new Bird("Mississippi Kite", BirdSize.Medium, BirdColor.Grey, BirdHabitat.America),\n new Bird("Red Kite", BirdSize.Medium, BirdColor.Brown, BirdHabitat.Europe),\n new Bird("Secretary Bird", BirdSize.Large, BirdColor.Grey, BirdHabitat.Africa),\n new Bird("Shoebill Stork", BirdSize.Large, BirdColor.Grey, BirdHabitat.Africa),\n new Bird("Cockatoo", BirdSize.Medium, BirdColor.White, BirdHabitat.Australia)\n };\n }\n\n public List<Bird> GetBirds()\n {\n return _birds;\n }\n\n public static bool TryParseColor(string color , out BirdColor result)\n {\n return Enum.TryParse(color , true , out result);\n }\n\n public static bool TryParseSize(string size , out BirdSize result)\n {\n return Enum.TryParse(size , true , out result);\n }\n\n public static bool TryParseHabitat(string size , out BirdHabitat result)\n {\n return Enum.TryParse(size , true , out result);\n }\n\n public Bird GetBird(BirdColor color , BirdSize size , BirdHabitat habitat)\n {\n return _birds.Find(x => x.Color == color && x.Size == size && x.Habitat == habitat);\n }\n}\n\npublic static class BirdConsole\n{\n // always keep global variabls at the top of the class \n public static BirdApplication _birdApp = new BirdApplication();\n\n public static void Start()\n {\n // Console.WriteLine will add the message into a new line, so no need to \\n \n // it would be more readable this way. \n Console.WriteLine("Welcome to the Bird of prey identification helper.");\n Console.WriteLine("(1) List of all birds and their descriptions.");\n Console.WriteLine("(2) Identification help.");\n Console.WriteLine();\n\n // restricting the input to only integers this way is a gurantee that you will get a vaild integer. \n // also, it would be flixable for adding more options in the future. \n while(!int.TryParse(Console.ReadLine() , out int result))\n {\n switch(result)\n {\n case 1:\n Console.Clear();\n GetBirdsList();\n break;\n case 2:\n Console.Clear();\n GetBirdQuestions();\n break;\n default:\n Console.WriteLine("Please choose between 1 or 2");\n break;\n }\n }\n\n }\n\n private static void GetBirdsList()\n {\n var str = string.Join(Environment.NewLine , _birdApp.GetBirds());\n Console.WriteLine(str);\n }\n // this is not important, but It would be better if questions has its own implementation with a collection, so you loop over them, and help you to manage them easier.\n private static void GetQuestionAnswer(string question , bool condition)\n {\n do\n {\n Console.WriteLine(question);\n Console.Write("Enter: ");\n } while(!condition);\n }\n\n private static void GetBirdQuestions()\n {\n\n Console.Clear();\n Console.WriteLine("This process will help you through identifying a bird you have seen.");\n // questions are constants, keep that way to keep them unchanged. \n const string question1 = "\\nWhat was the birds main color? Enter brown, grey, or white.";\n\n const string question2 = "\\nHow large or small was the bird? Enter small, medium, or large.";\n\n const string question3 = "\\nWhere did you see the bird? Enter America, Australia, Europe, or Africa.";\n\n GetQuestionAnswer(question1 , BirdApplication.TryParseColor(Console.ReadLine() , out BirdColor color));\n\n GetQuestionAnswer(question2 , BirdApplication.TryParseSize(Console.ReadLine() , out BirdSize size));\n\n GetQuestionAnswer(question3 , BirdApplication.TryParseHabitat(Console.ReadLine() , out BirdHabitat habitat));\n\n var getBird = _birdApp.GetBird(color , size , habitat);\n\n if(getBird != null)\n {\n Console.WriteLine("\\n" + getBird.Name);\n }\n else\n {\n Console.WriteLine("\\nNo birds found.");\n }\n\n }\n\n}\n\npublic static class Program \n{\n static void Main(string[] args)\n {\n BirdConsole.Start();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T09:23:05.840",
"Id": "247938",
"ParentId": "247902",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T13:52:58.490",
"Id": "247902",
"Score": "6",
"Tags": [
"c#",
"beginner",
"strings"
],
"Title": "My first C# project - Simple bird of prey identification console app. Does it need refactoring or complete rewriting?"
}
|
247902
|
<p>Any advice on how to make this code; cleaner, more effective, just overall better!</p>
<p>Program setup object that is coming from the database EF. It then maps the object to a view model and converts datetime to string and different datetime components.</p>
<pre><code>//EF Data
List<MeetingEvent> Meeting = new List<MeetingEvent>();
Meeting.Add(new MeetingEvent() { MeetingId = 1, MeetingName= "A1",StartDateTime= new DateTime(2020, 1, 01),EndDateTime = new DateTime(2020, 1, 05) });
Meeting.Add(new MeetingEvent() { MeetingId = 2, MeetingName = "A2", StartDateTime = new DateTime(2020, 2, 01), EndDateTime = new DateTime(2020, 2, 05) });
Meeting.Add(new MeetingEvent() { MeetingId = 3, MeetingName = "A3", StartDateTime = new DateTime(2020, 3, 01), EndDateTime = new DateTime(2020, 3, 05) });
Meeting.Add(new MeetingEvent() { MeetingId = 4, MeetingName = "A4", StartDateTime = new DateTime(2020, 4, 01), EndDateTime = new DateTime(2020, 4, 05) });
Meeting.Add(new MeetingEvent() { MeetingId = 5, MeetingName = "A5", StartDateTime = new DateTime(2020, 5, 01), EndDateTime = new DateTime(2020, 5, 05) });
//Logic
var listOfEvents = Meeting.Select(x => new MeetingEventViewModel
{
MeetingId = x.MeetingId,
MeetingName = x.MeetingName,
StartDateTime = x.StartDateTime,
EndDateTime = x.EndDateTime,
StartDateDayName = x.StartDateTime.DayOfWeek.ToString(),
StartDateMonth = x.StartDateTime.Month.ToString(),
StartDateDay = x.StartDateTime.Day.ToString(),
StartDateYear = x.StartDateTime.Year.ToString(),
EndDateDayName = x.EndDateTime.DayOfWeek.ToString(),
EndDateMonth = x.EndDateTime.Month.ToString(),
EndDateDay = x.EndDateTime.Day.ToString(),
EndDateYear = x.EndDateTime.Year.ToString(),
}).ToList().OrderBy(o => o.StartDateTime);
foreach (MeetingEventViewModel m in listOfEvents)
{
Console.WriteLine(m.MeetingId);
}
class MeetingEvent
{
public int MeetingId { get; set; }
public string MeetingName { get; set; }
public DateTime StartDateTime{ get; set; }
public DateTime EndDateTime { get; set; }
}
class MeetingEventViewModel
{
public int MeetingId { get; set; }
public string MeetingName { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
public string StartDateDayName { get; set; }
public string StartDateDay { get; set; }
public string StartDateYear { get; set; }
public string StartDateMonth { get; set; }
public string EndDateDayName { get; set; }
public string EndDateDay { get; set; }
public string EndDateYear { get; set; }
public string EndDateMonth { get; set; }
</code></pre>
<p>}</p>
|
[] |
[
{
"body": "<p>First of all I would advice to use <code>DateTimeOffset</code> instead of <code>DateTime</code>.</p>\n<blockquote>\n<p>Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications.\nSource: <a href=\"https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql?view=sql-server-ver15</a></p>\n</blockquote>\n<p>Besides that; If you have to do a lot of mapping I would use AutoMapper.</p>\n<p>The mapping profiles (where you can do some mapping configuration) would look like this:</p>\n<pre><code> public class MeetingEventProfile : Profile\n {\n public MeetingEventProfile()\n {\n CreateMap<MeetingEvent, MeetingEventViewModel>()\n .ForMember(x => x.StartDateDayName, x => x.MapFrom(_ => _.StartDateTime.DayOfWeek))\n .ForMember(x => x.StartDateMonth, x => x.MapFrom(_ => _.StartDateTime.Month))\n .ForMember(x => x.StartDateDay, x => x.MapFrom(_ => _.StartDateTime.Day))\n .ForMember(x => x.StartDateYear, x => x.MapFrom(_ => _.StartDateTime.Year))\n .ForMember(x => x.EndDateDayName, x => x.MapFrom(_ => _.EndDateTime.DayOfWeek))\n .ForMember(x => x.EndDateMonth, x => x.MapFrom(_ => _.EndDateTime.Month))\n .ForMember(x => x.EndDateDay, x => x.MapFrom(_ => _.EndDateTime.Day))\n .ForMember(x => x.EndDateYear, x => x.MapFrom(_ => _.EndDateTime.Year));\n }\n }\n</code></pre>\n<p>You only see some specific mappings for properties that don't match by name (or require some conversion/etc). Property names that match you don't have to explicitly map; although there is a lot of configuration possible here!</p>\n<p>In your logic (which is not poluted with mapping anymore) you would do something like this:</p>\n<pre><code>public class MyClass{\n private readonly IMapper _mapper;\n\n public MyClass(IMapper mapper){\n _mapper = mapper;\n }\n\n public void MyMethod(){\n var meetingVms = _mapper.Map<MeetingEventViewModel[]>(Meeting);\n }\n}\n</code></pre>\n<p>The performance impact by using AutoMapper is very low; I did quite some benchmarks with high performance requirements and the impact was very low.</p>\n<p>My example assumes you are using dependency injection. AutoMapper is very easy to implement. Otherwise you have to create the Mapper instance yourself which isn't hard too. The docs are well written: <a href=\"https://docs.automapper.org/en/stable/Dependency-injection.html\" rel=\"nofollow noreferrer\">https://docs.automapper.org/en/stable/Dependency-injection.html</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T14:20:29.820",
"Id": "247905",
"ParentId": "247903",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "247905",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T13:55:22.737",
"Id": "247903",
"Score": "2",
"Tags": [
"c#",
"entity-framework"
],
"Title": "View model using different datetime component"
}
|
247903
|
<p>Here's a simple one for u guys,</p>
<p>The code is called upon workbook_open and BeforeSave, it displays the right sheet in function of date and time (Day vs night shift vs date). The code run trough the sheet and activate it if the date on sheet is the same as the actual date. Since there's 2 sheets with the same date (day and night shift) i had to add a time condition. The nights shifts are before the day one (look at image) so i had to split my loop in 2 to make it work (could maybe be one). Also, if we're not in the week of that report, so that no sheets has a date that fits, i wanted it to select Friday cause it has a report on it. Since its called often i wanted to make sure that it is optimal.</p>
<p><a href="https://i.stack.imgur.com/PobEj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PobEj.png" alt="Sheet order" /></a></p>
<p>Code :</p>
<pre><code>Sub selectiondequartauto()
' Code that display sheet in fucntion of date and time
Dim count As Long ' Counter
Dim xSh As Worksheet
Dim activation as Boolean
Dim sheetdate As Date
Dim limitpm As Variant
Dim limitam As Variant
limitpm = TimeValue("16:15:00") ' Night shift Start
limitam = TimeValue("3:00:00") ' Night shift end
For Each xSh In Worksheets ' Loop on every visible sheet
If xSh.Visible Then
sheetdate = xSh.Cells(4, 2).Value ' Gives sheetdate the date of the sheet in present loop
If TimeValue(Now) < limitpm And TimeValue(Now) > limitam Then
If count < 1 Then ' If count is smaller than 1 (no sheet w same date as now yet)
If sheetdate = Date Then ' Si Sheetdate = actual date
count = count + 1 ' Count = 1 and next sheet, because 2 sheet have sheetdate = actual date
End If
ElseIf count = 1 Then ' Si count = 1
Activation = True
xSh.Activate ' Activate curent loop sheet and quit
Exit For
End If
Else ' If we are in night shift time frame
If sheetdate = Date Then
Activation = True
xSh.Activate ' Activate curent loop sheet and quit
Exit For
End If
End If
End If
Next
If Activation = False Then
Sheets("Vendredi jour").Activate
End If
End Sub
</code></pre>
|
[] |
[
{
"body": "<p><code>selectiondequartauto()</code> defines night shift to determine whether to select either the night shift or day shift sheet. If none of the worksheets meet the criteria of Night Shift or Day Shift then the Friday worksheet is selected. This all works fine but consider the advantages of my refactored code which separates these tasks into their own methods.</p>\n<p>• isNightShift: Using a function that determines what is Night Shift and what is Day Shift means that you can update the hours of Night Shift in one spot and not have to look over every procedure that is dependent on on the Night Shift.</p>\n<p>• NightShiftSheet() and DayShiftSheet(): Having these functions will prevent you from having to repeat the logic to find the sheets in the future. They also make <code>selectiondequartauto()</code> easier to read</p>\n<pre><code>Public Sub selectiondequartauto()\n Dim ws As Worksheet\n \n If isNightShift(Now) Then\n Set ws = NightShiftSheet\n Else\n Set ws = DayShiftSheet\n End If\n \n If ws Is Nothing Then\n Sheets("Vendredi jour").Activate\n Else\n ws.Activate\n End If\nEnd Sub\n\nPublic Function DayShiftSheet() As Worksheet\n Dim ws As Worksheet\n\n For Each ws In ThisWorkbook.Worksheets\n With ws.Range("B4")\n If IsDate(.Value) Then\n If Not isNightShift(.Value) Then\n Set DayShiftSheet = ws\n Exit Function\n End If\n End If\n End With\n Next\n \nEnd Function\n\nPublic Function NightShiftSheet() As Worksheet\n Dim ws As Worksheet\n For Each ws In ThisWorkbook.Worksheets\n With ws.Range("B4")\n If IsDate(.Value) Then\n If isNightShift(.Value) Then\n Set NightShiftSheet = ws\n Exit Function\n End If\n End If\n End With\n Next\nEnd Function\n\nPublic Function isNightShift(DateTime As Date) As Boolean\n isNightShift = TimeValue(DateTime) > TimeValue("3:00:00") And TimeValue(DateTime) < TimeValue("16:15:00")\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T12:18:55.507",
"Id": "485719",
"Score": "0",
"body": "Excellent refactor! It always seems to me that my code are clear but it seems like there's always something to perfect that i cant see! Before i accept i need to correct some little detail: do you want me to adress them in comment ot update my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T13:13:05.773",
"Id": "485722",
"Score": "0",
"body": "Update : I solved the issues, it now work following your logic even tho it went back to complex condition and hard to read; it woudve work perfecty with your method if date on sheets were actual date + time but rn its actually fixed pre determined manually entered date only (no time) so the call back to isNightShift was never returning True (since DateTime had no time in it)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T16:53:13.403",
"Id": "485737",
"Score": "0",
"body": "Il repost because of the amount of midification ive made"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:09:29.517",
"Id": "485741",
"Score": "1",
"body": "@PatatesPilées thanks for accepting my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:11:13.107",
"Id": "485742",
"Score": "0",
"body": "No problem that was usefull!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T02:31:26.510",
"Id": "248017",
"ParentId": "247904",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248017",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T14:09:30.680",
"Id": "247904",
"Score": "4",
"Tags": [
"vba",
"excel"
],
"Title": "Sheet display in function of date and time on open and save"
}
|
247904
|
<p>I'm experimenting in Unity with a tile-based game with crisp 32x32 tile textures and pixel perfect camera. I did not like the results coming from Unity's default <code>Tilemap</code> approach mainly because due to the crispiness of the textures, the edges between them (biome boundaries, if you will) were too sharp for my taste. I wanted to have a <strong>small margin between tiles where they interpolate smoothly</strong>.</p>
<p>As such, I eventually googled out that transitions and blending of textures can be done with shaders, a topic completely new to me, but I accepted the learning challenge. Thus, I present for review my first shader (of course after a few iterations and polish).</p>
<p>Sorry if the following introduction is overly lengthy or trivial but I felt a conceptual overview was necessary.</p>
<p>The challenge: blend the main texture with 4 adjacent ones within its margin (which is adjustable, but looks best to me at 2px for a 32x32 tile):</p>
<p><a href="https://i.stack.imgur.com/K7KXN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K7KXN.png" alt="Tiles" /></a></p>
<p>We blend the textures in such a way that inside the tile and at the inner edge of the margin, the tile is rendered at 100% strength. Within the margin we then interpolate linearly into the adjacent texture up to the tile's edge where they mix at a 50/50 ratio (that tile will then blend from 50/50 to 100% of itself within its own margin).</p>
<p>In the corners, we blend all three contributing textures linearly, where the corner mixes at a 50/25/25 ratio (yes, it's a potential discontinuity but we never actually render that as a pixel). Here's a zoom to the top right corner with a couple points probed:</p>
<p><a href="https://i.stack.imgur.com/VLdvT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VLdvT.png" alt="Interpolation explained" /></a></p>
<p>(Light grey points represent actual pixel probe points.)</p>
<p>Code incoming. The textures get assigned in my C# code to a temporary material, which passes them to the shader. Additionally, we need to handle literal edge cases: when the tile is the edge of the map, we turn off blending in that direction (also when adjacent cell has the same texture) and main texture applies 100% up to the edge. We do that using the _Blend* directives.</p>
<pre><code>Shader "Custom/EdgeBlender"
{
Properties
{
_BlendMargin ("Blend margin", float) = 0.0675 //2px for a 32x32 tile
[PerRendererData]_MainTex ("Center texture", 2D) = "white" {}
[PerRendererData]_BlendLeft ("Blend left texture", int) = 0
[PerRendererData]_LeftTex ("Left texture", 2D) = "white" {}
[PerRendererData]_BlendRight ("Blend right texture", int) = 0
[PerRendererData]_RightTex ("Right texture", 2D) = "white" {}
[PerRendererData]_BlendTop ("Blend top texture", int) = 0
[PerRendererData]_TopTex ("Top texture", 2D) = "white" {}
[PerRendererData]_BlendBottom ("Blend bottom texture", int) = 0
[PerRendererData]_BottomTex ("Bottom texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType" = "Opaque" }
CGPROGRAM
#pragma surface surf Standard
#pragma target 3.5
float _BlendMargin;
sampler2D _MainTex;
int _BlendLeft;
sampler2D _LeftTex;
int _BlendRight;
sampler2D _RightTex;
int _BlendTop;
sampler2D _TopTex;
int _BlendBottom;
sampler2D _BottomTex;
struct Input
{
float2 uv_MainTex;
float2 uv_LeftTex;
float2 uv_RightTex;
float2 uv_TopTex;
float2 uv_BottomTex;
};
// In a domain of [0; 1]:
// Scale from -1 to 0 on interval [0; margin]
// 0 on interval [margin; 1-margin]
// Scale from 0 to 1 on inteval [1-margin; 1]
float marginCalc(float position, float margin)
{
return sign(position - 0.5) * clamp(abs(position - 0.5) - (0.5 - margin), 0, margin) / margin;
}
void surf(Input IN, inout SurfaceOutputStandard o)
{
fixed4 main = tex2D(_MainTex, IN.uv_MainTex);
float2 pos = IN.uv_MainTex.xy;
fixed4 right = tex2D(_RightTex, IN.uv_RightTex);
fixed4 left = tex2D(_LeftTex, IN.uv_LeftTex);
fixed4 top = tex2D(_TopTex, IN.uv_TopTex);
fixed4 bottom = tex2D(_BottomTex, IN.uv_BottomTex);
// How much into the margins are we?
// Absolute magnitude is from 0 (inside or margin begins) to 1 (edge of tile)
// Sign signifies direction (postitive for right and top, negative for left and bottom)
float marginX = marginCalc(pos.x, _BlendMargin);
float marginY = marginCalc(pos.y, _BlendMargin);
// Blend power tells us how much of foreign tiles will be mixed in
// Goes from 0 inside and at inner margin edges, up to 0.5 on tile edges
float blendPower = max(abs(marginX), abs(marginY)) / 2.0;
// Which adjacent tiles will even play a role in the mix?
bool leftContributes = (_BlendLeft == 1) && (marginX < 0);
bool rightContributes = (_BlendRight == 1) && (marginX > 0);
bool topContributes = (_BlendTop == 1) && (marginY > 0);
bool bottomContributes = (_BlendBottom == 1) && (marginY < 0);
// Mix ratio between two adjacent textures within the corner
float cornerMixRatio = abs(marginY) / (abs(marginX) + abs(marginY));
fixed4 result;
if (leftContributes && topContributes) {
fixed4 mixin = lerp(
left,
top,
cornerMixRatio);
result = lerp(main, mixin, blendPower);
} else if (leftContributes && bottomContributes) {
fixed4 mixin = lerp(
left,
bottom,
cornerMixRatio);
result = lerp(main, mixin, blendPower);
} else if (rightContributes && topContributes) {
fixed4 mixin = lerp(
right,
top,
cornerMixRatio);
result = lerp(main, mixin, blendPower);
} else if (rightContributes && bottomContributes) {
fixed4 mixin = lerp(
right,
bottom,
cornerMixRatio);
result = lerp(main, mixin, blendPower);
} else if (leftContributes) {
result = lerp(main, left, blendPower);
} else if (rightContributes) {
result = lerp(main, right, blendPower);
} else if (topContributes) {
result = lerp(main, top, blendPower);
} else if (bottomContributes) {
result = lerp(main, bottom, blendPower);
} else {
result = main;
}
o.Albedo = result;
}
ENDCG
}
}
</code></pre>
<p>In terms of code correctness, I'm fairly sure it works well, at least I'm satisfied with the result and pretty proud of it:</p>
<p><a href="https://i.stack.imgur.com/sbU14.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sbU14.png" alt="End result" /></a></p>
<p>Code review objectives:</p>
<ul>
<li><p>What I'm looking for here is a general review of my shader code - any no-no's with regard to writing shaders, any features of the language (like functions I'm not aware of) that could simplify it, wrong types used, etc.</p>
</li>
<li><p>I put some effort to express <code>marginCalc</code> function without if statements. It does its job but is quite ugly. Does branchless programming even matter for GPU programming as much as it does for CPU?</p>
</li>
<li><p>I'm not thrilled with the "if-ology" in the last part of the code but couldn't figure out a better way.</p>
</li>
<li><p>The optimization of not blending if adjacent texture is same as current was done with performance in mind (we skip some <code>lerp</code>-ing if set to 0) but, being inexperienced with shaders, I don't even know if that matters in this case?</p>
</li>
<li><p>Eventually, I ran into the issue of "Too many texture interpolators would be used for ForwardBase pass (11 out of max 10)" and had to upgrade <code>#pragma target</code> to 3.5. My understanding is, this reduces hardware compatibility of my shader. If I went all silly and interpolated also diagonally (almost doubling the number of textures in use), I'd surely run into this problem again, and have to "upgrade" further. This got me thinking - maybe using the shader was not the best idea, after all?</p>
</li>
</ul>
<p>Addenum: In case it's relevant to understanding the logic, <code>marginCalc</code> basically recalculates the position in one dimension <code>[0; 1]</code> into a position with regard to the margin (0 - solid within the tile, 1/-1 - on the edge of tile):</p>
<p><a href="https://i.stack.imgur.com/N2U2n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N2U2n.png" alt="marginCalc chart" /></a></p>
|
[] |
[
{
"body": "<p><em>(Self-answer, and not comprehensive by any measure)</em></p>\n<p>After some consideration and more experimenting, I can offer one insight to this approach. It does not relate to shader code in any way but rather the structural approach.</p>\n<h3>The shader is too "fat" and deals with too many textures/does too many things.</h3>\n<p>Since every tile is rendered by a prefab, managed by a hand-written grid manager (remember, we're not using Unity's <code>Tilemap</code> here), we can make it more complex than a single quad with a single material and shader.</p>\n<p>Solution: <strong>"9-slice" the tile into 9 areas</strong></p>\n<p>It's a solution inspired by the idea of <a href=\"https://docs.unity3d.com/Manual/9SliceSprites.html\" rel=\"nofollow noreferrer\">9-splicing sprites</a> to reuse them more effectively and avoiding texture scaling issues.</p>\n<p><a href=\"https://i.stack.imgur.com/MPm5P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MPm5P.png\" alt=\"9-spliced tile\" /></a></p>\n<p>The tile in question (highlighted in yellow) is split into 9 areas (each of them is a separate quad with its own material-shader):</p>\n<ul>\n<li>Central, deals with only one texture, trivial shader.</li>\n<li>4 Edge areas, deal with only two textures, very simple <code>lerp</code>-ing shader, easily reusable by clever rotations.</li>\n<li>4 Corner areas, deals with only 3-4 textures (depending on whether you blend diagonally as well), somewhat more complex texture matth, again, reusable with clever rotations.</li>\n</ul>\n<p>A significant improvement over a single shader, with massive bloated logic and dealing with 5 or 9 textures.</p>\n<p>A snippet from the edge shader:</p>\n<pre><code> void surf(Input IN, inout SurfaceOutput o)\n {\n float3 pos = IN.worldPos - _RefZeroZero;\n \n fixed4 main = tex2D(_MainTex, pos);\n fixed4 blend = tex2D(_BlendTex, pos);\n\n float blendPower = 0.0;\n\n // How far from the center are we?\n float magnitude = dot(pos - float4(0.5, 0.5, 0, 0), _BlendDirection);\n\n // Are we into the margin?\n if (magnitude > 0.5 - _BlendMargin)\n {\n // Linearly scale from 0 at the margin's start to 0.5 at tile's edge\n blendPower = (magnitude - (0.5 - _BlendMargin)) / _BlendMargin / 2.0;\n }\n \n o.Albedo = lerp(main, blend, blendPower);\n }\n</code></pre>\n<p>Additional parameters included:</p>\n<ul>\n<li><code>_RefZeroZero</code> - The world position of the (0, 0) of the tile (bottom left corner) for easier texture calculations.</li>\n<li><code>_BlendDirection</code> - Unit vector pointing from the center of this tile towards the one we're blending with. Simplifies math a lot thanks to dot product (this is how I reuse the shader for all 4 edge areas - by just varying this vector).</li>\n</ul>\n<p>Sneak peek into the final result:</p>\n<p><a href=\"https://i.stack.imgur.com/02cqm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/02cqm.png\" alt=\"Final result\" /></a></p>\n<p>And with very wide margins (0.25 of tile) for comparison (although I'd never go this high in an actual game):</p>\n<p><a href=\"https://i.stack.imgur.com/GcaGC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GcaGC.png\" alt=\"Wide margins\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T11:37:12.663",
"Id": "247944",
"ParentId": "247906",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T14:58:17.007",
"Id": "247906",
"Score": "3",
"Tags": [
"game",
"unity3d",
"hlsl",
"shaders"
],
"Title": "Unity surface shader to blend between adjacent tiles"
}
|
247906
|
<p>I don't really have a problem. But, it's my first time using Kotlin for any project, so I want to know if there is any problem in my code or my code can be made cleaner.</p>
<p>This is an arithmetic parser made in Kotlin. It can evaluate a expression like <code>"(6+4)/(2+3)"</code> to 2.0
This handles operations like</p>
<ol>
<li>Power(^)</li>
<li>Divison(/)</li>
<li>Multiplication(*)</li>
<li>Subtraction(-)</li>
<li>Addition(+)</li>
</ol>
<p>It also handles brackets.</p>
<p>My Kotlin Code is :-</p>
<pre><code>import kotlin.math.pow
fun basic(rightNum:String?, leftNum:String?, op:String?):Double? {
return when (op) {
"+" -> {
(rightNum?.toDouble()!! + leftNum?.toDouble()!!)
}
"-" -> {
(rightNum?.toDouble()!! - leftNum?.toDouble()!!)
}
"*" -> {
(rightNum?.toDouble()!! * leftNum?.toDouble()!!)
}
"^" -> {
((rightNum?.toDouble()!!).pow(leftNum?.toDouble()!!))
}
else -> {
(rightNum?.toDouble()!! / leftNum?.toDouble()!!)
}
}
}
fun elemInside(mainString:String?, listCheck:List<String>):Boolean {
for (ops in listCheck) {
if (mainString?.contains(ops)!!){
return true
}
}
return false
}
fun getOpIndex(query: String?, operations:List<String>):Array<Int> {
var allIndex:Array<Int> = arrayOf()
var dupQuery = query
while (elemInside(dupQuery, operations)) {
for (op in operations) {
if (dupQuery?.contains(op)!!) {
allIndex = allIndex.plusElement(dupQuery.indexOf(op))
dupQuery = dupQuery.substring(0, dupQuery.indexOf(op)) + '1' + dupQuery.substring(dupQuery.indexOf(op) + 1)
}
}
}
allIndex.sort()
return allIndex
}
fun parseSimple(query:String?):Double? {
val operations = listOf("^", "/", "*", "-", "+")
var allIndex: Array<Int> = arrayOf()
var calcQuery = query
while (elemInside(calcQuery, operations) && (allIndex.size > 1 || if (allIndex.isEmpty()) true else allIndex[0] != 0)) {
for (op in operations) {
calcQuery = calcQuery?.replace("-+", "-")
calcQuery = calcQuery?.replace("--", "+")
calcQuery = calcQuery?.replace("+-", "-")
allIndex = getOpIndex(calcQuery, operations)
if (calcQuery?.contains(op)!!) {
val indexOp = calcQuery.indexOf(op)
val indexIndexOp = allIndex.indexOf(indexOp)
val rightIndex =
if (indexIndexOp == allIndex.lastIndex) calcQuery.lastIndex else allIndex[indexIndexOp + 1]
val leftIndex = if (indexIndexOp == 0) 0 else allIndex[indexIndexOp - 1]
val rightNum =
calcQuery.slice(if (rightIndex == calcQuery.lastIndex) indexOp + 1..rightIndex else indexOp + 1 until rightIndex)
val leftNum = calcQuery.slice(if (leftIndex == 0) leftIndex until indexOp else leftIndex + 1 until indexOp)
val result = basic(leftNum, rightNum, op)
calcQuery = (if (leftIndex != 0) calcQuery.substring(
0,
leftIndex + 1
) else "") + result.toString() + (if(rightIndex != calcQuery.lastIndex) calcQuery.substring(
rightIndex..calcQuery.lastIndex
) else "")
}
}
}
return calcQuery?.toDouble()
}
fun getAllIndex(query: String?, char: Char, replacement:String="%"):List<Int> {
var myQuery = query
var indexes:List<Int> = listOf()
while (char in myQuery!!) {
val indexFinded = myQuery.indexOf(char)
indexes = indexes.plus(indexFinded)
myQuery = myQuery.substring(0 until indexFinded) + replacement + myQuery.substring(indexFinded+1..myQuery.lastIndex)
}
return indexes
}
fun getBrackets(query: String?): List<Int> {
val allEndIndex = getAllIndex(query, ')')
val allStartIndex = getAllIndex(query, '(')
val firstIndex = allStartIndex[0]
for (endIndex in allEndIndex) {
val inBrac = query?.substring(firstIndex+1 until endIndex)
val inBracStart = getAllIndex(inBrac, '(')
val inBracEnd = getAllIndex(inBrac, ')')
if (inBracStart.size == inBracEnd.size){
return listOf(firstIndex, endIndex)
}
}
return listOf(-1, -1)
}
fun evaluate(query:String?):Double? {
var calcQuery = query
var index = 0;
// Check if brackets are present
while (calcQuery?.contains('(')!! && index < 200){
val startBrackets = getBrackets(calcQuery)[0]
val endBrackets = getBrackets(calcQuery)[1]
val inBrackets = calcQuery.slice(startBrackets+1 until endBrackets)
if ('(' in inBrackets && ')' in inBrackets){
val inBracValue = evaluate(inBrackets)
calcQuery = calcQuery.substring(0, startBrackets) + inBracValue.toString() + (if(endBrackets == calcQuery.lastIndex) "" else calcQuery.substring(endBrackets+1..calcQuery.lastIndex))
}
else {
val inBracValue = parseSimple(inBrackets)
calcQuery = calcQuery.substring(0, startBrackets) + inBracValue.toString() + (if(endBrackets == calcQuery.lastIndex) "" else calcQuery.substring(endBrackets+1..calcQuery.lastIndex))
}
index++
}
return parseSimple(calcQuery)
}
fun main() {
print("Enter the equation: ")
val equation = readLine()
println(evaluate(equation))
}
</code></pre>
<p>Please tell me how I can improve the code.</p>
<p>The github link is here: <a href="https://github.com/ProgrammerPro94/ArithematicParserKotlin" rel="nofollow noreferrer">https://github.com/ProgrammerPro94/ArithematicParserKotlin</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:19:00.347",
"Id": "485510",
"Score": "6",
"body": "Yes, I have nearly tested for around 100 expressions using lists of strings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:22:52.407",
"Id": "485513",
"Score": "3",
"body": "Do you have those tests automated? Or a list of them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:27:08.090",
"Id": "485514",
"Score": "0",
"body": "I have made a list of around 100 strings with some hard expressions and some complications and then passes each of them as a value of a parser and then compare the results of the tests of the parser and a calculator result for that expressions. They were same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:55:32.283",
"Id": "485518",
"Score": "3",
"body": "@programmerpro I think you should learn about JUnit https://junit.org/junit5/docs/current/user-guide/ (It can be used from Kotlin too)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T12:39:55.340",
"Id": "485574",
"Score": "1",
"body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>You are using a lot of nullable types, combined with non-null assertions (<code>!!</code>). This defeats the purpose of using the nullable types in the first place. You should <strong>as early as possible</strong> check whether or not a value is null, and then pass it on as not-null.</p>\n<p>For example, just looking at some of your function headers:</p>\n<pre><code>fun evaluate(query:String?):Double?\n\nfun parseSimple(query:String?):Double?\n\nfun basic(rightNum:String?, leftNum:String?, op:String?):Double?\n</code></pre>\n<p>Do these methods even make sense if any of those parameters is null? No! So don't declare them as nullable.</p>\n<hr />\n<p>If I write <code>2^5</code> and you have variables called <code>leftNum</code> and <code>rightNum</code>, I would expect 2 to be left and 5 to be right. But your code is <code>rightNum.toDouble().pow(leftNum.toDouble())</code> and it computes correctly. That's because you're putting 2 as rightNum and 5 as leftNum for some reason.</p>\n<hr />\n<p>You can make better use of Kotlin's amazing API, for example in this method:</p>\n<pre><code>fun elemInside(mainString:String?, listCheck:List<String>):Boolean {\n for (ops in listCheck) {\n if (mainString?.contains(ops)!!){\n return true\n }\n }\n return false\n}\n</code></pre>\n<p>This could be:</p>\n<pre><code>fun elemInside(mainString:String, listCheck: List<String>): Boolean {\n return listCheck.any { mainString.contains(it) }\n}\n</code></pre>\n<p>Which can even be written as:</p>\n<pre><code>fun elemInside(mainString:String, listCheck: List<String>): Boolean\n = listCheck.any { mainString.contains(it) }\n</code></pre>\n<hr />\n<p>I would strongly recommend using the <a href=\"https://en.wikipedia.org/wiki/Shunting-yard_algorithm\" rel=\"noreferrer\">Shunting-yard Algorithm</a> to parse the expression. It would enable you to implement new features with new operators and even functions such as <code>sin</code>, <code>cos</code>, <code>sqrt</code>, and so on...</p>\n<p>Or even negative numbers, which you don't support right now. <code>-2*3</code> breaks. It has to be written as <code>(0-2)*3</code> in order to work. Using Shunting-yard Algorithm also allows you to deal with whitespace much easier.</p>\n<p>Order of operations is also a bit of an issue with your current approach, <code>2*3+4*5</code> returns 50.0 while I would expect it to return 6+20 = 26. Shunting-yard would help with this too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:58:39.230",
"Id": "485519",
"Score": "0",
"body": "Ok I will improve my code for negative numbers and also try to implement shunting yard algorithm."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:33:09.097",
"Id": "247908",
"ParentId": "247907",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "247908",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T15:00:01.010",
"Id": "247907",
"Score": "9",
"Tags": [
"kotlin"
],
"Title": "Arithmetic Parser in Kotlin"
}
|
247907
|
<p>I know there is a way to simplify these checkbox onClick functions. I'm just not sure how to make it happen.</p>
<p>Upon checking the checkAllProfiles checkbox, all of the profileCheckboxes are checked:</p>
<pre><code>$('#checkAllProfiles').on('click', function()
{
$(".profileCheckbox").prop('checked', $(this).prop('checked'));
});
</code></pre>
<p>Then, if one of the profileCheckboxes are checked, it unchecks the checkAllProfiles checkbox:</p>
<pre><code>$(".profileCheckbox").on('click', function()
{
$(".checkAllProfiles").prop("checked", false );
});
</code></pre>
<p>Now here is another set of checkboxes that require the same functionality:</p>
<pre><code>$('#checkAllRegions').on('click', function()
{
$('.regionCheckbox').prop('checked', $(this).prop('checked'));
});
$(".regionCheckbox").on('click', function()
{
$(".checkAllRegions").prop("checked", false );
});
</code></pre>
<p>I want to be able to simplify this code. How can I do it?</p>
|
[] |
[
{
"body": "<p>One way to simplify this is you can use a data attribute to group them together with the check all option.</p>\n<p>This will allow you to add as many as groups as you want while reusing the same jquery.</p>\n<p>Also, you will want to use <code>change</code> and not <code>click</code> as click will be triggered when someone clicks on the radio even if its the same one, but change will only be triggered when a different one is selected by the user.</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>$(document).ready(function(){\n $(\".checkall\").on(\"change\",function(){\n $(\"[data-group=\" + $(this).data(\"group\") + \"]\").prop('checked', $(this).prop('checked'));\n });\n \n $(\"input[type=checkbox]:not(.checkall)\").on(\"change\",function(){\n $(\"[data-group=\" + $(this).data(\"group\") + \"].checkall\").prop('checked', false);\n });\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<input data-group=\"g1\" type=\"checkbox\" name=\"X\" value=\"1\">\n<input data-group=\"g1\" type=\"checkbox\" name=\"X\" value=\"2\">\n<input data-group=\"g1\" type=\"checkbox\" name=\"X\" value=\"3\"><br>\n<input data-group=\"g1\" id=\"g1checkall\" type=\"checkbox\" class=\"checkall\" name=\"X\"> <label for=\"g1checkall\">Check All</label>\n<hr>\n\n<input data-group=\"g2\" type=\"checkbox\" name=\"X2\" value=\"1\">\n<input data-group=\"g2\" type=\"checkbox\" name=\"X2\" value=\"2\">\n<input data-group=\"g2\" type=\"checkbox\" name=\"X2\" value=\"3\"><br>\n<input id=\"g2checkall\" data-group=\"g2\" type=\"checkbox\" class=\"checkall\" name=\"X2\"> <label for=\"g2checkall\">Check All</label></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T19:24:23.273",
"Id": "248101",
"ParentId": "247912",
"Score": "1"
}
},
{
"body": "<p>What about define the <code>class</code> of the checkboxes targets in a dataset attribute and every time you change this element, you change the elements with that class.</p>\n<p>You can define this behavior in a class, so, everytime you want to do this, you only need to pass the checkboxes class and add the class which you added the event listener instead of repeat the same piece of JavaScript</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>$('.checker').on('change', function() {\n $(\".\" + $(this).attr('data-checkbox')).prop('checked', $(this).prop('checked'));\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n\nRegions\n<input type=\"checkbox\" id=\"checkAllRegions\" data-checkbox=\"regionCheckbox\" class=\"checker\"/>\n<input type=\"checkbox\" class=\"regionCheckbox\" />\n<input type=\"checkbox\" class=\"regionCheckbox\" />\n<input type=\"checkbox\" class=\"regionCheckbox\" />\n<input type=\"checkbox\" class=\"regionCheckbox\" />\n\nProfiles\n<input type=\"checkbox\" id=\"checkAllProfiles\" data-checkbox=\"profileCheckbox\" class=\"checker\"/>\n<input type=\"checkbox\" class=\"profileCheckbox\" />\n<input type=\"checkbox\" class=\"profileCheckbox\" />\n<input type=\"checkbox\" class=\"profileCheckbox\" />\n<input type=\"checkbox\" class=\"profileCheckbox\" />\n\nfoo\n<input type=\"checkbox\" data-checkbox=\"bar\" class=\"checker\"/>\n<input type=\"checkbox\" class=\"bar\" />\n<input type=\"checkbox\" class=\"bar\" />\n<input type=\"checkbox\" class=\"bar\" />\n<input type=\"checkbox\" class=\"bar\" /></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T23:51:34.713",
"Id": "248216",
"ParentId": "247912",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T16:33:17.100",
"Id": "247912",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "How can I simplify these checkbox onClicks?"
}
|
247912
|
<p>I'm new to Go and have a use-case for periodically executing an async work-function. I want the interval between work-function executions to be constant (not the time between one finishing and the next starting). I also want this work-function to be executed some number of times. This translates to "run work N times, once per M ms".</p>
<p>This is what I have. I've tried to write <code>schedule</code> to be generic for any work-function. I've also written it so that the first time <code>work</code> is executed is at time 0 (as opposed to waiting for the first tick).</p>
<pre><code>package main
import (
"fmt"
"sync"
"time"
)
func work() {
fmt.Printf("work %s\n", time.Now())
}
func schedule(duration time.Duration, max int, work func()) {
ticker := time.NewTicker(duration)
defer ticker.Stop()
var wg sync.WaitGroup
var i = 0
for {
wg.Add(1)
go func() {
defer wg.Done()
work()
}()
i++
if i >= max {
wg.Wait()
return
}
<-ticker.C
}
}
func main() {
fmt.Printf("main begin %s\n", time.Now())
schedule(1*time.Second, 3, work)
fmt.Printf("main end %s\n", time.Now())
}
</code></pre>
<p>Any advice for simplifying and making this code more idiomatic is welcome :)</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T16:40:58.453",
"Id": "247913",
"Score": "3",
"Tags": [
"go",
"concurrency",
"async-await",
"timer",
"scheduled-tasks"
],
"Title": "n executions of a periodic goroutine"
}
|
247913
|
<p>Note that this is about System.Text.Json, not NewtonSoft.</p>
<p>The underlying issue that inspired this example is the problem of using different serialization on a particular property of a particular class when we can't change the source code of the class.</p>
<p>For this example, the target class looks like this:</p>
<pre><code>// Assume we can't change the definition of this class.
public class UndecoratedNumber
{
/// <summary>No JsonConverter attribute.</summary>
public int N { get; set; }
}
</code></pre>
<p>I want to serialize this class. But if N=1, I want to serialize it as the word "one" instead of as "1". So I need custom serialization. The following is the best I could do. Can you do better?</p>
<p>The inner converter for the integer:</p>
<pre><code>using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SystemJsonTesting
{
public class IntTextConverter : JsonConverter<int>
{
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var str = reader.GetString();
switch (str)
{
case "one":
return 1;
default:
return int.Parse(str);
}
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
if (value == 1)
{
writer.WriteStringValue("one");
} else
{
writer.WriteStringValue(value.ToString());
}
}
}
}
</code></pre>
<p>The outer converter for UndecoratedNumber:</p>
<pre><code>using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace SystemJsonTesting
{
public class UndecoratedNumberConverter : JsonConverter<UndecoratedNumber>
{
void validateToken(Utf8JsonReader reader, JsonTokenType tokenType)
{
if (reader.TokenType != tokenType)
throw new JsonException($"Invalid token: Was expecting a '{tokenType}' token but received a '{reader.TokenType}' token");
}
public UndecoratedNumberConverter()
{
var intTextConverter = new IntTextConverter();
ChildOptions = new JsonSerializerOptions();
ChildOptions.Converters.Add(intTextConverter);
}
public JsonSerializerOptions ChildOptions { get; }
public override UndecoratedNumber Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
reader.Read();
var r = new UndecoratedNumber();
while (reader.TokenType != JsonTokenType.EndObject)
{
validateToken(reader, JsonTokenType.PropertyName);
var value = reader.GetString();
switch (value)
{
case "N":
var n = JsonSerializer.Deserialize<int>(ref reader, ChildOptions);
r.N = n;
break;
}
reader.Read();
}
validateToken(reader, JsonTokenType.EndObject);
return r;
}
public override void Write(Utf8JsonWriter writer, UndecoratedNumber value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(UndecoratedNumber.N));
JsonSerializer.Serialize(writer, value.N, typeof(int), ChildOptions);
writer.WriteEndObject();
}
}
}
</code></pre>
<p>Two passing tests:</p>
<pre><code>using System.Text.Json;
using Xunit;
namespace SystemJsonTesting
{
public class UndecoratedNumberSerializationTests
{
[Fact]
public void UndecoratedNumber_1_RoundTrips()
{
var n = new UndecoratedNumber
{
N = 1
};
var converter = new UndecoratedNumberConverter();
var options = new JsonSerializerOptions();
options.Converters.Add(converter);
var serialized = JsonSerializer.Serialize(n, options);
Assert.Contains("one", serialized);
var deserialized = JsonSerializer.Deserialize<UndecoratedNumber>(serialized, options);
Assert.Equal(1, deserialized.N);
}
[Fact]
public void UndecoratedNumber_2_RoundTrips()
{
var n = new UndecoratedNumber
{
N = 2
};
var converter = new UndecoratedNumberConverter();
var options = new JsonSerializerOptions();
options.Converters.Add(converter);
var serialized = JsonSerializer.Serialize(n, options);
var deserialized = JsonSerializer.Deserialize<UndecoratedNumber>(serialized, options);
Assert.Equal(2, deserialized.N);
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T16:52:06.817",
"Id": "247914",
"Score": "1",
"Tags": [
"serialization"
],
"Title": "Custom JsonConverter for class"
}
|
247914
|
<p>To practice the very basics of node back-end, I'm implementing the most basic server possible for static content, using only the core node modules:</p>
<ul>
<li>http</li>
<li>fs</li>
<li>path</li>
</ul>
<p>With the following server requirements:</p>
<ul>
<li>Can serve any http file inside the public directory.</li>
<li>Accepts only GET requests, 404 for anything else.</li>
<li>Accepts only .html extensions, 404 for anything else.</li>
<li>Use public/not-found.html for 404s.</li>
</ul>
<p>These requirements are arbitrary, just to include some very basic logic in the request and response handling.</p>
<p>The working solution I'm presenting for code review is the following:</p>
<pre><code>const fs = require('fs')
const http = require('http')
const path = require('path')
const hostname = 'localhost'
const port = 3000
const runLog = `Server running ar http://${hostname}:${port}`
const rootPath = '../public'
const errorPath = `${rootPath}/not-found.html`
const server = http.createServer((req, res) => {
const fileUrl = req.url === '/' ? '/index.html' : req.url
const filePath = path.resolve(`${rootPath}${fileUrl}`)
res.setHeader('Content-Type', 'text/html')
if (reqIsOk(req, filePath)) {
res.statusCode = 200
fs.createReadStream(filePath).pipe(res)
} else {
res.statusCode = 404
fs.createReadStream(errorPath).pipe(res)
}
})
function reqIsOk (req, filePath) {
const fileExt = path.extname(filePath)
return req.method === 'GET' && fileExt === '.html' && fs.existsSync(filePath)
}
server.listen(port, hostname, () => {
console.log(runLog)
})
</code></pre>
<p>I'm looking for all kind of feedback, from style, code smells, anti-patterns, anything that can be improved is very welcome.</p>
<ul>
<li>Are the fs and path packages needed? Do they simplify things enough to justify the inclusion?</li>
<li>Can this be written more concisely?</li>
<li>Is the ternary operator justified? Would you keep it here, or is an if construct preferred?</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n<p>Are the fs and path packages needed? Do they simplify things enough to justify the inclusion?</p>\n</blockquote>\n<p><code>fs</code> is needed. How else would you get your data down the line without reading it in? <code>path</code> could be replaced with your own path utility library, but I wouldn't waste time reinventing that when a built-in one already exists.</p>\n<blockquote>\n<p>Can this be written more concisely?</p>\n</blockquote>\n<p>This is probably as concise as you can get it. Any further would probably make it unreadable.</p>\n<blockquote>\n<p>Is the ternary operator justified? Would you keep it here, or is an if construct preferred?</p>\n</blockquote>\n<p>Yep, ternary is fine. It's the check that might need improvement. That's because you're only tacking on <code>index.html</code> if the path is <code>/</code>. In other web servers, any path that ends in <code>/</code> assumes that <code>index.html</code> will be tacked on.</p>\n<pre><code>const filePath = path.resolve(`${rootPath}${fileUrl}`)\n</code></pre>\n<p>So one of the dangers when writing a web server is <a href=\"https://owasp.org/www-community/attacks/Path_Traversal\" rel=\"nofollow noreferrer\">directory traversal</a>. It's when your path resolver (in your case, this line) resolves to a path outside the web directory, and your server just willingly serves it. You'll need to check if the path resolved is still in your web directory.</p>\n<pre><code>res.setHeader('Content-Type', 'text/html')\n\nfunction reqIsOk (req, filePath) {\n const fileExt = path.extname(filePath)\n return req.method === 'GET' && fileExt === '.html' && fs.existsSync(filePath)\n}\n</code></pre>\n<p>A static server can be more than just HTML. Replace the hardcoded <code>text/html</code> with a value coming from a map of file extension to mimetype.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T22:22:48.907",
"Id": "247927",
"ParentId": "247915",
"Score": "3"
}
},
{
"body": "<p>As mentioned in <a href=\"https://codereview.stackexchange.com/a/247927/1581\">Joseph's excellent answer</a>, your server is vulnerable to a <em>path-traversal attack</em>. If I send it a request with enough <code>..</code>s in it, I can reach the root directory, and thus any directory from there.</p>\n<p>E.g. if your web root is <code>/var/www/root</code>, and I request the URI <code>../../usr/share/doc/bc/bc.html</code>, I will get the HTML documentation of the <code>bc</code> command from your PC. In fact, I can get <em>any</em> HTML document from your PC (including e.g. a <code>bookmarks.html</code> from a browser).</p>\n<p>You are asking (<strong>bold</strong> emphasis mine)</p>\n<blockquote>\n<p>I'm looking for <strong>all kind of feedback</strong>, from style, code smells, anti-patterns, <strong>anything that can be improved</strong> is very welcome.</p>\n</blockquote>\n<p>So, I will answer your question in a direction that you probably didn't intend but might be interesting for you anyway.</p>\n<p>"Real" webservers support a lot of additional features, for example:</p>\n<ul>\n<li>Virtual Hosts</li>\n<li>Access Control</li>\n<li>Server-side scripting</li>\n<li>Redirection</li>\n<li>Compression</li>\n</ul>\n<p>to name just a few.</p>\n<p>Obviously, your web server is only intended as a simple exercise, and all of these features require complex configuration files and massive machinery … or do they?</p>\n<p>It turns out, there are actually some tiny web servers that support some or all of these features in a clever way. For example, <a href=\"http://www.fefe.de/\" rel=\"nofollow noreferrer\">Felix von Leitner (fefe)</a>'s <a href=\"http://www.fefe.de/fnord/\" rel=\"nofollow noreferrer\">fnord (discontinued)</a> and <a href=\"http://www.fefe.de/gatling/\" rel=\"nofollow noreferrer\">gatling</a>, or <a href=\"http://acme.com/\" rel=\"nofollow noreferrer\">ACME Labs</a>' <a href=\"http://acme.com/software/thttpd/\" rel=\"nofollow noreferrer\">thttpd</a>. Especially fefe's web servers employ Unix filesystem semantics in "interesting" ways to avoid needing any configuration files.</p>\n<h1>Virtual Hosts</h1>\n<p>Configuring a Virtual Host in Gatling is easy: it's just a directory. Gatling does not serve files from the root of the web server directory, rather, it looks for a directory name that matches the <code>Host</code> HTTP header. So, if a browser sends a <code>GET</code> request for <code>/foo/bar.html</code> on <code>Host: 192.168.1.1:80</code>, Gatling will serve the file <code>$WEB_ROOT/192.168.1.1:80/foo/bar.html</code>.</p>\n<p>If you have ever needed to configure Virtual Hosts in Apache, you will appreciate how simple this is:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>mkdir -p 192.168.1.1:80/foo\ntouch 192.168.1.1:80/foo/bar.html\n</code></pre>\n<p>Boom, you're done.</p>\n<h1>Access Control</h1>\n<p>Access Control is a little trickier. But all three of the web servers I mentioned, have a really neat security feature that I wish more web servers had. Most web servers only care whether <em>they themselves</em> are allowed to read the file they are serving. However, thttpd, fnord, and gatling will <em>only</em> serve files that are explicitly <em>world-readable</em>, and they will only serve from directories that are explicitly <em>word-accessible</em>. They will also only generate directory listings for directories that are <em>world-readable</em> and will only show files within that listing that are <em>world-readable</em>.</p>\n<p>It is sometimes surprising to people when web servers make files readable to the world that are not <em>world-readable</em>.</p>\n<p>Note that this would also at least somewhat alleviate the path-traversal attack, since now I would only be able to access <em>world-readable</em> files in <em>world-accessible</em> directories.</p>\n<h1>Server-side scripting</h1>\n<p>In Gatling, any file that is <em>executable</em> will not be served as-is, but it will instead be <em>executed</em>, and the <em>output</em> of that file will be served. Specifically, it supports a subset of <a href=\"https://wikipedia.org/wiki/Common_Gateway_Interface\" rel=\"nofollow noreferrer\">CGI</a> (<a href=\"https://www.rfc-editor.org/rfc/rfc3875\" rel=\"nofollow noreferrer\">RFC 3875</a>).</p>\n<p>So, all you need to do to set up scripting in gatling, is <code>chmod +x</code>.</p>\n<h1>Redirection</h1>\n<p>In Gatling, <em>symbolic links</em> signify redirects. Remember that the target of a symbolic link is <em>just a path</em>. It doesn't actually have to exist.</p>\n<p>So, if you want to set up a <em>redirect</em> from <code>/search.html</code> to <code>https://google.com/</code>, the way you would do that in Gatling is simply this:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>ln -s https://google.com/ search.html\n</code></pre>\n<p>Again, compare this to redirects in Apache, or in a typical routing engine of a typical web framework.</p>\n<h1>Compression</h1>\n<p>At least Gatling and thttpd also support compression. I.e. if the client indicates that it supports <em>deflate</em> compression, and it requests the path <code>/foo/bar/baz.html</code>, they will first look for a file named <code>/foo/bar/baz.html.gz</code> and serve that if it exists.</p>\n<p>These are just a couple of ideas how to improve and extend your tiny web server. Most of these are additional features, and thus not really in scope for a simply Code Review, but I believe that at least the "only serve world-readable files out of world-accessible directories" part would be a worthwhile addition and increase the security and usability. (Of course, you also need to fix the path-traversal attack identified by Joseph.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T11:00:36.943",
"Id": "247985",
"ParentId": "247915",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247927",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T17:22:58.920",
"Id": "247915",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"http",
"server"
],
"Title": "Minimal, very simple, implementation of an HTTP server for static content, using only core node.js modules"
}
|
247915
|
<p>I need some feedback, please. Goals to practice: templates, std, interfaces, return value, constructors and some idioms.
People often suggest to use a library, but it's not the goal of this exercise, so please don't suggest those.</p>
<p>My worries about this code</p>
<ol>
<li>correctness of returns by value\reference</li>
<li>correctness of iterator constructor</li>
<li>correctness of type casts</li>
</ol>
<p>Thanks</p>
<h2>mymatrix.h</h2>
<pre><code>#pragma once
#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>
template <typename T>
class MyMatrix
{
public:
using value_type = T;
using reference = value_type&;
using const_reference = value_type const&;
using iterator = typename std::vector<value_type>::iterator;
using const_iterator = typename std::vector<value_type>::const_iterator;
using size_type = std::size_t;
private:
size_type m_rows;
size_type m_cols;
std::vector<value_type> m_buffer;
public:
MyMatrix(size_type dimx = 3, size_type dimy = 3)
: m_rows(dimx)
, m_cols(dimy)
, m_buffer(dimx * dimy)
{}
// Copy constructor
MyMatrix(MyMatrix const& copy)
: m_rows(copy.m_rows)
, m_cols(copy.m_cols)
, m_buffer(copy.m_buffer)
{}
// Move constructor
MyMatrix(MyMatrix&& move) noexcept
{
*this = std::move(move);
}
explicit MyMatrix<T>(iterator begin, iterator end, size_type dimx, size_type dimy)
: m_rows(dimx)
, m_cols(dimy)
, m_buffer(std::distance(begin, end))
{
std::copy(begin, end, m_buffer.begin());
}
// Copy assignment
MyMatrix& operator=(MyMatrix const& copy)
{
// Copy and Swap idiom
MyMatrix<value_type> tmp(copy);
tmp.swap(*this);
return *this;
}
// Move assignment
MyMatrix& operator=(MyMatrix&& move) noexcept
{
move.swap(*this);
return *this;
}
// Iterators
iterator begin() { return m_buffer.begin(); }
const_iterator begin() const { return m_buffer.begin(); }
const_iterator cbegin() const { return begin(); }
iterator end() { return m_buffer.end(); }
const_iterator end() const { return m_buffer.end(); }
const_iterator cend() const { return end(); }
// Access operators with validation
reference operator()(const size_type x, const size_type y)
{
size_type index = m_cols * x + y;
assert(index < m_buffer.size() && "Index is out of range");
return m_buffer[index];
}
const_reference operator()(const size_type x, const size_type y) const
{
size_type index = m_cols * x + y;
assert(index < m_buffer.size() && "Index is out of range");
return m_buffer[index];
}
reference operator[](size_type index)
{
assert(index < m_buffer.size() && "Index is out of range");
return m_buffer[index];
}
const_reference operator[](size_type index) const
{
assert(index < m_buffer.size() && "Index is out of range");
return m_buffer[index];
}
// Mutating functions
void ident()
{
assert(m_rows == m_cols && "Matrix must be square!");
for (size_type x = 0; x < m_rows; ++x) {
for (size_type y = 0; y < m_cols; ++y)
m_buffer[m_cols * x + y] = static_cast<T>(x == y); // CORRECT ?
}
}
void fill(value_type value)
{
std::fill(m_buffer.begin(), m_buffer.end(), value);
}
void fillRand()
{
std::generate(m_buffer.begin(), m_buffer.end(), []() {return std::rand() % 10; });
}
void swap(MyMatrix<value_type>& other) noexcept
{
using std::swap;
swap(this->m_rows, other.m_rows);
swap(this->m_cols, other.m_cols);
swap(this->m_buffer, other.m_buffer);
}
// Inspecting functions
size_type rows() const
{ return m_rows; }
size_type cols() const
{ return m_cols; }
template<class T> // linkage error without this!
friend std::ostream& operator<<(std::ostream& out, MyMatrix<T> const& mtx);
// Matrix mathematical operations
MyMatrix operator+(MyMatrix const& mtx) const
{
MyMatrix<T> result(*this);
return result += mtx;
}
MyMatrix& operator+=(MyMatrix const& mtx)
{
assert(m_rows == mtx.m_rows || m_cols == mtx.m_cols && "Matrix dimension must be the same.");
std::transform(m_buffer.begin(), m_buffer.end(), mtx.m_buffer.begin(), m_buffer.begin(), std::plus<>{});
return *this;
}
MyMatrix operator-(MyMatrix const& mtx) const
{
MyMatrix<T> result(*this);
return result -= mtx;
}
MyMatrix& operator-=(MyMatrix const& mtx)
{
assert(m_rows == mtx.m_rows || m_cols == mtx.m_cols && "Matrix dimension must be the same.");
std::transform(m_buffer.begin(), m_buffer.end(), mtx.m_buffer.begin(), m_buffer.begin(), std::minus<>{});
return *this;
}
MyMatrix operator*(MyMatrix const& mtx) const
{
MyMatrix<T> tmp(*this);
return tmp *= mtx;
}
MyMatrix operator*=(MyMatrix const& mtx)
{
assert(m_cols == mtx.m_rows && "Invalid Matrix demensions.");
MyMatrix<value_type> result(m_rows, mtx.m_cols);
for (size_type r = 0; r < m_rows; r++) {
for (size_type c = 0; c < mtx.m_cols; c++) {
for (size_type i = 0; i < m_cols; i++) {
result.m_buffer[mtx.m_cols * r + c] += m_buffer[m_cols * r + i] * mtx.m_buffer[mtx.m_cols * i + c];
}
}
}
return result;
}
// Comparision
bool operator==(MyMatrix const& mtx) const noexcept
{
if (m_rows != mtx.m_rows || m_cols != mtx.m_cols)
return false;
std::for_each(m_buffer.begin(), m_buffer.end(), [&](const unsigned int i) { return m_buffer[i] != mtx.m_buffer[i]; });
return true;
}
bool operator!=(MyMatrix const& mtx) const noexcept { return !(*this == mtx); }
// Matrix scalar operations
MyMatrix& operator+(const T& value)
{
std::transform(m_buffer.begin(), m_buffer.end(), m_buffer.begin(), [&value](const T index) {return index + value; });
return *this;
}
MyMatrix& operator-(const T& value)
{
std::transform(m_buffer.begin(), m_buffer.end(), m_buffer.begin(), [&value](const T index) {return index - value; });
return *this;
}
MyMatrix& operator*(const T& value)
{
std::transform(m_buffer.begin(), m_buffer.end(), m_buffer.begin(), [&value](T index) {return index * value; });
return *this;
}
MyMatrix& operator/(const T& value)
{
std::transform(m_buffer.begin(), m_buffer.end(), m_buffer.begin(), [&value](T index) {return index / value; });
return *this;
}
};
template <typename T>
std::ostream& operator<<(std::ostream& out, MyMatrix<T> const& mtx)
{
std::size_t rows = mtx.rows();
std::size_t cols = mtx.cols();
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
out << mtx(i, j) << ' ';
}
out << "\n";
}
return out;
}
template <typename T>
MyMatrix<T> transpose(MyMatrix<T> const& mtx)
{
std::size_t rows = mtx.rows();
std::size_t cols = mtx.cols();
MyMatrix<T> result(cols, rows);
for (std::size_t r = 0; r < rows * cols; r++) {
std::size_t i = r / rows;
std::size_t j = r % rows;
result[r] = mtx[cols * j + i];
}
return result;
}
template <typename T>
MyMatrix<T> inverse(MyMatrix<T> const& mtx)
{
MyMatrix<T> result(mtx);
std::transform(result.begin(), result.end(), result.begin(), [](const T index) {return 1 / index; });
return result;
}
template <typename T>
MyMatrix<T> symmetric(MyMatrix<T> const& mtx)
{
assert(mtx.cols() == mtx.rows() && "Invalid Matrix demensions.");
MyMatrix<T> result(mtx);
return mtx * transpose(mtx);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T18:58:00.767",
"Id": "485535",
"Score": "0",
"body": "tried compiling using clang 10.0.1 but there is an error: `127:20: error: declaration of 'T' shadows template parameter`"
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef MATRIX_H\n#define MATRIX_H\n// file contents go here\n#endif // MATRIX_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n<h2>Use <code>throw</code> rather than <code>assert</code></h2>\n<p>The bounds checking your program does is good, but it should <code>throw</code> an exception rather than using <code>assert</code> to be compatible with STL containers.</p>\n<h2>Implement mathematical operations with templates</h2>\n<p>Consider the following code:</p>\n<pre><code>MyMatrix<float> fm;\nMyMatrix<int> im;\nfm += im;\n</code></pre>\n<p>This ought to work but does not because the current code requires both matrices to be of the same type. Better would be to write the function like this:</p>\n<pre><code>template<class U>\nMyMatrix& operator+=(MyMatrix<U> const& mtx)\n{\n if (m_rows != mtx.rows() || m_cols != mtx.cols()) \n throw std::invalid_argument("Matrix dimension must be the same.");\n std::transform(m_buffer.begin(), m_buffer.end(), mtx.begin(), m_buffer.begin(), std::plus<>{});\n return *this;\n}\n</code></pre>\n<p>Now it works with any pair of types for which <code>std::plus<></code> is defined.</p>\n<h2>Implement mathematical operations as freestanding functions</h2>\n<p>Consider this code:</p>\n<pre><code>MyMatrix<float> fm;\nauto doppel = fm + fm;\n</code></pre>\n<p>It should work but does not. Fix that by defining <code>operator+</code> as a freestanding templated function:</p>\n<pre><code>template <typename T, typename U>\nMyMatrix<T> operator+(MyMatrix<T> one, MyMatrix<U> const& two) {\n return one += two;\n}\n</code></pre>\n<h2>Don't shadow parameters</h2>\n<p>The inserter function is currently defined like this:</p>\n<pre><code>template<class T> // linkage error without this!\nfriend std::ostream& operator<<(std::ostream& out, MyMatrix<T> const& mtx);\n</code></pre>\n<p>The problem with that is it's inside a template that also takes a <code>class T</code> and the compiler has no way to distinguish between them. Fortunately, it's a simple fix here, just use a different letter, such as <code>U</code> for this declaration.</p>\n<h2>Implement unary operators</h2>\n<p>The unary <code>-</code> and unary <code>+</code> operators are missing. The result is that this fails:</p>\n<pre><code>std::cout << -foo << "\\n";\n</code></pre>\n<p>You could implement unary - like this:</p>\n<pre><code>MyMatrix operator-() const {\n MyMatrix result(*this);\n std::transform(result.begin(), result.end(), result.begin(), std::negate<>{});\n return result;\n}\n</code></pre>\n<h2>Fix the spelling errors</h2>\n<p>In some place the word "dimension" is spelled incorrectly. Since your code is mostly pretty nice, it's worth the extra step to eliminate spelling errors.</p>\n<h2>Implement operators with constant arguments</h2>\n<p>The <code>operator+=</code> is defined, but only for two objects of type <code>MyMatrix</code>. I would suggest implementing each of the operators so that the right side can be a constant. For example, this won't compile:</p>\n<pre><code>MyMatrix fm;\nfm += 2;\n</code></pre>\n<p>A simple way to address that is by defining those versions:</p>\n<pre><code>template<class U>\nMyMatrix& operator+=(U const& val)\n{\n std::for_each(m_buffer.begin(), m_buffer.end(), [val](T& item){ item += val; });\n return *this;\n}\n</code></pre>\n<h2>Eliminate work</h2>\n<p>The <code>operator==</code> is much more complex than it needs to be. Since the code is using a <code>std::vector</code> as the underlying storage, we can use the overloaded <code>operator==</code> for that and simplify the code:</p>\n<pre><code>bool operator==(MyMatrix const& mtx) const noexcept\n{\n return m_rows == mtx.m_rows && m_cols == mtx.m_cols && m_buffer == mtx.m_buffer;\n}\n</code></pre>\n<h2>Implement a <code>size()</code> operator</h2>\n<p>I'd write one like this:</p>\n<pre><code>size_type size() const \n{ return m_buffer.size(); }\n</code></pre>\n<h2>Avoid making assumptions about templated types</h2>\n<p>The <code>fillRand()</code> function appears to assume that the underlying type is numeric, but there is no guarentee of that. We could write this:</p>\n<pre><code>MyMatrix<std::string> sm{3, 2};\nsm.fillRand();\n</code></pre>\n<p>But it's unlikely to provide a satisfactory result because what happens is that it creates six strings, each one character long with the numeric value of the generated random value. For that reason, I'd suggest simply omitting that function. If you wish to only accomodate numeric values, then the code could include <code>std::enable_if</code> with the <a href=\"https://en.cppreference.com/w/cpp/types/is_arithmetic\" rel=\"nofollow noreferrer\"><code>is_arithmetic</code></a> type trait.</p>\n<h2>Consider implementing initializer list constructors</h2>\n<p>It would be nice to be able to do this:</p>\n<pre><code>MyMatrix<std::string> sm{3, 2, { "one", "two", "three", "four", "five", "six" }};\n</code></pre>\n<p>It's quite simple to accomodate this:</p>\n<pre><code>MyMatrix(size_type dimx, size_type dimy, std::initializer_list<T> init)\n : m_rows(dimx)\n , m_cols(dimy)\n , m_buffer(dimx * dimy)\n{\n const size_type minlen{std::min(m_buffer.size(), init.size())};\n std::copy_n(init.begin(), minlen, m_buffer.begin());\n}\n</code></pre>\n<h2>Don't overspecify functions</h2>\n<p>The <code>fill</code> function should not be a member function since a user of the class can just as easily use the existing <code>std::fill</code>. I would same suggestion about the inserter function (<code>std::ostream& operator<<</code>). It's OK to have one as a convenience function for testing (which I would suggest would also need a <code>wstream</code> version), but I would recommend against having it in a library.</p>\n<h2>Write test cases</h2>\n<p>I would strongly recommend writing a large number of test cases to make sure this code does what you intend. It's easy to miss small details. Here's your first test case:</p>\n<pre><code> MyMatrix<bool> b{5, 5};\n std::cout << b << "\\n";\n</code></pre>\n<p>On my machine, this segfaults and dies. See if you can figure out why and fix it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T20:23:53.743",
"Id": "485538",
"Score": "0",
"body": "Thank you, that's very helpful! I'll post an update here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T20:25:52.773",
"Id": "485539",
"Score": "0",
"body": "While it's great that the review enabled you to improve your code, please do not update the code in your question to incorporate feedback from answers. Doing so goes against the Question + Answer style of Code Review, as it unfortunately invalidates the existing review(s). This is not a forum where you should keep the most updated version in your question. Please see see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)* for ways to announce your new code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T20:40:17.637",
"Id": "485540",
"Score": "0",
"body": "it makes sense, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T04:33:11.857",
"Id": "485557",
"Score": "2",
"body": "That test case is a nasty trick. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T23:15:44.657",
"Id": "485768",
"Score": "0",
"body": "The test case compiles for me with a warning. But did you mean that a const bool being passed by reference? Should it be passed by value? ( I use visual studio 2019's version of clang.)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T19:20:47.843",
"Id": "247919",
"ParentId": "247916",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247919",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T18:10:58.107",
"Id": "247916",
"Score": "5",
"Tags": [
"c++",
"matrix"
],
"Title": "Matrix template with a vector buffer"
}
|
247916
|
<h1>Problem</h1>
<p>I'm trying to create the most performant code to:</p>
<ul>
<li>Extract a text file from a zip</li>
<li>parse its content</li>
<li>serialize class</li>
<li>post to Azure Queue Storage</li>
</ul>
<h1>Scenario</h1>
<p>4 times per year I receive 20 zip files. All zip files have just one text file inside.
Each text file is a fixed width file.
Each line in the text file is a different type of data. There are 3 of them:</p>
<ul>
<li>Company (First character of line is "1")</li>
<li>Partners (First character of line is "2")</li>
<li>Activity (First character of line is "6")</li>
</ul>
<p>They are always in sequence:</p>
<pre><code>1First Company Data ..................................
2First Company First Partner .........................
2First Company Second Partner ........................
2First Company Third Partner .........................
6First Company Activity ..............................
1Second Company Data .................................
2Second Company First Partner ........................
2Second Company Second Partner .......................
2Second Company Third Partner ........................
2Second Company Fourth Partner .......................
6Second Company Activity .............................
</code></pre>
<p>There are always one line for company, one line for activity, but zero to many partners.</p>
<p>Activity is compound of 7 numbers sequence repeated multiple times. For example:</p>
<ul>
<li>1111111 is an activity</li>
</ul>
<p>if the company have more than one activity, they are putted in sequence like:</p>
<ul>
<li>111111122222223333333</li>
</ul>
<p>if there's no other activity, zeros are used until the end of line:</p>
<ul>
<li>11111112222222333333300000000000000000000000000000000000</li>
</ul>
<p>the line identifier for activity is "6", so, the full line stills like:</p>
<ul>
<li>611111112222222333333300000000000000000000000000000000000</li>
</ul>
<p>Two companys appear like this way:</p>
<pre><code>1First Company Data .....................................
2First Company First Partner ............................
2First Company Second Partner ...........................
2First Company Third Partner ............................
611111112222222333333300000000000000000000000000000000000
1Second Company Data ....................................
2Second Company First Partner ...........................
2Second Company Second Partner ..........................
2Second Company Third Partner ...........................
2Second Company Fourth Partner ..........................
644444445555555000000000000000000000000000000000000000000
</code></pre>
<p>the zip files need to be read in sequence, because, the last line of a file may be in the middle of company data:</p>
<pre><code>1First Company Data .....................................
2First Company First Partner ............................
2First Company Second Partner ...........................
2First Company Third Partner ............................
611111112222222333333300000000000000000000000000000000000
1Second Company Data ....................................
2Second Company First Partner ...........................
[------ END OF FILE 1 ------]
[----- BEGIN OF FILE 2 -----]
2Second Company Second Partner ..........................
2Second Company Third Partner ...........................
2Second Company Fourth Partner ..........................
644444445555555000000000000000000000000000000000000000000
</code></pre>
<h1>About the code</h1>
<p>I never worked with multithread before, I tried to put a thread to open the zip files, read its content, parse the data and post it to a Blocking Collection. The second thread I used to post Base 64 Encoded serialized class to Azure Queue Storage. I tried to use more than one thread to this but with no success. The third thread I use just to notify about the processing. I used a trick to post data to Azure Queue in batch, it sped up the performance, but I don't know if there is a more secure and better way to do this.</p>
<p>I'm posting to Azure Queue Storage, and, in the other side, I have another console to take data from Azure Queue and post to SQL Server. If there is a way to do this that is secure and reliable, but without using Azure Queue, I'll appreciate too. I tried this method in the first time, but network problems in the middle of process make me lost 120,000 companies data.
The total of companies is about 43,000,000.</p>
<p>The data is public, and can be downloaded at:
<a href="http://receita.economia.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/dados-publicos-cnpj" rel="noreferrer">http://receita.economia.gov.br/orientacao/tributaria/cadastros/cadastro-nacional-de-pessoas-juridicas-cnpj/dados-publicos-cnpj</a></p>
<h1>Code</h1>
<p>this is the main console code</p>
<pre><code>using Azure.Storage.Queues;
using BaseReceita.Producer.Model;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
namespace BaseReceita.Producer
{
class Program
{
private static string FilesDirectory { get; set; }
static void Main(string[] args)
{
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Starting...");
Console.WriteLine("Specify the folder with zip files: ");
FilesDirectory = @"" + Console.ReadLine();
Start().Wait();
}
private static async Task Start()
{
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] starting to read...");
var watch = new Stopwatch();
watch.Start();
ServicePointManager.UseNagleAlgorithm = false;
ServicePointManager.DefaultConnectionLimit = 1000;
object lockobj = new object();
long RegistrosProcessados = 0;
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
IConfigurationRoot Configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
string storageConnectionString = Configuration["Storage:ConnectionString"];
QueueClient queueClient = new QueueClient(storageConnectionString, "rfb-update-queue");
//-------------------- Collection
BufferBlock<string> buffer = new BufferBlock<string>(new DataflowBlockOptions() { BoundedCapacity = 50000 });
//-------------------- Consumers
var Consumers = new List<Task>();
for (var i = 0; i < 1; i++)
{
Consumers.Add(Task.Run(async () => {
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Consumer starting.");
while (await buffer.OutputAvailableAsync(ct))
{
if (buffer.TryReceiveAll(out var items))
{
try
{
await SendMessagesAsync(queueClient, items.AsEnumerable());
lock (lockobj)
RegistrosProcessados = RegistrosProcessados + items.Count;
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Erro: {e.Message}");
Console.ResetColor();
//throw;
}
}
}
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Consumer finalized");
Console.ResetColor();
}));
}
//-------------------- Notifier
Task Notifier = Task.Factory.StartNew(() =>
{
while (true)
{
if (!ct.IsCancellationRequested)
{
//F = Buffer Size
//P = Processed companies
//in the sequence, average processed per second, per minute and per hour
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] F-{buffer.Count} P-{RegistrosProcessados:n0} ({RegistrosProcessados / watch.Elapsed.TotalSeconds:n0}/s | {RegistrosProcessados / (watch.Elapsed.TotalSeconds / 60):n0}/m | {RegistrosProcessados / (watch.Elapsed.TotalSeconds / 60 / 60):n0}/h)");
Thread.Sleep(5000); //notify every 5 seconds
}
else
{
break;
}
}
});
//-------------------- Producer
Task Producer = Task.Run(async () =>
{
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Producer started.");
string conjunto = string.Empty;
string linha = string.Empty;
try
{
//open all zip files
foreach (string file in Directory.EnumerateFiles(FilesDirectory, "*.zip"))
{
//open zip
using (ZipFile zf = new ZipFile(file))
{
//take all files (aways will be one file
foreach (ZipEntry entry in zf)
{
//open as stream
using (var stream = zf.GetInputStream(entry))
using (var reader = new StreamReader(stream))
{
//read line from file
while ((linha = reader.ReadLine()) != null)
{
string tipoCampo = linha.Substring(0, 1);
if (tipoCampo == "1")
{
//every "1" is a new company, than, I parse the last company based on all the text extracted
EmpresaModel empresa = Parse(conjunto);
if (empresa != null)
{
//the first time will be null
//the others wont
//serialize, compress and post to buffer
string json = JsonConvert.SerializeObject(empresa);
string compressed = Base64Compress(json);
buffer.Post(compressed);
}
conjunto = linha;
}
else if (tipoCampo != "0")
{
conjunto = conjunto + Environment.NewLine + linha;
}
}
}
}
}
}
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Producer Error: {e.Message}");
Console.ResetColor();
}
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Producer finalized");
Console.ResetColor();
});
try
{
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Starting threads.");
List<Task> tasks = new List<Task>();
tasks.Add(Producer);
tasks.AddRange(Consumers);
Task.WaitAll(tasks.ToArray());
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Threads finalized");
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Error: {e.Message}");
Console.ResetColor();
}
ts.Cancel();
watch.Stop();
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Total Time: {watch.Elapsed.ToString()}");
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] Pushed-{RegistrosProcessados:n0} ({RegistrosProcessados / watch.Elapsed.TotalSeconds:n0}/s | {RegistrosProcessados / (watch.Elapsed.TotalSeconds / 60):n0}/m | {RegistrosProcessados / (watch.Elapsed.TotalSeconds / 60 / 60):n0}/h)");
Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] End of process");
Console.ReadLine();
}
private static EmpresaModel Parse(string conjunto)
{
EmpresaModel empresa = null;
if (!string.IsNullOrEmpty(conjunto))
{
string[] linhas = conjunto.Trim().Split(new[] { '\n' });
foreach (string linha in linhas)
{
string cnpj = linha.Substring(3, 14);
if (linha.Substring(0, 1) == "1")
{
//Company
empresa = new EmpresaModel();
empresa.Cnpj = cnpj;
empresa.IndicadorMatrizFilial = linha.Substring(17, 1).Trim();
empresa.RazaoSocial = linha.Substring(18, 150).Trim();
empresa.NomeFantasia = linha.Substring(168, 55).Trim();
empresa.CodigoSituacaoCadastral = linha.Substring(223, 2).Trim();
//empresa.SituacaoCadastral = (string)SituacaoCadastral.FirstOrDefault(x => x.Key == empresa.CodigoSituacaoCadastral).Value;
empresa.DataSituacaoCadastral = linha.Substring(225, 8).Trim();
empresa.CodigoMotivoSituacaoCadastral = linha.Substring(233, 2).Trim();
//empresa.MotivoSituacaoCadastral = (string)MotivoSituacaoCadastral.FirstOrDefault(x => x.Key == empresa.CodigoMotivoSituacaoCadastral).Value;
empresa.CidadeExterior = linha.Substring(235, 55).Trim();
empresa.CodigoPais = linha.Substring(290, 3).Trim();
empresa.Pais = linha.Substring(293, 70).Trim();
empresa.CodigoNaturezaJuridica = linha.Substring(363, 3).Trim() + "-" + linha.Substring(366, 1).Trim();
//empresa.NaturezaJuridica = (string)NaturezaJuridica.FirstOrDefault(x => x.Key == empresa.CodigoNaturezaJuridica).Value;
empresa.DataInicioAtividade = linha.Substring(367, 8).Trim();
empresa.IdCnae = linha.Substring(375, 7).Trim();
empresa.TipoLogradouro = linha.Substring(382, 20).Trim();
empresa.Logradouro = linha.Substring(402, 60).Trim();
empresa.Numero = linha.Substring(462, 6).Trim();
empresa.Complemento = linha.Substring(468, 156).Trim();
empresa.Bairro = linha.Substring(624, 50).Trim();
empresa.Cep = linha.Substring(674, 8).Trim();
empresa.UF = linha.Substring(682, 2).Trim();
empresa.CodigoMunicipio = linha.Substring(684, 4).Trim();
empresa.Municipio = linha.Substring(688, 50).Trim();
empresa.DDD1 = linha.Substring(738, 4).Trim();
empresa.Telefone1 = linha.Substring(742, 8).Trim();
empresa.DDD2 = linha.Substring(750, 4).Trim();
empresa.Telefone2 = linha.Substring(754, 8).Trim();
empresa.DDDFax = linha.Substring(762, 4).Trim();
empresa.TelefoneFax = linha.Substring(766, 8).Trim();
empresa.Email = linha.Substring(774, 115).Trim();
empresa.CodigoQualificacaoResponsavel = linha.Substring(889, 2).Trim();
empresa.CapitalSocial = linha.Substring(891, 14).Trim();
empresa.CodigoPorteEmpresa = linha.Substring(905, 2).Trim();
empresa.CodigoOpcaoSimplesNacional = linha.Substring(907, 1).Trim();
empresa.DataOpcaoSimples = linha.Substring(908, 8).Trim();
empresa.OptanteMei = linha.Substring(924, 1).Trim();
empresa.SituacaoEspecial = linha.Substring(925, 23).Trim();
empresa.DataSituacaoEspecial = linha.Substring(948, 8).Trim();
}
else if (linha.Substring(0, 1) == "2")
{
//Partners
QuadroSocietarioModel qsa = new QuadroSocietarioModel();
qsa.Cnpj = linha.Substring(3, 14).Trim();
qsa.IdentificadorSocio = linha.Substring(17, 1).Trim();
qsa.NomeSocio = linha.Substring(18, 150).Trim();
qsa.CnpjCpfSocio = linha.Substring(168, 14).Trim();
qsa.CodigoQualificacaoSocio = linha.Substring(182, 2).Trim();
//qsa.QualificacaoSocio = (string)QualificacaoResponsavelSocio.FirstOrDefault(x => x.Key == qsa.CodigoQualificacaoSocio).Value;
qsa.PercentualCapitalSocial = linha.Substring(184, 5).Trim();
qsa.DataEntradaSociedade = linha.Substring(189, 8).Trim();
qsa.CodigoPais = linha.Substring(197, 3).Trim();
qsa.Pais = linha.Substring(200, 70).Trim();
qsa.CpfRepresentanteLegal = linha.Substring(270, 11).Trim();
qsa.NomeRepresentante = linha.Substring(281, 60).Trim();
qsa.CodigoQualificacaoRepresentanteLegal = linha.Substring(341, 2).Trim();
empresa?.QuadroSocietario.Add(qsa);
}
else if (linha.Substring(0, 1) == "6")
{
//Activity
string[] cnaes =
Split(linha.Substring(17, 693).Trim(), 7)
.Where(x => x != "0000000")
.Where(x => !string.IsNullOrEmpty(x.Trim()))
//.Select(x => "cnae/" + x)
.ToArray();
foreach (string cnae in cnaes)
{
CnaeSecundarioModel cnaeSecundario = new CnaeSecundarioModel();
cnaeSecundario.Cnpj = cnpj;
cnaeSecundario.Cnae = cnae;
empresa?.CnaesSecundarios.Add(cnaeSecundario);
}
}
}
}
return empresa;
}
private static IEnumerable<string> Split(string str, int chunkSize)
{
return Enumerable.Range(0, str.Length / chunkSize)
.Select(i => str.Substring(i * chunkSize, chunkSize));
}
private static string Base64Compress(string s)
{
byte[] inputBytes = Encoding.UTF8.GetBytes(s);
using (var outputStream = new MemoryStream())
{
using (var gZipStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionMode.Compress))
gZipStream.Write(inputBytes, 0, inputBytes.Length);
var outputBytes = outputStream.ToArray();
var outputbase64 = Convert.ToBase64String(outputBytes);
return outputbase64;
}
}
public static async Task SendMessagesAsync(QueueClient queue, IEnumerable<string> messages)
{
await Task.WhenAll(
from partition in Partitioner.Create(messages).GetPartitions(500)
select Task.Run(async delegate
{
using (partition)
while (partition.MoveNext())
await queue.SendMessageAsync(partition.Current);
}));
}
}
}
</code></pre>
<p>here are the entities</p>
<pre><code>using System.Collections.Generic;
namespace BaseReceita.Producer.Model
{
public class EmpresaModel
{
public EmpresaModel()
{
QuadroSocietario = new HashSet<QuadroSocietarioModel>();
CnaesSecundarios = new HashSet<CnaeSecundarioModel>();
}
public string Cnpj { get; set; }
public string IndicadorMatrizFilial { get; set; }
public string RazaoSocial { get; set; }
public string NomeFantasia { get; set; }
public string CodigoSituacaoCadastral { get; set; }
public string DataSituacaoCadastral { get; set; }
public string CodigoMotivoSituacaoCadastral { get; set; }
public string CidadeExterior { get; set; }
public string CodigoPais { get; set; }
public string Pais { get; set; }
public string CodigoNaturezaJuridica { get; set; }
public string DataInicioAtividade { get; set; }
public string IdCnae { get; set; }
public string TipoLogradouro { get; set; }
public string Logradouro { get; set; }
public string Numero { get; set; }
public string Complemento { get; set; }
public string Bairro { get; set; }
public string Cep { get; set; }
public string UF { get; set; }
public string CodigoMunicipio { get; set; }
public string Municipio { get; set; }
public string DDD1 { get; set; }
public string Telefone1 { get; set; }
public string DDD2 { get; set; }
public string Telefone2 { get; set; }
public string DDDFax { get; set; }
public string TelefoneFax { get; set; }
public string Email { get; set; }
public string CodigoQualificacaoResponsavel { get; set; }
public string CapitalSocial { get; set; }
public string CodigoPorteEmpresa { get; set; }
public string CodigoOpcaoSimplesNacional { get; set; }
public string DataOpcaoSimples { get; set; }
public string OptanteMei { get; set; }
public string SituacaoEspecial { get; set; }
public string DataSituacaoEspecial { get; set; }
public HashSet<QuadroSocietarioModel> QuadroSocietario { get; set; }
public HashSet<CnaeSecundarioModel> CnaesSecundarios { get; set; }
}
public class QuadroSocietarioModel
{
public string Cnpj { get; set; }
public string IdentificadorSocio { get; set; }
public string NomeSocio { get; set; }
public string CnpjCpfSocio { get; set; }
public string CodigoQualificacaoSocio { get; set; }
public string PercentualCapitalSocial { get; set; }
public string DataEntradaSociedade { get; set; }
public string CodigoPais { get; set; }
public string Pais { get; set; }
public string CpfRepresentanteLegal { get; set; }
public string NomeRepresentante { get; set; }
public string CodigoQualificacaoRepresentanteLegal { get; set; }
}
public class CnaeSecundarioModel
{
public string Cnpj { get; set; }
public string Cnae { get; set; }
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I assume you are using .net core. If so you should make the Main method to be async Task Main(string[] args) have been supported since .net core 2.0. I would move the configuration builder into the main method as well. Have everything you need to support running your app in the main method.</p>\n<p>Right now you have a couple of big methods that do a lot of things and we want to have more methods but each method do one thing. Some simple ones to break out</p>\n<pre><code>/// <summary>\n/// Creates Empresa (Company)\n/// </summary>\n/// <param name="data">Info to use to fill in model (fixed width)</param>\n/// <returns></returns>\nprivate EmpresaModel CreateCompany(string data)\n{\n return new EmpresaModel()\n {\n Cnpj = data.Substring(3, 14),\n IndicadorMatrizFilial = data.Substring(17, 1).Trim(),\n RazaoSocial = data.Substring(18, 150).Trim(),\n NomeFantasia = data.Substring(168, 55).Trim(),\n CodigoSituacaoCadastral = data.Substring(223, 2).Trim(),\n DataSituacaoCadastral = data.Substring(225, 8).Trim(),\n CodigoMotivoSituacaoCadastral = data.Substring(233, 2).Trim(),\n CidadeExterior = data.Substring(235, 55).Trim(),\n CodigoPais = data.Substring(290, 3).Trim(),\n Pais = data.Substring(293, 70).Trim(),\n CodigoNaturezaJuridica = data.Substring(363, 3).Trim() + "-" + data.Substring(366, 1).Trim(),\n DataInicioAtividade = data.Substring(367, 8).Trim(),\n IdCnae = data.Substring(375, 7).Trim(),\n TipoLogradouro = data.Substring(382, 20).Trim(),\n Logradouro = data.Substring(402, 60).Trim(),\n Numero = data.Substring(462, 6).Trim(),\n Complemento = data.Substring(468, 156).Trim(),\n Bairro = data.Substring(624, 50).Trim(),\n Cep = data.Substring(674, 8).Trim(),\n UF = data.Substring(682, 2).Trim(),\n CodigoMunicipio = data.Substring(684, 4).Trim(),\n Municipio = data.Substring(688, 50).Trim(),\n DDD1 = data.Substring(738, 4).Trim(),\n Telefone1 = data.Substring(742, 8).Trim(),\n DDD2 = data.Substring(750, 4).Trim(),\n Telefone2 = data.Substring(754, 8).Trim(),\n DDDFax = data.Substring(762, 4).Trim(),\n TelefoneFax = data.Substring(766, 8).Trim(),\n Email = data.Substring(774, 115).Trim(),\n CodigoQualificacaoResponsavel = data.Substring(889, 2).Trim(),\n CapitalSocial = data.Substring(891, 14).Trim(),\n CodigoPorteEmpresa = data.Substring(905, 2).Trim(),\n CodigoOpcaoSimplesNacional = data.Substring(907, 1).Trim(),\n DataOpcaoSimples = data.Substring(908, 8).Trim(),\n OptanteMei = data.Substring(924, 1).Trim(),\n SituacaoEspecial = data.Substring(925, 23).Trim(),\n DataSituacaoEspecial = data.Substring(948, 8).Trim(),\n };\n}\n\n/// <summary>\n/// Creates QuadroSocietario (Partner)\n/// </summary>\n/// <param name="data">Info to use to fill in model (fixed width)</param>\n/// <returns></returns>\nprivate QuadroSocietarioModel CreatePartner(string data)\n{\n return new QuadroSocietarioModel()\n {\n Cnpj = data.Substring(3, 14).Trim(),\n IdentificadorSocio = data.Substring(17, 1).Trim(),\n NomeSocio = data.Substring(18, 150).Trim(),\n CnpjCpfSocio = data.Substring(168, 14).Trim(),\n CodigoQualificacaoSocio = data.Substring(182, 2).Trim(),\n PercentualCapitalSocial = data.Substring(184, 5).Trim(),\n DataEntradaSociedade = data.Substring(189, 8).Trim(),\n CodigoPais = data.Substring(197, 3).Trim(),\n Pais = data.Substring(200, 70).Trim(),\n CpfRepresentanteLegal = data.Substring(270, 11).Trim(),\n NomeRepresentante = data.Substring(281, 60).Trim(),\n CodigoQualificacaoRepresentanteLegal = data.Substring(341, 2).Trim(),\n };\n}\n\n/// <summary>\n/// Creates CnaeSecundarioModel (Activities)\n/// </summary>\n/// <param name="data">Info to use to fill in model (fixed width)</param>\n/// <returns></returns>\nprivate IEnumerable<CnaeSecundarioModel> CreateActivities(string data)\n{\n var cnpj = data.Substring(3, 14);\n // why do we start at 17?\n return Split(data.Substring(17, 693).Trim(), 7)\n .Where(x => !string.IsNullOrEmpty(x) && x != "0000000")\n .Select(cnae => new CnaeSecundarioModel()\n {\n Cnae = cnae,\n Cnpj = cnpj\n });\n}\n</code></pre>\n<p>To help "hide" the magic values for Company/Partners/Activities we can create an enum for those values. Also a value for unknown and end of file which we will use in a bit</p>\n<pre><code>public enum LineType\n{\n Skip = '0',\n Company = '1',\n Partners = '2',\n Activity = '6',\n EOF = 'E',\n Unknown = 'X'\n}\n</code></pre>\n<p>Since we are using TPL DataFlow we can create a mesh that will help process. So first thing we need is a method to convert the zip file into models and a method to read the entries in the zip file. I'm using System.IO.Compression for reading the zip and Microsoft.Extensions.Logging to add some logging.</p>\n<pre><code>/// <summary>\n/// Converts Fixed Line files into Company models\n/// </summary>\n/// <param name="lines">Lines from file</param>\n/// <param name="token">Cancellation Token</param>\n/// <returns></returns>\nprivate async IAsyncEnumerable<EmpresaModel> Deserialize(string file, [EnumeratorCancellation] CancellationToken token = default)\n{\n EmpresaModel empresa = null;\n await foreach (var line in GetData(file).WithCancellation(token).ConfigureAwait(false))\n {\n if (string.IsNullOrWhiteSpace(line))\n {\n continue;\n }\n var type = (LineType)line[0];\n switch (type)\n {\n case LineType.EOF:\n {\n if (empresa != null)\n {\n yield return empresa;\n empresa = null;\n }\n break;\n }\n case LineType.Skip:\n {\n break;\n }\n case LineType.Company:\n {\n if (empresa != null)\n {\n yield return empresa;\n }\n\n empresa = CreateCompany(line);\n break;\n }\n case LineType.Partners:\n {\n if (empresa == null)\n {\n this.logger.LogWarning(new EventId((int)LineType.Partners, LineType.Partners.ToString()), "Missing Company");\n break;\n }\n empresa.QuadroSocietario.Add(CreatePartner(line));\n break;\n }\n case LineType.Activity:\n {\n if (empresa == null)\n {\n this.logger.LogWarning(new EventId((int)LineType.Activity, LineType.Activity.ToString()), "Missing Company");\n break;\n }\n foreach (var activity in CreateActivities(line))\n {\n empresa.CnaesSecundarios.Add(activity);\n }\n break;\n }\n default:\n {\n this.logger.LogError(new EventId((int)LineType.Unknown, LineType.Unknown.ToString()), new FileFormatException("Unkown line type"), "Unkown line type");\n break;\n }\n }\n }\n\n if (empresa != null)\n {\n yield return empresa;\n }\n}\n\n/// <summary>\n/// Open zip files reads all files and outputs their text\n/// </summary>\n/// <param name="zipFile"></param>\n/// <param name="token"></param>\n/// <returns>Enumerable for each file in archive with asyncenum to read the lines in that file</returns>\nprivate async IAsyncEnumerable<string> GetData(string zipFile, [EnumeratorCancellation] CancellationToken token = default)\n{\n using (var archive = ZipFile.OpenRead(zipFile))\n {\n foreach (var file in archive.Entries)\n {\n using (var fileStream = file.Open())\n {\n using (var reader = new StreamReader(fileStream))\n {\n while (!reader.EndOfStream && !token.IsCancellationRequested)\n {\n var line = await reader.ReadLineAsync().ConfigureAwait(false);\n if (line != null)\n {\n yield return line;\n }\n }\n // special case for end of file\n yield return ((Char)LineType.EOF).ToString();\n }\n }\n }\n }\n}\n</code></pre>\n<p>Now we need a custom Data flow block that will take in path to zipfile and output all the models in it.</p>\n<pre><code>/// <summary>\n/// Creates a Data Block that takes in the zip file path and out put models\n/// </summary>\n/// <param name="ExecutionDataflowBlockOptions"></param>\n/// <returns>Custom Data Flow Block</returns>\nprivate IPropagatorBlock<string, EmpresaModel> ExtractZip(ExecutionDataflowBlockOptions options = null)\n{\n var token = options?.CancellationToken ?? CancellationToken.None;\n // this will Broadcase out the models once build\n var source = new TransformBlock<EmpresaModel, EmpresaModel>(t => t, options);\n // Will go threw the zip and create the models\n var target = new ActionBlock<string>(async file =>\n {\n await foreach (var model in Deserialize(file).WithCancellation(token).ConfigureAwait(false))\n {\n await source.SendAsync(model, token).ConfigureAwait(false);\n }\n }, options);\n\n // When the target is set to the completed state set the source to the completed state.\n target.Completion.ContinueWith(_ => source.Complete());\n\n return DataflowBlock.Encapsulate(target, source);\n}\n</code></pre>\n<p>For outputting progress I typically use the IProgress<> interface. Because I want it to be threadsafe I'm going to implement the interface myself and not use the Progress class.</p>\n<pre><code>public class Notifier : IProgress<int> \n{\n private int totalCount = 0;\n private DateTime startTime = DateTime.Now;\n private DateTime lastNotified = DateTime.Now.Subtract(TimeSpan.FromSeconds(5));\n public void Report(int numberToAdd)\n {\n var total = Interlocked.Add(ref totalCount, numberToAdd);\n if (DateTime.Now.Subtract(lastNotified) >= TimeSpan.FromSeconds(5))\n {\n var totalSeconds = DateTime.Now.Subtract(startTime).TotalSeconds;\n Console.WriteLine($"[{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}] P-{total:n0} ({total / totalSeconds:n0}/s | {total / (totalSeconds / 60):n0}/m | {total / (totalSeconds / 60 / 60):n0}/h)");\n lastNotified = DateTime.Now;\n }\n }\n}\n</code></pre>\n<p>We will create a method to encode the models. I'm using the System.Text.Json and pushing json stream into the gzip stream to not have to create a memory stream</p>\n<pre><code>private async Task<string> SerializeAsync(EmpresaModel model, CancellationToken token)\n{\n using (var memoryStream = new MemoryStream())\n {\n using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Compress))\n {\n await JsonSerializer.SerializeAsync(gzipStream, model, null, token).ConfigureAwait(false);\n }\n return Convert.ToBase64String(memoryStream.ToArray());\n }\n}\n</code></pre>\n<p>The last thing we need is a method to send to the Azure. If wanting to go to SQL and not have issue where you lost records then should look into Poly to handle transient errors. Plus wrap it all in a transaction so they either complete or rollback as one statement. With this when Poly retries you will get atomic writes</p>\n<pre><code>private async Task<string> SendToQueue(QueueClient client, string message, CancellationToken token)\n{\n // if want to go directly to SQL then in this method can add Poly to handle transient errors\n var receipt = await client.SendMessageAsync(message, token).ConfigureAwait(false);\n return receipt.Value.MessageId;\n}\n</code></pre>\n<p>Noe that we have all the methods we just need to create the mesh pipeline.</p>\n<pre><code>public async Task Start(string directory, QueueClient client, IProgress<int> progress, CancellationToken token)\n{\n var executionBlockOptions = new ExecutionDataflowBlockOptions()\n {\n CancellationToken = token,\n // MaxDegreeOfParallelism = 2,\n BoundedCapacity = 500\n };\n\n var extractZip = ExtractZip(executionBlockOptions);\n var encode = new TransformBlock<EmpresaModel, string>(async x => await SerializeAsync(x, token).ConfigureAwait(false), executionBlockOptions);\n var sendToQueue = new TransformBlock<string, string>(async x => await SendToQueue(client, x, token).ConfigureAwait(false), executionBlockOptions);\n var report = new ActionBlock<string>(_ => progress.Report(1), executionBlockOptions);\n var linkOptions = new DataflowLinkOptions()\n {\n PropagateCompletion = true,\n };\n extractZip.LinkTo(encode, linkOptions);\n encode.LinkTo(sendToQueue, linkOptions);\n sendToQueue.LinkTo(report, linkOptions);\n\n foreach (var file in Directory.EnumerateFiles(directory, "*.zip"))\n {\n await extractZip.SendAsync(file).ConfigureAwait(false);\n }\n extractZip.Complete();\n await report.Completion.ConfigureAwait(false);\n}\n</code></pre>\n<p>With all the async work we doing it actually slowed down how fast my machine could do if I set MaxDegreeOfParallelism. You could also have each Data flow block have its own execution option and tinker to see what performs best on your machine/network. Basically we setup the mesh to extract the data, then encode the data then sent to azure and finally report the progress. Then once the mesh is setup we loop through all the zip files in the directory and push the value into the mesh then wait for the entire mesh to finish.</p>\n<p>Every machine is different but I downloaded 6 of the zips and this used ~95% of my 8 core and processed around 7,500 companies a second. You can always tweak the data flow options to see what works best as I just took some guess, to be honest this took a lot of time but I was intrigued about it. Using the IAsyncEnumerable will help lower the memory as we don't need to load as much of the file into memory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T09:50:20.963",
"Id": "485645",
"Score": "0",
"body": "This is a splendid answer (+1). I'm not very familiar with the dataflow api/framework, so this is just a clarifying question: why are you using async/await for the delegates, you provide to `TransformBlock`/`ActionBlock`? Isn't that an extra layer of asynchronicity on top of that maintained by the framework (when sending each file to `extractZip` with `SendAsync()` - instead of `Post()`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T15:27:59.703",
"Id": "485675",
"Score": "0",
"body": "@HenrikHansen What I really want to use instead of the ExtractZip method is the TransformManyBlock but, at this time, it only supports IEnumerable and not IAsyncEnumerable. There is talk of them adding support for IAsyncEnumerbal and when that happens ExtractZip could be simplified, removing the ActionBlock/TransformBlock all together. To keep it as IAsyncEnumerable and still output multiple values for one input I had to create my own custom block. When creating your own block you need to provide the logic in the block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T16:28:33.677",
"Id": "485681",
"Score": "0",
"body": "OK, thanks, I think, I understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T16:42:29.840",
"Id": "486572",
"Score": "0",
"body": "Thanks for sharing, @CharlesNRice. I tested with your suggestions and it worked. Now the code is a lot more understandable and reliable."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T03:08:52.547",
"Id": "247974",
"ParentId": "247917",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247974",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T18:48:29.700",
"Id": "247917",
"Score": "6",
"Tags": [
"c#",
"multithreading",
"thread-safety",
"queue"
],
"Title": "Extract text file from zip, parse content and post to azure queue storage"
}
|
247917
|
<p>The exercise is as follows:</p>
<blockquote>
<p>Player A will write list <span class="math-container">\$ a \$</span> consisting of <span class="math-container">\$ n \$</span> numbers. Player B will take a look at the paper. After that the A player will ask player B <span class="math-container">\$q\$</span> questions. Each question will be of the following form:</p>
<p>If I give you two <span class="math-container">\$ R \$</span> and <span class="math-container">\$ L \$</span> in <span class="math-container">\$ a \$</span> such that (<span class="math-container">\$ 1<=L<=R<=n\$</span> ), calculate the following value:</p>
<p><span class="math-container">$$ 1*a[L] + 2*a[L+1] + 4*a[L+2] + ... + 2^{R-L-1}*a[R-1]+2^{R-L}*a[R] $$</span></p>
<p>Because the numbers can be really large, we need to find the residue that the result will give when divided by <span class="math-container">\$ 10^9 + 7\$</span>.</p>
<p>Input is as follows:</p>
<pre>
n q
a1 a2 an
L1 R1
L2 R2
Lq Rq
</pre>
<p>The output is: on one line the result for one query.</p>
</blockquote>
<p>The problem:</p>
<p>I need to improve performance so it is finished within 1 second. I think the problem may be because I have 2 for loops. Because the number of numbers can be up to 200,000 as well as the pairs. This means that in the worst case it has to go through the process 40,000,000,000 times.</p>
<p>Can someone please tell me how to improve the performance?</p>
<pre><code>#include <iostream>
using namespace std;
const int MAXN = 200000;
int residues[MAXN];
int numbers[MAXN];
int pairs[MAXN][2];
void findResidues(int i)
{
residues[i] = (residues[i - 1] * 2) % 1000000007;
}
long long int sumBetween(int first, int second)
{
long long int sum = 0;
int pos = first;
while(pos <= second)
{
sum += (long long)residues[pos - first] * numbers[pos];
sum %= 1000000007;
pos++;
}
return sum;
}
int main()
{
residues[0] = 1;
int n, q ;
cin >> n >> q;
for(int i = 0; i < n; i++)
{
cin >> numbers[i];
findResidues(i + 1);
}
for(int i = 0; i < q; i++)
{
cin >> pairs[i][0] >> pairs[i][1];
cout << sumBetween(pairs[i][0] - 1, pairs[i][1] - 1) << endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T09:59:49.580",
"Id": "485646",
"Score": "1",
"body": "I have big gripe with a lot of these \"programming challenges\", because almost all of them are actually *maths* problems, and the actual \"programming\" part of them is mostly trivial. I have no problem with those challenges, *per se*, but simply don't call them programming challenges, and *specifically* do not imply that solving them somehow makes you a good programmer. There's a reason *Project Euler* is named after a mathematician, not a programmer, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:00:58.753",
"Id": "485647",
"Score": "0",
"body": "Are they fun? Sure. Are they interesting puzzles? Yes. Are they in any way, shape or form useful for teaching programming or judging programming skills? Not in the slightest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:55:49.413",
"Id": "485960",
"Score": "0",
"body": "I think while finding a solution is clearly in the realm of mathematics and often relies on some piece of theory which one either _happens to know from experience_ (perhaps such as this) or must hunt for (especially having taken some brilliant mathematician years to evolve, it is unseemly to ask during limited-resource challenges, such as in-person interviews) .. once found, generating an implementation of it, or better optimizing an existing solution (as in this case) is extremely valuable for programmers to practice and consider."
}
] |
[
{
"body": "<p>The <code>std::endl</code> flushes the buffer every time, which makes the code slower.\nInstead of it, you should use <code>'\\n'</code> so the buffer only flushes when it's full.</p>\n<p>For further reading, check out <a href=\"https://en.cppreference.com/w/cpp/io/manip/flush\" rel=\"nofollow noreferrer\"><code>std::flush</code></a></p>\n<p>Hope it makes your code faster!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T20:58:48.140",
"Id": "485541",
"Score": "1",
"body": "There should be an even bigger win if input, output and data processing are all separated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T20:56:04.050",
"Id": "247922",
"ParentId": "247920",
"Score": "1"
}
},
{
"body": "<p>The code is already using symbolic constants such as <code>MAXN</code>, the code would be clearer if <code>1000000007</code> was a numeric constant as well.</p>\n<p>Are you sure that <code>first</code> and <code>second</code> will always be integers you may need to make these <code>long long</code> as well. When using a <code>long long</code> there is no reason to specify <code>int</code> as well, the values will be integer unless otherwise indicated.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<p>Pass the array <code>residues</code> into the functions <code>findResidues()</code> and <code>sumBetween()</code></p>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<h2>Use C++ Container Classes</h2>\n<p>The code is currently using old <code>C</code> programming style arrays, it would be better to use C++ container classes such as <a href=\"http://www.cplusplus.com/reference/array/array/\" rel=\"nofollow noreferrer\">std::array</a> or <a href=\"http://www.cplusplus.com/reference/vector/vector/\" rel=\"nofollow noreferrer\">std::vector</a>. Either one of these classes will allow you to use iterators which could possibly speed up the implementation.</p>\n<p>Possibly <code>std::vector</code> would be a better type to use that <code>std::array</code> would be in this particular problem. <code>std::vector</code> is a variable length array. If you want to continue using <code>MAXN</code> as the maximum size you can reserve the memory.</p>\n<h2>Gather All the Data Before Processing the Data</h2>\n<p>Currently the program is creating the resedue information as the data is being input. Rather than breaking up calculations by getting new input first get all of the input and then process the data. Getting all the input at once should help speed up the program, and will make the algorithm easier to follow.</p>\n<p>Break up the <code>main()</code> function a little more into 2 functions that get input and then functions that do the calculations.</p>\n<h2>Use <code>size_t</code> or Another <code>unsigned</code> Variable Type When Indexing Arrays or Other Indexed Variable Types</h2>\n<p>When indexing into arrays it is safer to use <code>size_t</code> because this is unsigned and the value can't go negative if it gets too large. Indexing by negative numbers can cause an immediate out of range exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:25:55.473",
"Id": "485650",
"Score": "0",
"body": "Overlapping computation and I/O can be good if you're limited by a slow I/O device (like reading a file that's not hot in pagecache). Assuming there's hardware and/or OS readahead, so spending time computing does give the disk some time to get some data into memory before you ask for more. With buffered I/O, you're not getting a system call for every `cin >>`, and you're making the same total number of system calls. It's probably better to avoid potentially-large arrays in your program, unless you actually prep large strings for one big multi-line `cout<<` to reduce locking overhead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:27:12.200",
"Id": "485651",
"Score": "0",
"body": "OTOH yes, doing a batch of computation at once can give the optimizer more room to auto-vectorize, and not touching IO buffer data structures between computations can let more of your data stay hot in cache."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T20:56:29.997",
"Id": "247923",
"ParentId": "247920",
"Score": "4"
}
},
{
"body": "<ul>\n<li><p><code>int pairs[MAXN][2];</code> wastes memory. You don't need to read all the queries at once:</p>\n<pre><code> for(int i = 0; i < q; i++)\n {\n cin >> L >> R;\n cout << sumBetween(L - 1, R - 1) << endl;\n }\n</code></pre>\n<p>works equally well. Besides, the problem statement doesn't say how many queries are there; it could be way more than the size of the array.</p>\n</li>\n<li><p>Your feeling that you use the wrong algorithm is well founded. Bruteforcing is almost always wrong. Look at the underlying math first. I don't want to spell out everything, just a couple of hints:</p>\n<ul>\n<li><p><span class=\"math-container\">\\$1*a_{L} + 2*a_{L+1}+ ... + 2^{R-L}*a_{R} = \\dfrac{2^L*a_{L} + 2^{L+1}*a_{L+1}+... + 2^R*a_{R}}{2^L}\\$</span></p>\n</li>\n<li><p>The numerator above is a difference of two partial sums of the <span class=\"math-container\">\\$2^n*a_{n}\\$</span> sequence.</p>\n</li>\n<li><p><span class=\"math-container\">\\$1000000007\\$</span> is a prime number, so division by <span class=\"math-container\">\\$2^L\\$</span> modulo <code>1000000007</code> is a multiplication by a multiplicative inverse of <code>2</code> modulo <code>1000000007</code> (which is trivial to find) to the same power.</p>\n</li>\n</ul>\n<p>I hope it is enough to get you going in the right direction. You should be able to answer each query in constant time.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T22:14:01.703",
"Id": "247926",
"ParentId": "247920",
"Score": "6"
}
},
{
"body": "<p>This looks to me like a issue about efficiency, not style.</p>\n<p>We can use prefix sums instead of brute forcing each case. (learn more <a href=\"https://en.wikipedia.org/wiki/Prefix_sum\" rel=\"nofollow noreferrer\">here</a>)</p>\n<p>Create an array <code>prefix</code> of size n + 1. At the ith index, find whatever the sum would be for the first i numbers. For example, if the list a was <code>a_1, a_2, a_3, ..., a_n)</code>, <code>prefix</code> would be <code>0, a_1, a_1 + 2*a_2, a_1+2*a_2+4*a_3, ...</code>.</p>\n<p>Then, if we wanted to query from <code>L</code> to <code>R</code>, we could find <code>prefix[R]-prefix[L-1]</code>. As a basic example, pretend <code>L=2, R=3</code>. Then, the difference mentioned above would be <code>prefix[3]-prefix[1] = 2*a_2+4*a_3</code>, which is double of the sum that we are expecting. Afterwards, we can divide by <code>2^{L-1}</code> to get what the exercise wants.</p>\n<p>I'm a little busy right now, but I will post some code as soon as possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T23:51:15.693",
"Id": "247931",
"ParentId": "247920",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-14T19:27:19.023",
"Id": "247920",
"Score": "8",
"Tags": [
"c++",
"performance",
"beginner",
"programming-challenge"
],
"Title": "Calculate sum of multiple series within array"
}
|
247920
|
<p><a href="https://github.com/AlexZhou876/music-editor" rel="nofollow noreferrer">Source</a></p>
<p>I made a project for a class, a MIDI editor written with Java 8 and Swing, and continued working on it on my own. However, I ran into a problem I couldn't solve and gave up.</p>
<p>I'd like feedback on high level design/architecture, things like cohesion, coupling etc between classes. I'm pretty sure the project is weak in this regard. Would MVC be appropriate here?</p>
<p>I'm also concerned about the model. I made it so that a composition has a list of measures, and a measure has a list of notes, but I think that was hard to work with and caused issues. Maybe a map data structure would have been better. The class for reading MIDI files became really complicated because I didn't model sequences and tracks.</p>
<p>The problem I couldn't solve was synchronizing the movement of the progress line and the audio playback. I know the focus of this site isn't to debug, so you don't have to comment on that.</p>
<p>Please feel free to offer any feedback at all also.</p>
<pre><code>package ui;
import model.Composition;
import persistence.Reader;
import ui.players.EntirePlayer;
import ui.sound.MidiSynth;
import ui.tools.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import static ui.CompositionPanel.SEMITONE_HEIGHT;
public class GraphicalEditorApp extends JFrame {
public static final int WIDTH = 1500;
public static final int HEIGHT = SEMITONE_HEIGHT * 88;
//public static final int HEIGHT = SEMITONE_HEIGHT * 70;
//public static final String SAVE_FILE = "./data/saveFile.mid";
public static final String SAVE_FILE = "./data/Gurenge.mid";
private MidiSynth midiSynth;
private EntirePlayer player;
private Timer masterTimer;
private CompositionPanel compositionPanel;
private JScrollPane scroller;
private List<Tool> tools; // is this even useful??
private Tool activeTool;
public GraphicalEditorApp() {
super("Music Editor");
initFields();
initGraphics();
initSound();
showInitDialog();
initInteraction();
}
public MidiSynth getMidiSynth() {
return midiSynth;
}
public CompositionPanel getCompositionPanel() {
return compositionPanel;
}
private void initFields() {
activeTool = null;
compositionPanel = new CompositionPanel(1, 4, 4, this);
//composition.addMeasures(1, 1, 4, 4);
tools = new ArrayList<Tool>();
}
// EFFECTS: allows the user to input init options, such as to load from file or create new.
private void showInitDialog() {
int closedOption = -1;
int yes = 0;
int no = 1;
String[] options = {"Yes", "No"};
int n = JOptionPane.showOptionDialog(this,
"Would you like to load the previously saved file?",
"Initialization",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[1]);
if (n == closedOption) {
return;
} else if (n == yes) {
loadProject();
} else {
return;
}
}
// MODIFIES: this
// EFFECTS: changes composition to the one contained in the save file
private void loadProject() {
compositionPanel.setComposition(Reader.readFile(new File(SAVE_FILE)));
compositionPanel.getComposition().addMidiSynthToAll(midiSynth);
// important!!
player.setComposition(compositionPanel.getComposition());
repaint();
}
private void initSound() {
midiSynth = new MidiSynth();
midiSynth.open();
}
private void initGraphics() {
setLayout(new BorderLayout());
setMinimumSize(new Dimension(WIDTH, HEIGHT));
createTools();
createNavigationBar();
addComposition();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
// necessary if size of composition may change???
setBackground(Color.black);
}
private void createNavigationBar() {
//JToolBar navigationBar = new JToolBar("Navigation");
JButton button = new JButton("Jump to");
JTextField measureNumber = new JTextField();
NavigationBar bar = new NavigationBar("Navigation", button, measureNumber, this);
add(bar, BorderLayout.PAGE_START);
}
// MODIFIES: this
// EFFECTS: adds a composition component to the editor
private void addComposition() {
//add(compositionPanel, BorderLayout.CENTER);
compositionPanel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
scroller = new JScrollPane(compositionPanel);
add(scroller, BorderLayout.CENTER);
validate();
}
public JScrollPane getScroller() {
return scroller;
}
// MODIFIES: this
// EFFECTS: declare and instantiate all tools
private void createTools() {
JPanel toolbar = new JPanel();
toolbar.setLayout(new GridLayout(0, 1));
toolbar.setSize((new Dimension(0, 0)));
add(toolbar, BorderLayout.EAST);
AddNoteTool addNoteTool = new AddNoteTool(this, toolbar);
tools.add(addNoteTool);
// should I add the others to the list?? What is the point of the list?
AddMeasuresTool addMeasuresTool = new AddMeasuresTool(this, toolbar);
EditNoteTool editNoteTool = new EditNoteTool(this, toolbar);
RemoveMeasuresTool removeMeasuresTool = new RemoveMeasuresTool(this, toolbar);
masterTimer = new Timer(0, null);
player = new EntirePlayer(compositionPanel.getComposition(), null, null);
PlayEntireTool playEntireTool = new PlayEntireTool(this, toolbar, player);
player.setTool(playEntireTool);
//player.setCompositionPanel(compositionPanel);
SaveTool saveTool = new SaveTool(this, toolbar);
setActiveTool(addNoteTool);
}
public EntirePlayer getPlayer() {
return player;
}
public Timer getMasterTimer() {
return masterTimer;
}
public void setMasterTimer(Timer masterTimer) {
this.masterTimer = masterTimer;
}
// MODIFIES: this
// EFFECTS: initializes EditorMouseListener and EKL for JFrame
private void initInteraction() {
EditorMouseListener eml = new EditorMouseListener();
compositionPanel.addMouseListener(eml);
compositionPanel.addMouseMotionListener(eml);
//EditorKeyListener ekl = new EditorKeyListener();
//addKeyListener(ekl);
//compositionPanel.addKeyListener(ekl);
//compositionPanel.setFocusable(true);
//compositionPanel.requestFocusInWindow();
}
// MODIFIES: this
// EFFECTS: sets the given tool as the activeTool
public void setActiveTool(Tool tool) {
if (activeTool != null) {
activeTool.deactivate();
}
tool.activate();
activeTool = tool;
}
// EFFECTS: if activeTool != null, then mousePressedInDrawingArea is invoked on activeTool, depends on the
// type of the tool which is currently activeTool
private void handleMousePressed(MouseEvent e) {
if (activeTool != null) {
activeTool.mousePressed(e);
}
repaint();
}
// EFFECTS: if activeTool != null, then mouseReleasedInDrawingArea is invoked on activeTool, depends on the
// type of the tool which is currently activeTool
private void handleMouseReleased(MouseEvent e) {
if (activeTool != null) {
activeTool.mouseReleased(e);
}
repaint();
}
// EFFECTS: if activeTool != null, then mouseClickedInDrawingArea is invoked on activeTool, depends on the
// type of the tool which is currently activeTool
private void handleMouseClicked(MouseEvent e) {
if (activeTool != null) {
activeTool.mouseClicked(e);
}
repaint();
}
// EFFECTS: if activeTool != null, then mouseDraggedInDrawingArea is invoked on activeTool, depends on the
// type of the tool which is currently activeTool
private void handleMouseDragged(MouseEvent e) {
if (activeTool != null) {
activeTool.mouseDragged(e);
}
repaint();
}
// EFFECTS: if activeTool != null, then keytyped is invoked on activeTool.
private void handleKeyTyped(KeyEvent ke) {
if (activeTool != null) {
activeTool.keyTyped(ke);
}
repaint();
}
// from SimpleDrawingPlayer (modified)
private class EditorMouseListener extends MouseAdapter {
// EFFECTS: Forward mouse pressed event to the active tool
public void mousePressed(MouseEvent e) {
handleMousePressed(translateEvent(e));
}
// EFFECTS: Forward mouse released event to the active tool
public void mouseReleased(MouseEvent e) {
handleMouseReleased(translateEvent(e));
}
// EFFECTS:Forward mouse clicked event to the active tool
public void mouseClicked(MouseEvent e) {
handleMouseClicked(translateEvent(e));
}
// EFFECTS:Forward mouse dragged event to the active tool
public void mouseDragged(MouseEvent e) {
handleMouseDragged(translateEvent(e));
}
// EFFECTS: translates the mouse event to current drawing's coordinate system
private MouseEvent translateEvent(MouseEvent e) {
return SwingUtilities.convertMouseEvent(e.getComponent(), e, compositionPanel);
}
}
}
</code></pre>
<pre><code>package ui;
import model.Composition;
import model.Measure;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
// a beat refers to a quarter beat.
public class CompositionPanel extends JPanel implements ActionListener, Scrollable {
private int playLineColumn;
private GraphicalEditorApp editor;
private Composition composition;
public static final int DEFAULT_BPM = 80;
public static final int MAXIMUM_BEAT_WIDTH = 512;
public static final int MINIMUM_BEAT_WIDTH = 1;
public static final int ZOOM_INTERVAL = 10;
public static int bpm;
//public static int resolution = 4; // initial tick is a 16th note
public static int tickWidth = 16;
//public static int beatWidth = tickWidth * resolution; //50, then tried 64
public static int beatWidth = 64;
public static final int SEMITONE_HEIGHT = 10;
public CompositionPanel(int numMeasures, int beatNum, int beatType, GraphicalEditorApp editor) {
super();
setBackground(Color.black);
composition = new Composition(numMeasures, beatNum, beatType);
this.editor = editor;
bpm = DEFAULT_BPM;
}
@Override
// MODIFIES: this
// EFFECTS: update this every time the timer fires by incrementing playLineColumn by one screen coordinate
// and scroll following.
public void actionPerformed(ActionEvent e) {
playLineColumn += 1;
repaint();
followPlaying();
//if (editor.getMasterTimer().getDelay() == )
}
// MODIFIES: this
// EFFECTS: stops the timer and resets the playLineColumn to 0.
public void stopPlaying() {
editor.getMasterTimer().stop();
playLineColumn = 0;
repaint();
}
// MODIFIES: this
// EFFECTS: sets the value of beatWidth and makes sure invariant relationships between static variables
// are maintained.
// value writes even of public static variables should be done locally and in one place so the repercussions can be
// handled in one place.
public void setBeatWidth(int newBeatWidth) {
float factor = (float) newBeatWidth / (float) beatWidth;
beatWidth = newBeatWidth;
tickWidth = Math.round(factor * tickWidth);
}
// EFFECTS: gets the end of the composition panel in screen x coordinate.
// OUTDATED
public int getEnd() {
int totalTicks = composition.getNumTicks();
return totalTicks * tickWidth;
//int totalBeats = composition.getNumBeats();
//return totalBeats * beatWidth;
}
// MODIFIES: this
// EFFECTS: changes the dimensions of this. If the new width is greater than the starting width, assign
// the new width. Otherwise do nothing.
public void resize() {
if (getEnd() > editor.WIDTH) {
setPreferredSize(new Dimension(getEnd(), editor.HEIGHT));
}
revalidate();
}
public void setBPM(int newBPM) {
bpm = newBPM;
}
public Composition getComposition() {
return composition;
}
// EFFECTS: sets composition to the given one, and ensures that the ratio of tickwidth to beatwidth
// obeys the resolution of the composition.
public void setComposition(Composition composition) {
this.composition = composition;
int amount = beatWidth / Composition.resolution;
if (amount == 0) {
amount = 1;
}
tickWidth = amount;
resize();
}
// EFFECTS: paints grid, playing line, notes in composition.
// calls to repaint() get here
@Override
public void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
drawLines(graphics);
// it may be better for measure.draw to draw bar lines.
for (Measure measure : composition.getListOfMeasure()) {
measure.draw(graphics);
}
}
// EFFECTS: draws semitone lines and bar lines
private void drawLines(Graphics graphics) {
int endX = 0;
Color save = graphics.getColor();
graphics.setColor(new Color(100, 100, 200));
// 100 100 200
List<Integer> positions = composition.getPositionsOfMeasureLines();
for (Integer x : positions) {
graphics.drawLine(x, 0, x, getHeight());
endX = x;
}
for (int y = SEMITONE_HEIGHT; y < getHeight(); y += SEMITONE_HEIGHT) {
graphics.drawLine(0, y, endX, y);
}
if (playLineColumn > 0 && playLineColumn < getWidth()) {
graphics.setColor(Color.RED);
graphics.drawLine(playLineColumn, 0, playLineColumn, getHeight());
}
graphics.setColor(save);
}
// MODIFIES: this
// EFFECTS: sets value of playLineColumn
public void setPlayLineColumn(int target) {
playLineColumn = target;
}
// MODIFIES: editor
// EFFECTS: makes the editor's scroller keep the playing line in the middle of the view.
public void followPlaying() {
int leftEndOfView = playLineColumn - (editor.WIDTH / 2);
editor.getScroller().getHorizontalScrollBar().setValue(leftEndOfView);
}
}
</code></pre>
<pre><code>package model;
import ui.sound.MidiSynth;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static ui.CompositionPanel.*;
// consider splitting graphical responsibilities into new class
// represents an entire composition, which is a collection of measures. The order of measures in the list is the order
// of measures in the composition.
public class Composition { // used to extend JPanel
private List<Measure> listOfMeasure;
//private int beatsPerMinute;
private int beatNum;
private int beatType;
private int barWidth; // implement later
public static int resolution = 4;
// the resolution is the number of ticks per quarter beat.
// REQUIRES: beatType is a power of 2
// EFFECTS: instantiates a new composition with numMeasures measures, beatNum beats of type beatType per measure.
public Composition(int numMeasures, int beatNum, int beatType) {
//super();
//setBackground(Color.black);
this.beatNum = beatNum;
this.beatType = beatType;
listOfMeasure = new ArrayList<Measure>();
for (int i = 0; i < numMeasures; i++) {
Measure tempMeasure = new Measure(beatNum, beatType, this, i + 1);
listOfMeasure.add(tempMeasure);
}
}
public void setResolution(int resolution) {
Composition.resolution = resolution;
}
// OBSOLETE
// REQUIRES: beat > 0
// EFFECTS: returns the measure which has the given global beat within it. If none have the given beat, return null.
public Measure getMeasureAtBeat(int beat) {
int beatCount = 0;
for (Measure measure: listOfMeasure) {
beatCount += measure.getBeatNumber();
if (beatCount >= beat) {
return measure;
}
}
return null;
}
// REQUIRES: tick > 0
// EFFECTS: returns the measure which has the given tick within it. If none, return null.
public Measure getMeasureAtTick(int tick) {
int tickCount = 0;
for (Measure m: listOfMeasure) {
tickCount += m.getNumTicks();
if (tickCount >= tick) {
return m;
}
}
return null;
}
// EFFECTS: adds a midisynth to all notes.
public void addMidiSynthToAll(MidiSynth midiSynth) {
for (Measure measure : listOfMeasure) {
measure.addMidiSynthToAll(midiSynth);
}
}
// EFFECTS: returns array containing the x screen coordinates of all measure lines in the composition.
public List<Integer> getPositionsOfMeasureLines() {
List<Integer> output = new ArrayList<Integer>();
output.add(0);
int tickCount = 0;
for (Measure m: listOfMeasure) {
tickCount += m.getNumTicks();
output.add(tickCount * tickWidth);
}
return output;
}
// EFFECTS: returns the global start tick of the given measure.
public int getGlobalStartOf(Measure measure) {
int output = 0;
for (Measure m: listOfMeasure) {
if (!m.equals(measure)) {
output += m.getNumTicks();
} else {
output++;
return output;
}
}
return 0; //this should throw an exception probably
}
// EFFECTS: returns the note at a given point in composition, if any.
public Note getNoteAtPoint(Point point) {
for (Measure measure : listOfMeasure) {
for (Note note : measure.getListOfNote()) {
if (note.contains(point)) {
return note;
}
}
}
return null;
}
// EFFECTS: returns list of notes at a given column in the composition.
public List<Note> getNotesAtColumn(int x) {
List<Note> notesAtColumn = new ArrayList<Note>();
for (Measure m: listOfMeasure) {
for (Note note : m.getListOfNote()) {
if (note.containsX(x)) {
notesAtColumn.add(note);
}
}
}
return notesAtColumn;
}
// EFFECTS: returns list of notes at a given tick in the composition.
public List<Note> getNotesAtTick(int tick) {
List<Note> notesAtTick = new ArrayList<>();
/*
for (Measure m: listOfMeasure) {
for (Note note : m.getListOfNote()) {
if (note.containsTick(tick)) {
notesAtTick.add(note);
}
}
}
*/
int ticksPerMeasure = listOfMeasure.get(0).getNumTicks();
int index = tick / ticksPerMeasure;
Measure measure = listOfMeasure.get(index);
for (Note note : measure.getListOfNote()) {
if (note.containsTick(tick)) {
notesAtTick.add(note);
}
}
return notesAtTick;
}
// REQUIRES: pos <= number of measures, beatType is a power of 2
// MODIFIES: this
// EFFECTS: adds n new measures to composition after the posth measure with beatNum beats of type beatType.
public void addMeasures(int n, int pos, int beatNum, int beatType) {
//int prevSize = listOfMeasure.size();
for (int i = 0; i < n; i++) {
Measure tempMeasure = new Measure(beatNum, beatType, this, pos + i + 1);
listOfMeasure.add(pos + i, tempMeasure);
countAndNotifyMeasures();
assert checkMeasureNums();
//.add adds the element at the index and shifts everything afterwards to the right by one.
}
}
// EFFECTS: checks the class invariant that the measures have correct measure numbers for their order in
// listOfMeasure
private boolean checkMeasureNums() {
int count = 0;
for (Measure measure : listOfMeasure) {
count++;
if (count != measure.getMeasureNumber()) {
return false;
}
}
return true;
}
// REQUIRES: there is a measure at every position specified.
// MODIFIES: this
// EFFECTS: removes the specified measures from composition, and makes sure note positions and measure numbers
// resulting are updated.
public void removeMeasures(List<Integer> listOfPos) {
// reverse list to remove last first
Collections.sort(listOfPos); // have to sort first
Collections.reverse(listOfPos);
for (Integer pos : listOfPos) {
int tickDiff = -1 * listOfMeasure.get(pos - 1).getNumTicks();
updateNotePositions(tickDiff, pos); // pos - 1 + 1
listOfMeasure.remove(pos - 1);
}
countAndNotifyMeasures();
}
// MODIFIES: this
// EFFECTS: for all measures from the one after the one to be removed until the end, adjust note starts by
// tickDiff.
private void updateNotePositions(int tickDiff, int index) {
for (int i = index; i < listOfMeasure.size(); i++) {
listOfMeasure.get(i).adjustNotes(tickDiff);
}
}
// EFFECTS: notifies all measures of their measure numbers.
private void countAndNotifyMeasures() {
int count = 0;
for (Measure measure: listOfMeasure) {
count++;
measure.setMeasureNumber(count);
}
}
// EFFECTS: returns the number of measures in the composition.
public int getNumMeasures() {
return listOfMeasure.size();
}
// EFFECTS: returns the total number of beats in the composition.
public int getNumBeats() {
int numBeats = 0;
for (Measure measure : listOfMeasure) {
numBeats = numBeats + measure.getBeatNumber();
}
return numBeats;
}
// EFFECTS: returns the total number of ticks in the composition.
public int getNumTicks() {
int numTicks = 0;
for (Measure measure : listOfMeasure) {
numTicks += measure.getNumTicks();
}
return numTicks;
}
// EFFECTS: returns the measure at pos
public Measure getMeasure(int pos) {
return listOfMeasure.get(pos - 1);
}
/*
public int getPosOfMeasure(Measure measure) {
return 0;
}
*/
// EFFECTS: return formatted content of composition
public String getContents() {
String tempString = "";
for (int i = 0; i < listOfMeasure.size(); i++) {
int n = i + 1;
tempString = tempString + "\n" + "Measure" + n + "\n" + listOfMeasure.get(i).getContents();
}
return tempString;
}
// REQUIRES: measure not null
// MODIFIES: this
// EFFECTS: add measure to end of composition
public void addMeasure(Measure measure) {
measure.assignToComposition(this);
listOfMeasure.add(measure);
measure.setMeasureNumber(listOfMeasure.size());
}
public int getBeatNum() {
return beatNum;
}
public int getBeatType() {
return beatType;
}
public List<Measure> getListOfMeasure() {
return listOfMeasure;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T00:56:39.783",
"Id": "485553",
"Score": "2",
"body": "Maybe you missed the text on the right side when asking: \"_Your question must contain code that is already working correctly, and **the relevant code sections must be embedded in the question**._\" Questions must [include the code to be reviewed](https://codereview.meta.stackexchange.com/a/3653/120114). Links to code hosted on third-party sites are permissible, but the most relevant excerpts must be embedded in the question itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T02:40:57.333",
"Id": "485556",
"Score": "2",
"body": "@SᴀᴍOnᴇᴌᴀ noted and fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T12:37:06.560",
"Id": "485573",
"Score": "2",
"body": "This is a well asked question (now that it includes the code), but you may not get everything you want out of a code review. The Software Engineering site provides design reviews and that may give you more of what you are looking for, but make sure to read their [help center](https://softwareengineering.stackexchange.com/help/asking). first."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T00:22:22.690",
"Id": "247932",
"Score": "3",
"Tags": [
"java",
"swing",
"music"
],
"Title": "MIDI editor application"
}
|
247932
|
<p>We are given an array of intervals we need to merge all overlapping intervals and sort the resulting non-overlapping intervals. When they "touch" in a single point, intervals are <em>also</em> considered to be overlapping .</p>
<pre><code>class Span
{
public uint Start { get; }
public uint End { get; }
private Span(uint start, uint end)
{
Start = start;
End = end;
}
private static Span _default = new Span(0, 0);
// To avoid constructor throwing an exception
public static Span Create(uint start, uint end)
{
if (start > end) throw new ArgumentOutOfRangeException(nameof(start), "Begin cannot me more than end");
return new Span(start, end);
}
public bool IsOverlapped(Span other)
{
return Start <= other.End && End >= other.Start;
}
public Span Merge(Span other)
{
if (!IsOverlapped(other)) throw new ArgumentOutOfRangeException(nameof(other), "Spans must overlap");
return new Span(Math.Min(Start, other.Start), Math.Max(End, other.End));
}
public bool TryMerge(Span other, out Span mergedItem)
{
mergedItem = _default;
if (!IsOverlapped(other)) return false;
mergedItem = new Span(Math.Min(Start, other.Start), Math.Max(End, other.End));
return true;
}
}
// In reality this method will be in a different class where it belongs
class Util
{
public static Span[] Normalise(Span[] spans)
{
var results = new List<Span>();
foreach (var item in spans.OrderBy(x => x.Start))
{
var lastResultIndex = results.Count - 1;
if (lastResultIndex >= 0 && results[lastResultIndex].TryMerge(item, out Span mergedItem))
{
results[lastResultIndex] = mergedItem;
}
else
{
results.Add(item);
}
}
return results.ToArray();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I can't see the point in having the <code>Create</code> method here, there's no reason why a constructor can't throw an exception in C#. I'd just get rid of <code>Create</code> and move it all into the constructor (making it public).</p>\n<p>The name <code>IsOverlapped</code> sounds a bit odd to me. <code>Is</code> is present tense and <code>Overlapped</code> is past tense. Maybe something like <code>IsOverlapping</code> or even just <code>Overlaps</code>.</p>\n<p>You have a typo here: "Begin cannot me more than end". <code>me</code> should be <code>be</code>.</p>\n<p>If you have access to expression-bodied members, they can reduce noise IMO:</p>\n<pre><code>public bool Overlaps(Span other) => other != null && Start <= other.End && End >= other.Start;\n</code></pre>\n<p>You'll notice that I've also put a null check for <code>other</code> in there at the same time.</p>\n<p>You should rewrite <code>Merge</code> to call <code>TryMerge</code> internally:</p>\n<pre><code>public Span Merge(Span other) => \n TryMerge(other, out var mergedSpan)\n ? mergedSpan\n : throw new ArgumentOutOfRangeException(nameof(other), "Spans must overlap");\n</code></pre>\n<p>I really value conciseness and I'm happy with throw expressions so I like this kind of pattern. If you don't, this version would also be fine:</p>\n<pre><code>public Span Merge(Span other)\n{\n if (!TryMerge(other, out var mergedSpan))\n throw new ArgumentOutOfRangeException(nameof(other), "Spans must overlap");\n return mergedSpan;\n}\n</code></pre>\n<p>Note: there's no need to check for null here as we now do that in <code>Overlaps</code>.</p>\n<p>Your <code>Normalise</code> method looks good to me. It's a simple algorithm and easy to read.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T07:10:19.610",
"Id": "248023",
"ParentId": "247933",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "248023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T03:08:33.487",
"Id": "247933",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Merging and sorting overlapped intervals"
}
|
247933
|
<p>I'm working on a text-based tic-tac-toe game, mostly for fun and because I'm learning programming. I would appreciate any comments you could give me to improve it.</p>
<p><strong>Main structure</strong>:</p>
<p>Uses a Board class for all the game. It's initialized with an empty tic-tac-toe board implemented using numpy arrays. It has views to handle the rows, columns and diagonals directly. It also initializes some other variables (player token, current game turns, etc).</p>
<p>Most of the the functions are helpers to handle the different moves performed by the computer (completing triples, filling diagonal cases, etc). The game loop is performed by the <code>play</code> function, which calls the other two main functions: <code>computer_turn</code> and <code>user_turn</code>.</p>
<p><strong>Code</strong>:</p>
<pre><code>from itertools import cycle
from random import shuffle
import numpy as np
### TODO:
# - 2 player mode.
# - Choose player/cpu token.
class NoMove(Exception):
pass
class Board:
players = cycle('xo')
def __init__(self):
self.board = np.array([['', '', ''], ['', '', ''], ['', '', '']])
self.rows = [self.board[0], self.board[1], self.board[2]]
self.columns = [self.board[:, 0], self.board[:, 1], self.board[:, 2]]
# Top to bottom, left to right diagonal
self.diag0 = np.einsum('ii->i', self.board)
# To to bottom, right to left diagonal
self.diag1 = np.einsum('ii->i', np.fliplr(self.board))
self.diags = [self.diag0, self.diag1]
self.player = next(Board.players)
self.user_score = 0
self.computer_score = 0
self.turns = 0
def check_winner(self, player=None):
"""
player: The token to check
Checks if a row, column or diagonal is filled with 'player' token.
If no 'player' token is given, uses curren self.player token.
Returns True if condition is valid. False otherwise.
"""
if not player:
player = self.player
# Horizontal win
for i in range(3):
if np.sum(self.rows[i] == player) == 3:
print('Horizontal check')
return True
# Vertical win
for j in range(3):
if np.sum(self.columns[j] == player) == 3:
print('Vertical check')
return True
# Diagonal win
for d in range(2):
if np.sum(self.diags[d] == player) == 3:
print('Diagonal check')
return True
return False
def fill_next(self):
"""
Fills the next empty case with self.player token.
"""
for i in range(3):
for j in range(3):
if not self.board[i][j]:
self.board[i][j] = self.player
return None
def fill_corner(self):
"""
Chooses one corner randomly.
If it's empty, fills it with self.player token.
Raises NoMove exception if not possible for all corners.
"""
random_corners = list(range(4))
shuffle(random_corners)
for i in random_corners:
if i == 0 and not self.board[0][0]:
self.board[0][0] = self.player
break
elif i == 1 and not self.board[0][2]:
self.board[0][2] = self.player
break
elif i == 2 and not self.board[2][0]:
self.board[2][0] = self.player
break
elif i == 3 and not self.board[2][2]:
self.board[2][2] = self.player
break
else:
raise NoMove
def diagonal_free(self):
"""
If center case is free, will attempt to fill the diagonally opposed case
of a case already filled with self.player token.
Raises a NoMove exception if conditions aren't met.
"""
if not self.board[1][1]:
for d in range(2):
for filled, empty in [(0, 2), (2, 0)]:
if self.diags[d][filled] == self.player and \
not self.diags[d][empty]:
self.diags[d][empty] = self.player
return None
else:
raise NoMove
else:
raise NoMove
def complete_triple(self, target=None):
"""
target: A player token. If none is given, will use current
self.player token.
Scans rows, columns and diagonals for 2 occurrences of target token.
If 2 cases are filled with 'target', it will fill the remaining case
with target.
If no occurrences take place, raises NoMove exception.
"""
def try_fill(array3):
"""
array3: An array with 3 elements.
If two elements of the array are filled with 'target' token and
one is empty, fills the empty case with current self.player token.
Returns True if successful. False if not.
"""
if np.sum(array3 == target) == 2 and \
np.sum(array3 == '') == 1:
array3[array3 == ''] = self.player
return True
return False
if not target:
target = self.player
# Rows
for row in self.rows:
if try_fill(row):
return None
# Columns
for column in self.columns:
if try_fill(column):
return None
# Diagonals
for diagonal in self.diags:
if try_fill(diagonal):
return None
raise NoMove
def win_move(self):
"""
Searches for rows, columns and diagonals with 2 occurrences of
self.symbol and completes it to win.
If no occurrences take place, complete_triple raises NoMove exception.
"""
self.complete_triple()
return None
def avoid_losing(self):
"""
Searches for rows, columns and diagonals with 2 occurrences of
the adversary of self.player token.
Completes the empty case to avoid losing.
If no occurrences take place, raises NoMove exception.
"""
if self.player == 'x':
target = 'o'
else:
target = 'x'
self.complete_triple(target)
return None
def count_corners(self, target=None):
"""
Returns the number of corners occupied by the current
self.player token. (0 - 4)
"""
if not target:
target = self.player
return np.sum(self.board[[0, 0, -1, -1], [0, -1, 0, -1]] == target)
def defend_corner(self):
"""
Checks if the other player has filled one of the corners of the board.
Returns True or False.
"""
if self.player == 'x':
other_player = 'o'
else:
other_player = 'x'
return self.count_corners(other_player) >= 1
def scan_one(self, array3):
"""
array3: An array with 3 elements.
Scans if token self.token occupies one and only one token
in array3. All other cases must be empty.
Returns True if valid. If not, False.
"""
return np.sum(array3 == self.player) == 1 and \
np.sum(array3 == '') == 2
def fill_one(self, array3):
"""
array3: An array of 3 elements.
Fills the first empty case in array3 with self.player token.
Raise NoMove exception if not possible
"""
for i in range(3):
if not array3[i]:
array3[i] = self.player
return None
raise NoMove
def complete_second(self):
"""
Will scan rows, columns and diagonals (in that order)
with only one current player case filled and no cases filled
by the other player. It will then fill one of those cases.
Returns NoMove exception if no occurrence is possible.
"""
for i in range(3):
if self.scan_one(self.rows[i]):
self.fill_one(self.rows[i])
return None
for j in range(3):
if self.scan_one(self.columns[j]):
self.fill_one(self.columns[j])
return None
for diagonal in self.diags:
if self.scan_one(diagonal):
self.fill_one(diagonal)
return None
raise NoMove
def computer_turn(self):
"""
Attempts different moves.
If any move succeds, it returns None.
When a move fails, it raises a NoMove exception and
attempts the next move.
"""
self.turns +=1
if self.player == 'x':
other_player = 'o'
else:
other_player = 'x'
input('Computer turn... (Press any key to continue)')
# Starts by filling any of the corners.
if self.turns <= 2:
# If the other player started the game and filled
# any of the corners, fill the center case.
if self.turns == 2:
if self.defend_corner():
self.board[1][1] = self.player
return None
try:
self.fill_corner()
return None
except NoMove:
pass
# Attempts to win the game with a single move.
try:
self.win_move()
return None
except NoMove:
pass
# If the opponent is about to complete a triple, avoid it.
try:
self.avoid_losing()
return None
except NoMove:
pass
# Attempts filling the diagonally opposed case if
# the central case is empty.
try:
self.diagonal_free()
return None
except NoMove:
pass
# During mid game, attempts to continue filling corners.
# First verifies that some corners are already filled by the player
# or that the opponent hasn't filled the corners already so that
# it's a worthy move.
if (self.turns <= 4 and self.count_corners(other_player) != 2) or \
self.count_corners() >= 2:
try:
self.fill_corner()
return None
except NoMove:
pass
# If no other option, will complete any row/column/diagonal
# that has one player token and two empty cases.
try:
self.complete_second()
return None
except NoMove:
pass
# If no other possible options, fill any empty case.
self.fill_next()
return None
def get_index(self, text):
"""
Will prompt the player for a row or column index.
Returns an integer index between 0 - 2.
"""
index = 0
while True:
index = input("Choose a {} (0 - 2)\n".format(text))
try:
index = int(index)
except ValueError:
print('Please enter a number')
continue
if index > 2:
print('Invalid input. Possible values: 0 - 2')
else:
break
return index
def try_case(self, i, j):
"""
Will atempt filling the case[i][j].
Returns True on success. False otherwise.
"""
if not self.board[i][j]:
self.board[i][j] = self.player
return True
return False
def user_turn(self):
"""
Prompts the user for a row and a column index.
Verifies case isn't filled.
"""
self.turns += 1
print('Your turn')
while True:
i = self.get_index('row')
j = self.get_index('column')
if self.try_case(i, j):
break
else:
print('Case is filled. Choose another one!')
return None
def play(self):
"""
Game loop.
Starts with computer turn.
Alternates turns between player/computer.
Verifies if there is a winner.
Verifies if there is a draw.
Starts new game alternating from last player.
"""
current_player = self.player
print('Welcome!')
self.print_score()
input('New game?\n(Press any key to continue)')
print(self)
while True:
current_player = self.player
if current_player == 'x':
self.computer_turn()
print(self)
else:
self.user_turn()
print(self)
if self.check_winner():
if current_player == 'x':
self.computer_win()
else:
self.player_win()
self.print_score()
self.reset()
print('New game')
print(self)
# Loser starts next game
self.player = next(Board.players)
elif self.endgame():
self.print_score()
print("It's a draw!")
input('Press any key to continue...')
self.reset()
print('New game')
print(self)
self.player = next(Board.players)
else:
self.player = next(Board.players)
def endgame(self):
"""
Checks if 9 turns of the game have elapsed.
"""
return self.turns == 9
def reset(self):
"""
Empties all board cases and sets turns to 0.
"""
self.board.fill('')
self.turns = 0
def computer_win(self):
"""
Prints computer winning message.
Increments computer score by one.
"""
print('Computer won!')
input('Press enter to continue...')
self.computer_score += 1
def player_win(self):
"""
Prints player winning message.
Increases player score.
"""
print('You win!')
input('Press enter to continue...')
self.user_score += 1
def print_score(self):
"""
Prints score
"""
print('Current score is:\n Player\t: {}\n CPU\t: {}'
.format(self.user_score,self.computer_score))
def __str__(self):
"""
Game board pretty printing.
"""
dash = '---'
counter = 0
board_str = ''
for row in self.board:
board_str += '{: ^5s}|{: ^5s}|{: ^5s}\n'\
.format(row[0], row[1], row[2])
if counter < 2:
counter += 1
board_str += '{0: ^5s}+{0: ^5s}+{0: ^5s}\n'.format(dash)
return board_str
board = Board()
board.play()
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T18:50:29.630",
"Id": "485594",
"Score": "0",
"body": "I don't using numpy is really useful for your case. It made it harder for me to understand the code, since I am not familiar with it. Especially \"einsum\" confused me, made me look up, einsum in numpy, then Einstein notation on wikipedia and I was still confused.\nI think using plain Python would be more readable here and safe you from an extra dependency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:21:41.163",
"Id": "485600",
"Score": "1",
"body": "I thought the same at first. Initially, I implemented the board using nested lists. However, whenever I tested or modified the columns, rows or diagonals, I had to explicitly refer to the corresponding elements in the nested list using two indeces, which was cumbersome and prone to error. The advantage of using Numpy arrays is that I can refer to the elements of the board by grouping them in rows, columns and diagonals. The changes on this arrays reflect back on the original board, which offered more expressive functions and clearer code in the long run. Thank you for your comment."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T03:26:54.447",
"Id": "247934",
"Score": "4",
"Tags": [
"python",
"game",
"numpy",
"tic-tac-toe"
],
"Title": "Text-based tic-tac-toe game in Python"
}
|
247934
|
<p>This is a practice task from Automate the Boring Stuff with Python. I imagine many others have asked for their version of the solution to be checked, so I apologise beforehand for boring you yet again.</p>
<p>In brief, the task entails writing a code that carries out an experiment of checking if there is a streak of 6 'heads' or 'tails' in 100 coin tosses, then replicates it 10,000 times and gives a percentage of the success rate.</p>
<pre><code>import random
numberOfStreaks = 0
listOf100 = []
streak = 0
def toss():
flip = random.randint(0, 1)
if flip == 0:
return 'H'
else:
return 'T'
for experimentNumber in range(10000):
# Code that creates a list of 100 'heads' or 'tails' values.
for flipCoin in range(100):
listOf100.append(toss())
# Code that checks if there is a streak of 6 'heads' or 'tails' in a row.
for listItem in range(len(listOf100) - 1):
if listOf100[listItem] == listOf100[listItem + 1]:
streak += 1
if streak == 5:
numberOfStreaks += 1
streak = 0
break
else:
streak = 0
listOf100 = []
print('Chance of streak: %s%%' % (numberOfStreaks / 10000))
</code></pre>
<p>My question is, am I correct in setting the condition <code>if streak == 5</code>?</p>
<p>My reasoning is that there are 5 pairs to be checked for similarities, if the actual streak is to be 6, for example:<br />
<code>if listOf100[0] == listOf100[1]</code><br />
<code>if listOf100[1] == listOf100[2]</code><br />
<code>if listOf100[2] == listOf100[3]</code><br />
<code>if listOf100[3] == listOf100[4]</code><br />
<code>if listOf100[4] == listOf100[5]</code></p>
<p>So, if all 5 such pairs increase streak with 1, it means that there are 6 list items in a row that are either 'heads' or 'tails'.</p>
<p>Thank you!</p>
|
[] |
[
{
"body": "<p>You are correct.</p>\n<p>However, your code is not very pythonic and the number of trials you want to do is hardcoded causing you to change it in multiple places whenever you want to change it.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for flipCoin in range(100):\n listOf100.append(toss())\n</code></pre>\n<p>Can be replaced with a list comprehension.</p>\n<pre class=\"lang-py prettyprint-override\"><code>listOf100 = [toss() for _ in range(100)]\n</code></pre>\n<p>from there you could use a functional approach to the problem, thus making your script:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from functools import reduce\nimport random\n\nnumberOfStreaks = 0\ntrialCount = 1000\n\n\ndef toss():\n flip = random.randint(0, 1)\n if flip == 0:\n return 'H'\n else:\n return 'T'\n\n\ndef updateStreak(streakState, nextValue):\n currentStreak, currentMaxStreak, lastValue = streakState\n if nextValue == lastValue:\n return (currentStreak + 1, currentMaxStreak, nextValue)\n else:\n return (1, max(currentStreak, currentMaxStreak), nextValue)\n\n\nfor experiment in range(trialCount):\n l = [toss() for _ in range(100)]\n currentStreak, maxStreak, _ = reduce(updateStreak, l, (0, 0, ''))\n if max(currentStreak, maxStreak) >= 6:\n numberOfStreaks += 1\nprint('Chance of streak: %s%%' % (numberOfStreaks / trialCount))\n</code></pre>\n<p>Google 'funcitonal programming in python' to learn more about each of the new functions I've shown you</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:34:09.337",
"Id": "485636",
"Score": "0",
"body": "@AJNeufeld - My bad, it's now edited and tested so will run :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T13:46:27.487",
"Id": "247947",
"ParentId": "247936",
"Score": "1"
}
},
{
"body": "<p>After the many hints @AJNeufeld already gave you (PEP-8, conventions for naming, constants in UPPERCASE etc.), here is advice targeted on a different level.</p>\n<p>Programming in Python often benefits from the work of others; in other words, you do not have to reinvent the wheel. If you choose the right data format for your problem, very often there is either a built-in method or a module which you can import to do the work. This has several benefits:</p>\n<ul>\n<li>It's faster and/or much more optimized than freshly written code.</li>\n<li>While not important for each and every program, with fast code you can scale more easily.</li>\n<li>Re-used code has been debugged a lot of times before, by different people, so there is a high chance that it will work as expected (esp. with regards to corner cases).</li>\n<li>Your program becomes more compact, for better overview and maintainability.</li>\n</ul>\n\n<pre><code>import random\n\ndef main():\n # declare constants\n NUM_EXPERIMENTS = 10000\n SEQLEN = 100\n STREAKLEN = 6\n\n streaks = 0\n for _ in range(NUM_EXPERIMENTS):\n # create a random sequence of length SEQLEN\n # this IS the experiment of coin tosses\n seqlist = [random.choice('HT') for _ in range(SEQLEN)]\n\n # convert list to string for easier searching\n seq = ''.join(seqlist)\n\n # if a streak of H's or T's occurs, the experiment is positive...\n if seq.count('H'*STREAKLEN) > 0 or seq.count('T'*STREAKLEN) > 0:\n streaks += 1\n # ... and we can stop searching & continue with the next\n continue\n\n print('probability: {0:.2f} %'.format(100.0*streaks/NUM_EXPERIMENTS))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Remarks:</p>\n<ol>\n<li><p>As you already make use of the <code>random</code> module, why not check the other module functions to see if one of them can generate a random sequence of characters of length <code>seqlen</code> directly? <code>random.choice</code> does that.</p>\n</li>\n<li><p>The right data format: looking for subsequences lends itself to string comparison. Your random sequence is a list. The next line converts a <code>list</code> to a <code>string</code>. As the 2 values are characters already, and we want to search for substrings, having a method <code>string.count()</code> is very convenient. It counts the number of occurrences of a substring within a string.</p>\n</li>\n<li><p>Now we only need to check if a streak is found, increment the streak counter and continue with the next experiment.</p>\n</li>\n<li><p>To print the percentage, we have to multiply the division by 100.</p>\n</li>\n</ol>\n<p>What is gained? Using built-in functions is nearly always much faster than using an explicit loop, especially as Python is an interpreted language. Sometimes, choosing a different data format may offer you one of those built-in methods which would not be applicable with the original format.</p>\n<p>So converting from the original <code>list</code> to <code>string</code> in your code enables you to use the built-in <code>str.count()</code> method which takes care of scanning the sequence, keeping a count on the match length etc., all within an embedded loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:48:28.807",
"Id": "485604",
"Score": "1",
"body": "This is an alternate solution, but does not even superficially review the OP's code, and is therefore not a valid answer by the rules of this site, and is subject to deletion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:50:55.123",
"Id": "485605",
"Score": "1",
"body": "`seqlist` always has **exactly** 50 heads & 50 tails, which is not correct for a **random** sequence of 100 flips."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T21:31:19.747",
"Id": "485607",
"Score": "1",
"body": "@AJNeufeld: I can't really follow your first remark, as I've worked closely along OP's code in the sense of refactoring it. Pointing out alternative programming principles were meant as useful hints for a learner. Your second remark IMHO is fully valid and is an oversight on my side. My code will produce wrong results for sure. Shall I edit it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T00:48:44.900",
"Id": "485618",
"Score": "1",
"body": "\"Here is a different approach to your problem...\" doesn't describe why the OP's code needs a different approach. The OP is left to look at the two approaches and guess at the reasoning behind the differences. Yes, you described things that you did, and why you did them, but not what was wrong with what they did. Compare your answer with mine. (I'll leave you to figure out the differences, instead of spelling it out.). But yes, edit your answer, and actually add a REVIEW, and I'll retract my downvote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:47:02.093",
"Id": "485667",
"Score": "1",
"body": "Why are you still using Python 2?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:39:36.900",
"Id": "485813",
"Score": "0",
"body": "@Heap Overflow: was using it on a rarely used NB, updated now. IMHO there is no reason not to use Python 3.8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T22:42:58.543",
"Id": "485865",
"Score": "0",
"body": "Hmm, but then why does your answer still have remark 4?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T07:31:27.887",
"Id": "486007",
"Score": "0",
"body": "right, that might have been misleading, edited out."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:37:32.360",
"Id": "247955",
"ParentId": "247936",
"Score": "2"
}
},
{
"body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> "gives coding conventions for the Python code ... intended to improve the readability of code and make it consistent across the wide spectrum of Python code."</p>\n<p>Since a large majority of Python projects follow PEP-8 guideline, it behooves you to follow those conventions as much as possible (except when you shouldn't, as outlined in section 2 of the document).</p>\n<p>These conventions include:</p>\n<ul>\n<li>using <code>snake_case</code> for variable names, instead of <code>mixedCase</code>. Eg, <code>numberOfStreaks</code> should be named <code>number_of_streaks</code>.</li>\n<li>imports should be followed by a blank line</li>\n<li>functions should appear after import and before main code. Eg) <code>number_of_streaks = 0</code>, <code>list_of_100 = []</code>, and <code>streaks = 0</code> should appear after <code>def toss():</code></li>\n<li>the mainline code should be inside a "main-guard" (<code>if __name__ == '__main__':</code>) statement.</li>\n</ul>\n<h1>Correctness</h1>\n<h2>Task</h2>\n<s>\nI fear you have interpreted the practice task incorrectly, or at least, implemented it wrong.\n<p>The task is to check "if there is a streak of 6 'heads' or 'tails' in 100 coin tosses, not "how many" streaks occurred. It asks for a percentage success rate. If you had an unfair coin, with your code you may find several dozen streaks in each experiment, and well over 10,000 streaks in the course of the 10,000 experiments, which would lead to a "percentage success rate" that exceeds 100%, which is suspect.\n</s></p>\n<p>(Incorrect, but left in to support <a href=\"https://codereview.stackexchange.com/a/247988/100620\">Heap Overflow's answer</a>)</p>\n<h2>Math</h2>\n<p><code>print('Chance of streak: %s%%' % (numberOfStreaks / 10000))</code></p>\n<p>Simply dividing a count by the total possible does not yield a percentage; 95 / 100 = 0.95 ... you must multiply by 100 to compute the result as a percentage.</p>\n<h1>WET -vs- DRY and locality of reference.</h1>\n<p>Your code reads (roughly):</p>\n<pre><code>listOf100 = []\n\n# ...\n\nfor experiment ...:\n\n for flipCoin in range(100):\n listOf100.append(toss())\n\n ...\n\n listOf100 = []\n</code></pre>\n<p>You see the <code>listOf100 = []</code>? WET stands for "Write Everything Twice". In contrast, DRY stands for "Don't Repeat Yourself". In general, with less code, the code is easier to understand and maintain. If variables are defined near where they are used, the code is also easier to understand and maintain.</p>\n<p>Let's DRY this code up.</p>\n<pre><code># ...\n\nfor experiment ...:\n\n listOf100 = []\n for flipCoin in range(100):\n listOf100.append(toss())\n\n ...\n</code></pre>\n<p>Now, <code>listOf100 = []</code> exists only once, and it exists right before it is being used.</p>\n<p>Now, as demonstrated in the other two answers, you can replace the initialization and repeated <code>.append()</code> with a more concise list comprehension.</p>\n<h1>Magic Numbers</h1>\n<p>I see several numbers in the code: <code>10000</code>, <code>100</code>, <code>listOf100</code>, <code>1</code>, <code>5</code>, <code>0</code>. What do these numbers mean?</p>\n<p>If you wanted to change the number of experiments from <code>10000</code> to <code>20000</code> how many changes would you have to make? Two?</p>\n<p>If you wanted to changed the number of tosses per experiment from 100 to 200, how many changes do you have to make? Change a number once, and a variable name 6 times??? That seems awkward and unmaintainable. And wrong, because there is also the comment.</p>\n<p>Named constants go a long way to improving maintainability.</p>\n<pre><code>NUM_EXPERIMENTS = 10_000\n\n...\n\nfor experiementNumber in range(NUM_EXPERIMENTS):\n ...\n\nprint('Change of streak: %s%%' % (numberOfStreaks / NUM_EXPERIMENTS))\n</code></pre>\n<p>Finally, <code>5</code> is the length of the streak. No, wait, 6 is the length of the streak. Uh. It would be nice to have a <code>STREAK_LENGTH = 6</code> named constant, and then the algorithm could use <code>if streak == STREAK_LENGTH - 1:</code>, with perhaps a comment explaining the "why".</p>\n<h1>Unused variables</h1>\n<p>The variable created in this statement:</p>\n<pre><code>for experimentNumber in range(10000):\n</code></pre>\n<p>is never used anywhere. It only serves two purposes.</p>\n<ol>\n<li>to make a syntactically valid <code>for</code> statement.</li>\n<li>indicate this loop is executed once per experiment.</li>\n</ol>\n<p>The second reason is obsoleted by changing the magic number <code>10000</code> into the named constant <code>NUM_EXPERIMENTS</code>. By convention, <code>_</code> is used as the throw-away variable, used only to satisfy syntactical reasons. So this <code>for</code> statement could become:</p>\n<pre><code>for _ in range(NUM_EXPERIMENTS):\n</code></pre>\n<p>Ditto for the <code>for flipCoin in range(100):</code> statement; it could become (say):</p>\n<pre><code> for _ in range(COIN_TOSSES_PER_EXPERIMENT):\n</code></pre>\n<h1>Formatting numbers</h1>\n<p>Using the <code>%s</code> format code for a number is not a good habit to get into. It may produce ok results here; you are dividing by 10,000 so likely will get a number with only 4 decimal points. But if you were asked to perform a different number of experiments, such as 7, you could get a lot of digits after the decimal point.</p>\n<p>Using the format code <code>%.4f</code> produces four digits after the decimal point, regardless of the actual number of experiments.</p>\n<h1>Improved Code</h1>\n<p>Others have answered with advanced -- or at best, tricky, and at worst, confusing -- methods of detecting the streaks including:</p>\n<ul>\n<li>string concatenation and substring searching</li>\n<li>functional programming</li>\n<li>converting head/tail coin values into same/different values</li>\n</ul>\n<p>In the spirit of the <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a> tag, let's investigate a clearer way.</p>\n<p>You are currently testing <code>listOf100[listItem] == listOf100[listItem + 1]</code> to check if a coin face is the same as the next. The <code>[listItem + 1]</code> is the awkward part here, necessitating stopping our loop one element before the end of the list. Let's rethink this. Instead of comparing two coins at a time, how about examining only one coin at a time? Simply remember the whether the streak is currently heads or tails, and ask if the current coin matches that streak:</p>\n<pre><code> for coin_face in coin_tosses:\n if coin_face == current_streak_face:\n streak_length += 1\n</code></pre>\n<p>When we find a coin that doesn't match the current streak, we have to start the streak with one instance of the new face.</p>\n<pre><code> else:\n current_streak_face = coin_face\n streak_length = 1\n</code></pre>\n<p>Of course, we have to initialize our state variables. The first coin won't match any previous value, so we should start off with some value which is neither heads nor tails.</p>\n<pre><code> current_streak_face = None\n streak_length = 0\n</code></pre>\n<p>Using this, we can create a simple coin streak detector function:</p>\n<pre><code>def contains_a_streak(coin_tosses, minimum_length):\n\n current_streak_face = None\n streak_length = 0\n\n for coin_face in coin_tosses:\n if coin_face == current_streak_face:\n streak_length += 1\n else:\n current_streak_face = coin_face\n streak_length = 1\n\n if streak_length >= minimum_length:\n return True\n\n return False\n</code></pre>\n<p>Notice that since we are initialize the <code>streak_length</code> to <code>1</code> when we find a different coin face, and adding <code>1</code> when we find a matching face, our <code>streak_length</code> counter is actually the length of the streak, and not one less. No more 5 -vs- 6, confusion, which is a huge win for clarity.</p>\n<p>Actually, there is nothing about this detector that is specific to coin tosses. We could use it for dice rolls, win-loss streaks, and so on. Just need to change some variable names ... and change the initial value from <code>None</code> to a different sentinel, so it could even properly detect a streak of <code>None</code> values at the start of a sequence of values.</p>\n<pre><code>def contains_a_streak(iterable, minimum_length):\n\n current = object() # a unique value that can't possibly match this first\n streak_length = 0\n\n for value in iterable:\n if current == value:\n streak_length += 1\n else:\n current = value\n streak_length = 1\n\n if streak_length >= minimum_length:\n return True\n\n return False\n</code></pre>\n<p>Now, our code for one experiment could become:</p>\n<pre><code>def coin_toss_experiment(number_of_tosses, streak_length):\n\n tosses = []\n for _ in range(number_of_tosses):\n tosses.append(toss())\n\n return contains_a_streak(tosses, streak_length)\n</code></pre>\n<p>As noted elsewhere, the list initialization and repeated appending could be replaced with list comprehension:</p>\n<pre><code>def coin_toss_experiment(number_of_tosses, streak_length):\n\n tosses = [toss() for _ in range(number_of_tosses)]\n\n return contains_a_streak(tosses, streak_length)\n</code></pre>\n<p>(Actually, a generator expression might be even better, but since we're focusing at the <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a> level, we'll just note it in passing. When you're a bit more comfortable with Python, look up what it is and what it would do for you, and why you might want to use one.)</p>\n<p>We need to run multiple experiments to compute the streak success rate:</p>\n<pre><code>def repeated_coin_toss_experiment(num_experiments, num_tosses, streak_length):\n successes = 0\n for _ in range(num_experiments):\n if coin_toss_experiment():\n successes += 1\n\n print(f"Chance of streak: {successes/num_experiments*100:.2f}%")\n</code></pre>\n<p>Finally, we need to run our experiment:</p>\n<pre><code>if __name__ == '__main__':\n repeated_coin_toss_experiment(10_000, 100, 6)\n</code></pre>\n<p>If you want to change the number of tosses, you only have to change one number. If you want to change the number of experiments, again, you just have to change one number. Change the streak length? Well, you get the idea.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T23:20:53.740",
"Id": "485867",
"Score": "0",
"body": "A few comments: 1) \"Of course, we have to initialize our state variables\" - You don't need to initialize `streak_length` there [*]. 2) \"`object() [...] can't possibly match`\" - [It can](https://repl.it/repls/SereneVirtualExponent#main.py). 3) For `minimum_length=0` the result should always be `True`, but for an empty iterable you produce `False`. 4) Better do `100*successes/num_experiments` to get the most accurate result."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T00:39:12.367",
"Id": "247971",
"ParentId": "247936",
"Score": "7"
}
},
{
"body": "<p><code>numberOfStreaks</code> is a misleading variable name. You even managed to make @AJNeufeld <a href=\"https://codereview.stackexchange.com/a/247971/219610\">claim</a> that you're not checking <em>whether</em> a streak occurred but that you're <em>counting</em> the number of streaks (possibly <em>multiple</em> per experiment) and thus compute the wrong thing. But you stop at the first streak in each experiment, so you're doing the right thing. A better name would be <code>experiments_with_streak</code>, as that's what you're really counting.</p>\n<p>As AJNeufeld pointed out, you misrepresent the result, showing about 0.8% instead of about 80%. Now the 80% means that most experiments have streaks. Probably on average somewhere in the middle. So it's wasteful to compute 100 tosses if you actually don't use the last few dozen. Also, you don't always need to follow the letter of the task (though that is advantageous for clarity) as long as you get the right result. In this case, instead of 100 tosses of heads/tails, you could look at 99 tosses of same/different (as the coin before). It can make the code a bit simpler. Only 99 because the first coin doesn't have one before.</p>\n<p>Putting these observations into code (also incorporating some of AJNeufeld's points):</p>\n<pre><code>import random\n\nNUM_EXPERIMENTS = 10_000\n\nexperiments_with_streak = 0\n\nfor _ in range(NUM_EXPERIMENTS):\n streak = 0\n for _ in range(99):\n same = random.choice((True, False))\n streak = streak + 1 if same else 0\n if streak == 5:\n experiments_with_streak += 1\n break\n\nprint('Chance of streak: %.2f%%' % (100 * experiments_with_streak / NUM_EXPERIMENTS))\n</code></pre>\n<p>Finally let me have some fun with a <code>for</code>-loop-less solution that even allows me to use <code>statistics.mean</code> so I don't have to repeat the number of experiments:</p>\n<pre><code>from random import choices\nfrom statistics import mean\n\nchance = mean('s' * 5 in ''.join(choices('sd', k=99))\n for _ in range(10000))\n\nprint('Chance of streak: %.2f%%' % (100 * chance))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T12:53:49.140",
"Id": "247988",
"ParentId": "247936",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T07:01:57.187",
"Id": "247936",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge"
],
"Title": "Coin Flip Streaks - correct streak condition"
}
|
247936
|
<p>I have written a code that triggers my div with another menu. I do not know which one is better and should be used. Can I get some feedback?</p>
<p>First code in one function:</p>
<pre><code>function sidebar() {
var menu = document.querySelector('#sidebar-container');
var menuSmall = document.querySelector('#sidebar-container2');
var icon = document.getElementById('right');
menuSmall.style.display = "block";
menu.style.display = "none";
if(menu.style.display == "none") {
icon.onclick = function () {
menu.style.display = "block";
menuSmall.style.display = "none";
}
}
</code></pre>
<p>Second code with two functions but does the same work:</p>
<pre><code>function sidebar() {
var menu = document.querySelector('#sidebar-container');
var menuSmall = document.querySelector('#sidebar-container2');
menuSmall.style.display = "block";
menu.style.display = "none";
},
function openbar() {
var menu = document.querySelector('#sidebar-container');
var menuSmall = document.querySelector('#sidebar-container2');
menuSmall.style.display = "none";
menu.style.display = "block";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T10:20:01.457",
"Id": "485562",
"Score": "2",
"body": "Could you please take care of your indentation of code blocks and closing braces? This would enhance readability of your code a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:20:11.733",
"Id": "485583",
"Score": "0",
"body": "Welcome to Code Review! It would be helpful to know when the functions are called. Please [edit] your post to include relevant code that calls the functions. Include a [snippet](https://stackoverflow.blog/2014/09/16/introducing-runnable-javascript-css-and-html-code-snippets/) if you think it is appropriate."
}
] |
[
{
"body": "<p>If I had to choose between your 2 methods, I would go with the second method.</p>\n<p>You should always err on the side of readability and also the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single-responsibility Principle</a>.</p>\n<p>But if I were to suggest an alternative to your original code, I would propose the use of CSS classes.</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>function toggleMenu(selectedMenu) {\n // Grab the currently open menu\n var openMenu = document.querySelector('.js-menu-open');\n \n // Grab the menu you want to open\n var targetMenu = document.querySelector(selectedMenu);\n\n // Scenario 1: a menu is already open\n // Close the open menu.\n if(openMenu) {\n openMenu.classList.replace('js-menu-open', 'js-menu-closed');\n }\n \n // Secnario 2: if the menu you are trying to open isn't the currently open menu\n // Open the target menu.\n if(openMenu !== targetMenu) {\n targetMenu.classList.replace('js-menu-closed', 'js-menu-open');\n }\n \n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.js-menu-closed {\n display: none;\n}\n\n.js-menu-open {\n display: block;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"sidebar-container\" class=\"js-menu-closed\">\n Sidebar 1\n</div>\n\n<div id=\"sidebar-container2\" class=\"js-menu-closed\">\n Sidebar 2\n</div>\n\n<div id=\"sidebar-container3\" class=\"js-menu-closed\">\n Sidebar 3\n</div>\n\n<button onclick=\"toggleMenu('#sidebar-container')\">Toggle sidebar 1</button>\n<button onclick=\"toggleMenu('#sidebar-container2')\">Toggle Sidebar 2</button>\n<button onclick=\"toggleMenu('#sidebar-container3')\">Toggle sidebar 3</button></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This method essentially uses CSS classes as a kind of persistent state, which helps simplify your JS logic, and also reduces the repetition of your code (keeping it <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>) AND it is infinitely re-usable for as many menus as you'd like! :)</p>\n<p>Other pluses is that you can now choose to have any one of your menu's open by default, and apply more performant animations in CSS.</p>\n<p>Hope this helped.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T11:53:34.790",
"Id": "248084",
"ParentId": "247939",
"Score": "1"
}
},
{
"body": "<p>I think that is easier to write and understand the state change if you don't need to think about the edge cases.</p>\n<p>In the first case, you already start in the state that you want and only need to invert the both states. In the second, you just need to "turn off" every states and "turn on" the one that you want to.</p>\n<p>I think that is simplier if you think this way.</p>\n<h1>Two sidebars</h1>\n<p>I think that you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle\" rel=\"nofollow noreferrer\">DOMTokenList.toggle()</a>:</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>const sidebars = document.querySelectorAll('.sidebar');\nconst icon = document.getElementById('icon');\n\nconst toggle = el => el.classList.toggle('hidden');\n\nicon.addEventListener('click',() => sidebars.forEach(toggle));</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/* the display value of a div is block by default */\n.hidden {\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!-- you don't need to find which sidebar is open in your js -->\n<div class=\"sidebar\">first</div>\n<div class=\"sidebar hidden\">second</div>\n<span id=\"icon\">icon</span></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Docs:</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList\" rel=\"nofollow noreferrer\">DOMTokenList</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/classList\" rel=\"nofollow noreferrer\">Element.classList</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/forEach\" rel=\"nofollow noreferrer\">DOMTokenList.forEach()</a></li>\n</ul>\n<hr />\n<h1>More than two sidebars</h1>\n<p>Maybe toggle can't be useful in this case. However, I think that <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset\" rel=\"nofollow noreferrer\">datasets</a> might help</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>const sidebars = document.querySelectorAll('.sidebar');\nconst btns = document.querySelectorAll('.btn');\n\nconst getSidebar = btn => btn.dataset.sidebar;\n\nconst hide = el => el.classList.add('hidden');\n\nbtns.forEach(btn =>\n btn.addEventListener('click', () => {\n const target = document.getElementById(getSidebar(btn));\n sidebars.forEach(hide);\n target.classList.remove('hidden');\n })\n);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.hidden {\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"sidebar\" id=\"first\">sidebar 1</div>\n<div class=\"sidebar hidden\" id=\"second\">sidebar 2</div>\n<div class=\"sidebar hidden\" id=\"third\">sidebar 3</div>\n<button class=\"btn\" data-sidebar=\"first\">1</button>\n<button class=\"btn\" data-sidebar=\"second\">2</button>\n<button class=\"btn\" data-sidebar=\"third\">3</button></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<hr />\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T02:57:52.733",
"Id": "248118",
"ParentId": "247939",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T09:31:44.513",
"Id": "247939",
"Score": "5",
"Tags": [
"javascript"
],
"Title": "Simple javascript toggle div function"
}
|
247939
|
<p>I'm writing a method that writes the code for a loading routine.
Given an object from the database, I want to put its properties in the right control on a userform.
I have the list of the properties and I have the names of the controls.</p>
<p>For each property, I want my code to search in the controls' name and find the most similar.</p>
<p>It doesn't have to be perfect, it's just something to avoid to rewrite the code over and over for every userform of each project. If it can guess 75%-80% it's ok.</p>
<p>I wrote the code below. The idea is:</p>
<ul>
<li>Check the presence of each character in the original string in each of the words in the list. If we are able to find it add 1 point to the score else subtract 1 point.</li>
<li>Check if the position of the character is the same in both the words (+1/-1)</li>
<li>Check if the closest characters - left and right - are the same (both match +1, 1 match 0, 0 match -1)</li>
</ul>
<p>You can use the function as a worksheet one and you can see the scores in the immediate window.</p>
<p>The code does work. I mean, the results make sense.</p>
<p>For example:</p>
<p><strong>Original string</strong>: michele</p>
<p><strong>List to check</strong>: marta, elehcim, valerio, txtmichele, miche</p>
<p><strong>Most similar according to the code</strong>: miche</p>
<p>Is this the most similar?
How good developers approach this problem?</p>
<p>I'd like to have your opinion on the idea and if there is a better way to achieve the goal.
The code is a mess but it's just a draft, doesn't matter at the moment.</p>
<p>Thank you for your time!</p>
<pre><code>Public Function GetMostSimilar(toString As String, between As Variant) As String
Dim i As Long
Dim ch As String
Dim o As Long
Dim comparison As Variant
Dim positionScore As Double
Dim presenceScore As Double
Dim am As ArrayManipulation
Dim index As Long
Dim bestScore As Double
Dim bestComparison As String
Dim closeCharatersScore As Double
Dim score As Double
' range to array
between = between.value
Set am = New ArrayManipulation
' a low number
bestScore = -1000
For o = LBound(between) To UBound(between)
comparison = GetArrayOfCharacters(CStr(between(o, 1))) ' returns 1 based array
positionScore = 0
presenceScore = 0
closeCharatersScore = 0
' loop in characters
For i = 1 To Len(toString)
ch = Mid(toString, i, 1)
' array manipulation is an object to do stuff with arrays. In this case find the index of something in an array
index = am.FindIndex(comparison, ch, 0, , False)
' method that check for match in left and right characters of the current character. +- 0.5 for each character depending if match
closeCharatersScore = closeCharatersScore + GetCloseCharactersScore(CStr(between(o, 1)), index, toString, i)
If index = -1 Then
presenceScore = presenceScore - 1
positionScore = positionScore - 1
Else
presenceScore = presenceScore + 1
positionScore = positionScore + IIf(i = index, 1, -1)
comparison(index) = vbNullString
End If
Next i
score = positionScore + presenceScore + closeCharatersScore
Debug.Print between(o, 1) & ": " & score & "| POS: " & positionScore & " | Pres: " & presenceScore & " | Close: " & closeCharatersScore
If score > bestScore Then
bestScore = score
bestComparison = between(o, 1)
End If
Next o
GetMostSimilar = bestComparison
End Function
Private Function GetCloseCharactersScore(comparison As String, index As Long, toString As String, i As Long) As Double
Dim leftOriginal As String
Dim rightOriginal As String
Dim leftComparison As String
Dim rightComparison As String
On Error Resume Next
leftOriginal = Mid(toString, i - 1, 1)
rightOriginal = Mid(toString, i + 1, 1)
leftComparison = Mid(comparison, index - 1, 1)
rightComparison = Mid(comparison, index + 1, 1)
On Error GoTo 0
GetCloseCharactersScore = IIf(leftOriginal = leftComparison, 0.5, -0.5) + IIf(rightOriginal = rightComparison, 0.5, -0.5)
End Function
Private Function GetArrayOfCharacters(str As String) As Variant
Dim i As Long
ReDim temp(1 To Len(str)) As Variant
For i = 1 To Len(str)
temp(i) = Mid(str, i, 1)
Next i
GetArrayOfCharacters = temp
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T11:40:01.843",
"Id": "485567",
"Score": "3",
"body": "A nice algorithm for fuzzy string comparisons is called \"Levenshtein Distance\" - it counts the number of swaps and insertions required to convert one string to another. If you divide by the string length, then you can get a % similarity between 2 strings. It's pretty fast too - google it for more info or take a look [here](https://stackoverflow.com/a/4243652/6609896) for a VBA implementation (although the accepted answer isn't necessarily the fastest implementation - but try it and you can see if speed is a problem). Using a well known algorithm can help people understand your code more easily"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:24:21.593",
"Id": "485601",
"Score": "0",
"body": "What is `ArrayManipulation`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:48:24.880",
"Id": "485639",
"Score": "0",
"body": "@TinMan it is an object with various methods and functions to manipulate o work with arrays"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T08:51:23.070",
"Id": "485644",
"Score": "1",
"body": "It should be included in your post."
}
] |
[
{
"body": "<p>Very interesting post.</p>\n<h2>Naming Conventions</h2>\n<p>The success of your code is dependent on how the controls on the userform are named. Is <code>miche</code> the most similar? In my opinion no. Controls will generally, have a prefix of suffix to identify the control type. For this reason, when comparing a word to a list control control names, the control name that contains a complete match should be taken over a partial match. Along the same lines, Camel and Pascal case naming conventions dictate that a the control name capitalization may need to be altered. Why would you give precedence to <code>miche</code> over <code>Michele</code>?</p>\n<h2>Using Arrays for String Comparisons</h2>\n<p>Creating an array for comparison as you shorten the match is very inefficient. Using a variant array to store characters is itself inefficient. (<a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/data-type-summary\" rel=\"nofollow noreferrer\">See MSDN: Data type summary</a>) Consider that it takes 10 bytes + the string length to store a string and 16-22 bytes need to be reserved for each element on an array. So it takes 16 bytes of memory to store <code>michele</code> as a string and a minimum of 96 bytes as a variant array of characters.<br />\nWith all things being equal, you can not write a VBA function that will outperform a native VBA function that is written in C++. <code>Instr()</code>, <code>Instr$()</code>, <code>InstrB()</code>, <code>Mid()</code>, <code>Mid$()</code> and <code>MidB()</code> are insanely fast and will outperform anything you try to replace them with. The <code>Instr()</code> functions can also make text comparisons which will ignore the text case.</p>\n<p>There is a small performance benefit to using byte arrays but IMO it is not significant enough to merit extra work.</p>\n<h2>Use the Right Name for the Job</h2>\n<p>• toString As String: It is usually obvious how <code>Object.toString</code> is to be used. toString does not indicate its context. Consider <code>Match</code>\n• between As Variant: This is very confusing considering that you are considering characters between the start and end of a string. Consider <code>MatchList</code></p>\n<h2>Miscellaneous</h2>\n<blockquote>\n<pre><code>' range to array\nbetween = between.value\n</code></pre>\n</blockquote>\n<p>This throw an error in my test. I assume that it was added when the OP was preparing the code to post.</p>\n<h2>GetCloseCharactersScore()</h2>\n<p>Always handle obvious errors don't escape them. <code>Mid()</code> will throw an "Invalid procedure call or argument" if the <code>Index < 1</code>. <code>Mid()</code> will also return a vbNullString if the <code>Index > Length</code> which might cause a false positive (although I doubt it). You should handle</p>\n<pre><code>Private Function GetCloseCharactersScore(comparison As String, index As Long, toString As String, i As Long) As Double\n If index > 1 And i > 1 And index < Len(comparison) And index < Len(toString) Then\n Dim leftOriginal As String\n Dim rightOriginal As String\n Dim leftComparison As String\n Dim rightComparison As String\n \n leftOriginal = Mid(toString, i - 1, 1)\n rightOriginal = Mid(toString, i + 1, 1)\n leftComparison = Mid(comparison, index - 1, 1)\n rightComparison = Mid(comparison, index + 1, 1)\n \n GetCloseCharactersScore = IIf(leftOriginal = leftComparison, 0.5, -0.5) + IIf(rightOriginal = rightComparison, 0.5, -0.5)\n Else\n GetCloseCharactersScore = -0.5\n End If\nEnd Function\n</code></pre>\n<h2>Is There a Better Way?</h2>\n<p>Again, this will depend on your naming conventions. My version takes the number of letters in the match value (from right to left) found in the comparison / length of the match value * weighted value and minuses the number of unmatched letters * a different weighted value to determine the overall score. The comparison is done right to left because you will seldom see a match where the first characters were truncated, it will almost always be the last. The weighted values will probably need to be adjusted but I think the theory is sound.</p>\n<pre><code>Public Function ClosestMatch(Match As String, MatchList As Variant) As String\n Dim n As Long\n Dim Item As Variant\n Dim BestMatch As String\n Dim BestScore As Double\n Dim CurrentScore As Double\n \n For Each Item In MatchList\n CurrentScore = MatchScore(Match, Item)\n If CurrentScore > BestScore Or BestScore = 0 Then\n BestMatch = CurrentScore\n BestMatch = Item\n End If\n Next\n \n ClosestMatch = BestMatch\nEnd Function\n\nPublic Function MatchScore(ByVal Match As String, ByVal MatchItem As Variant) As Double\n Const FullMatchWeight As Long = 10\n Const UnmatchedCharacterWeight As Long = -1\n \n Dim n As Long\n Dim Score As Double\n \n For n = Len(Match) To 1 Step -1\n If InStr(1, MatchItem, Left(Match, n) > 0, vbTextCompare) Then\n Score = Len(Match) / n * FullMatchWeight\n Exit For\n End If\n Next\n \n Dim UnmatchedCharacterScore As Double\n UnmatchedCharacterScore = Abs(n - Len(MatchItem)) * UnmatchedCharacterWeight\n MatchScore = Score + UnmatchedCharacterScore\n \nEnd Function\n \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T01:49:27.520",
"Id": "248016",
"ParentId": "247941",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T10:20:48.900",
"Id": "247941",
"Score": "5",
"Tags": [
"strings",
"vba"
],
"Title": "Similarity between words"
}
|
247941
|
<p>I've got a working solution to the Rustlings from_into exercise (i.e. the code compiles and all the tests pass). The task required that I implemented the <code>From</code> trait for <code>struct Person</code>. I've highlighted the relevant section inline with comments below.</p>
<pre><code>// The From trait is used for value-to-value conversions.
// If From is implemented correctly for a type, the Into trait should work conversely.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html
#[derive(Debug)]
struct Person {
name: String,
age: usize,
}
// We implement the Default trait to use it as a fallback
// when the provided string is not convertible into a Person object
impl Default for Person {
fn default() -> Person {
Person {
name: String::from("John"),
age: 30,
}
}
}
// THE BELOW IMPLEMENTATION IS WHAT I'D LIKE INPUT ON
//
// Steps:
// 1. If the length of the provided string is 0, then return the default of Person
// 2. Split the given string on the commas present in it
// 3. Extract the first element from the split operation and use it as the name
// 4. If the name is empty, then return the default of Person
// 5. Extract the other element from the split operation and parse it into a `usize` as the age
// If while parsing the age, something goes wrong, then return the default of Person
// Otherwise, then return an instantiated Person object with the results
impl From<&str> for Person {
fn from(s: &str) -> Person {
let s_as_vec = s.split(",").collect::<Vec<&str>>();
let name = s_as_vec[0].to_string();
if name.is_empty() {
Person::default()
} else if s_as_vec.len() > 1 {
match s.splitn(2, ",").collect::<Vec<&str>>()[1].parse::<usize>() {
Ok(age) => Person {name, age},
Err(_) => Person::default()
}
} else {
Person::default()
}
}
}
// END OF WHAT I'D LIKE INPUT ON
fn main() {
// Use the `from` function
let p1 = Person::from("Mark,20");
// Since From is implemented for Person, we should be able to use Into
let p2: Person = "Gerald,70".into();
println!("{:?}", p1);
println!("{:?}", p2);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default() {
// Test that the default person is 30 year old John
let dp = Person::default();
assert_eq!(dp.name, "John");
assert_eq!(dp.age, 30);
}
#[test]
fn test_bad_convert() {
// Test that John is returned when bad string is provided
let p = Person::from("");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_good_convert() {
// Test that "Mark,20" works
let p = Person::from("Mark,20");
assert_eq!(p.name, "Mark");
assert_eq!(p.age, 20);
}
#[test]
fn test_bad_age() {
// Test that "Mark.twenty" will return the default person due to an error in parsing age
let p = Person::from("Mark,twenty");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_comma_and_age() {
let p: Person = Person::from("Mark");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_age() {
let p: Person = Person::from("Mark,");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name() {
let p: Person = Person::from(",1");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_age() {
let p: Person = Person::from(",");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
#[test]
fn test_missing_name_and_invalid_age() {
let p: Person = Person::from(",one");
assert_eq!(p.name, "John");
assert_eq!(p.age, 30);
}
}
</code></pre>
<p>My primary question is: <strong>how do I make this more idiomatic?</strong> The pair of <code>split[n]()</code> calls seems wrong, but I'm not sure how to handle the various ways it would panic if I don't have explicit length checks.</p>
|
[] |
[
{
"body": "<p>Congratulations on your Rustlings challenge. Your code seems fine and is easy to understand, however, as you said yourself, some parts of it don't seem idiomatic yet.</p>\n<p>However, before I begin this review, I would like to mention that I consider myself a Rust beginner with a lot more experience in other languages. Keep that in mind while you read this review (and feel free to disagree and comment!).</p>\n<h1>Use <code>clippy</code></h1>\n<p>While <a href=\"https://github.com/rust-lang/rust-clippy\" rel=\"noreferrer\"><code>clippy</code></a> cannot work miracles, it can warn you about some lints. For example, the patterns in <code>split</code> are single character literals and thus should be written as <code>','</code>, not <code>","</code>.</p>\n<h1>Reuse what you already have</h1>\n<p>The longest line in your code is the <code>match</code> on <code>parse</code>'s result:</p>\n<pre><code>// indentation removed for simplicity\nmatch s.splitn(2, ",").collect::<Vec<&str>>()[1].parse::<usize>()\n</code></pre>\n<p>However, we already have <code>s.split(...)</code>'s result at hand. We don't need to split it a second time:</p>\n<pre><code>match s_as_vec[1].parse::<usize>()\n</code></pre>\n<p>If your concerned about the <code>n</code> in <code>splitn</code> then use <code>splitn</code> in your binding for <code>s_as_vec</code>. Note that the turbofish <code>::<usize></code> isn't necessary, as <code>rustc</code> can infer its type by the use in <code>Person</code>.</p>\n<h1>Use if-let when applicable</h1>\n<p>Back to the explicit length check. Instead of</p>\n<pre><code>if s_as_vec.len() > 1\n</code></pre>\n<p>we can use <code>get(1)</code> and check whether the element exist via <code>if let</code>:</p>\n<pre><code>if let Some(age) = s_as_vec.get(1) {\n match age.parse() {\n Ok(age) => Person { name, age },\n Err(_) => Person::default\n }\n}\n</code></pre>\n<p>This also prevents us from accidentally changing one of the index locations, e.g.</p>\n<pre><code>if s_as_vec.len() > 2 {\n match s_as_vec[3].parse() { // whoops, wrong number here\n ...\n</code></pre>\n<h1>Defer possible heavy operations if possible</h1>\n<p>We don't need <code>name</code> to be a <code>String</code> unless we have a valid <code>age</code>. Therefore, we can have <code>let name = s_as_vec[0]</code> until we create the <code>Person</code>. This removes unnecessary allocations.</p>\n<h1>All remarks above applied</h1>\n<p>If we apply all remarks above, we end up with the following variant.</p>\n<pre><code>impl From<&str> for Person {\n fn from(s: &str) -> Person {\n let s_as_vec = s.splitn(2, ',').collect::<Vec<&str>>();\n let name = s_as_vec[0];\n\n if name.is_empty() {\n Person::default()\n } else if let Some(age) = s_as_vec.get(1) {\n match age.parse() {\n Ok(age) => Person {name, age},\n Err(_) => Person::default()\n }\n } else {\n Person::default()\n }\n }\n}\n</code></pre>\n<p>However, I personally would probably try to minimize the possible return paths and use a single <code>match</code> expression, but that's based on my Haskell experience:</p>\n<pre><code>impl From<&str> for Person {\n fn from(s: &str) -> Person {\n let parts = s.splitn(2, ',').collect::<Vec<&str>>();\n\n match &parts[..] {\n [name, age] if !name.is_empty() => age\n .parse()\n .map(|age| Person {\n name: name.to_string(),\n age,\n })\n .unwrap_or_default(),\n _ => Person::default(),\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T08:58:36.287",
"Id": "485794",
"Score": "0",
"body": "Thanks, that's a great answer! I'm also much more experienced with other languages, but primarily C and Python, which both have a different mental model from Rust. Having the more functional insight from your Haskell experience is very useful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T07:26:01.537",
"Id": "248024",
"ParentId": "247942",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "248024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T11:31:50.740",
"Id": "247942",
"Score": "7",
"Tags": [
"error-handling",
"rust"
],
"Title": "How can I make my error handling more idiomatic in Rustlings exercise \"from_into\"?"
}
|
247942
|
<p>Generally, the approach I've taken is to try calling <code>container.decode</code> from a decodable <code>enum</code> with its associated value returning the actual class.
Each time the call to <code>container.decode</code> throws a different class is tried, from the class with the bigger number of member vars to the one with the smaller number of member vars.</p>
<p>This is how the deserialization is performed:</p>
<pre><code>let rawAccount = try JSONDecoder().decode(RawAccount.self, from: data)
let account = rawAccount?.value
</code></pre>
<p>This is the decodable enum:</p>
<pre><code>/// Nimiq account returned by the server. The especific type is in the associated value.
enum RawAccount : Decodable {
case account(Account)
case vesting(VestingContract)
case htlc(HTLC)
var value: Any {
switch self {
case .account(let value):
return value
case .vesting(let value):
return value
case .htlc(let value):
return value
}
}
private enum CodingKeys: String, CodingKey {
case account, vestingContract, hashedTimeLockedContract
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = .htlc(try container.decode(HTLC.self))
} catch {
do {
self = .vesting(try container.decode(VestingContract.self))
} catch {
self = .account(try container.decode(Account.self))
}
}
}
}
</code></pre>
<p>These are the different classes that are returned in the associate value:</p>
<pre><code>/// Normal Nimiq account object returned by the server.
public class Account: Decodable {
/// Hex-encoded 20 byte address.
public var id: String
/// User friendly address (NQ-address).
public var address: String
/// Balance of the account (in smallest unit).
public var balance: Int
/// The account type associated with the account.
public var type: AccountType
}
/// Vesting contract object returned by the server.
public class VestingContract : Account {
/// Hex-encoded 20 byte address of the owner of the vesting contract.
public var owner: String
///User-friendly address (NQ-address) of the owner of the vesting contract.
public var ownerAddress: String
/// The block that the vesting contracted commenced.
public var vestingStart: Int
/// The number of blocks after which some part of the vested funds is released.
public var vestingStepBlocks: Int
/// The amount (in smallest unit) released every vestingStepBlocks blocks.
public var vestingStepAmount: Int
/// The total amount (in the smallest unit) that was provided at the contract creation.
public var vestingTotalAmount: Int
private enum CodingKeys: String, CodingKey {
case owner, ownerAddress, vestingStart, vestingStepBlocks, vestingStepAmount, vestingTotalAmount
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.owner = try container.decode(String.self, forKey: .owner)
self.ownerAddress = try container.decode(String.self, forKey: .ownerAddress)
self.vestingStart = try container.decode(Int.self, forKey: .vestingStart)
self.vestingStepBlocks = try container.decode(Int.self, forKey: .vestingStepBlocks)
self.vestingStepAmount = try container.decode(Int.self, forKey: .vestingStepAmount)
self.vestingTotalAmount = try container.decode(Int.self, forKey: .vestingTotalAmount)
try super.init(from: decoder)
}
}
/// Hashed Timelock Contract object returned by the server.
public class HTLC : Account {
/// Hex-encoded 20 byte address of the sender of the HTLC.
public var sender: String
/// User friendly address (NQ-address) of the sender of the HTLC.
public var senderAddress: String
/// Hex-encoded 20 byte address of the recipient of the HTLC.
public var recipient: String
/// User friendly address (NQ-address) of the recipient of the HTLC.
public var recipientAddress: String
/// Hex-encoded 32 byte hash root.
public var hashRoot: String
/// Hash algorithm.
public var hashAlgorithm: Int
/// Number of hashes this HTLC is split into.
public var hashCount: Int
/// Block after which the contract can only be used by the original sender to recover funds.
public var timeout: Int
/// The total amount (in smallest unit) that was provided at the contract creation.
public var totalAmount: Int
private enum CodingKeys: String, CodingKey {
case sender, senderAddress, recipient, recipientAddress, hashRoot, hashAlgorithm, hashCount, timeout, totalAmount
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.sender = try container.decode(String.self, forKey: .sender)
self.senderAddress = try container.decode(String.self, forKey: .senderAddress)
self.recipient = try container.decode(String.self, forKey: .recipient)
self.recipientAddress = try container.decode(String.self, forKey: .recipientAddress)
self.hashRoot = try container.decode(String.self, forKey: .hashRoot)
self.hashAlgorithm = try container.decode(Int.self, forKey: .hashAlgorithm)
self.hashCount = try container.decode(Int.self, forKey: .hashCount)
self.timeout = try container.decode(Int.self, forKey: .timeout)
self.totalAmount = try container.decode(Int.self, forKey: .totalAmount)
try super.init(from: decoder)
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The same question was <a href=\"https://www.reddit.com/r/swift/comments/ia7gj3/how_to_properly_decode_a_json_dictionary_into/g1of7fn/\" rel=\"nofollow noreferrer\">answered</a> on Reddit by <a href=\"https://www.reddit.com/user/Saladfork4\" rel=\"nofollow noreferrer\">u/Saladfork4</a></p>\n<p>Here is the original answer:</p>\n<p>Usually you'll have a "type" somewhere in the JSON that tells you how to decode a field with an inconsistent structure. In your case, it is probably <code>type: AccountType</code>?\nIn that case, you'll usually want to decode that key first and then decode the rest based on that. Here's an example:</p>\n<pre><code>struct RawAccount: Decodable {\n\n enum CodingKeys: CodingKey {\n case type\n }\n\n let type: AccountType\n\n let account: Account\n\n init(from decoder: Decoder) throws {\n let container = try decoder.container(keyedBy: CodingKeys.self)\n type = try container.decode(AccountType.self, forKey: .type)\n \n let accountContainer = try decoder.singleValueContainer()\n switch type {\n case .htlc:\n account = try accountContainer.decode(HTLC.self)\n case .vesting:\n account = try accountContainer.decode(VestingContract.self)\n default:\n account = try accountContainer.decode(Account.self)\n }\n }\n\n}\n\npublic enum AccountType: String, Codable {\n\n case htlc = "HTLC"\n\n case vesting = "Vesting"\n\n case account = "Account"\n\n}\n\n// Example\ndo {\n let rawAccount = try decoder.decode(RawAccount.self, from: data)\n print(rawAccount.account)\n} catch {\n print(error)\n}\n</code></pre>\n<p>That way, you don't have to exhaustively try decoding it as every type--and you won't end up with a really big pyramid of code as you add more account types.\nIf you prefer the enum with associated values instead of <code>let account: Account</code>, you can just add a field to RawAccount and use that instead after decoding within the switch.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:24:53.920",
"Id": "247990",
"ParentId": "247945",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T13:15:15.283",
"Id": "247945",
"Score": "5",
"Tags": [
"json",
"swift",
"serialization"
],
"Title": "How to properly decode a JSON dictionary into different Swift classes using Decodable and JSONDecoder?"
}
|
247945
|
<p>I am currently going through <a href="https://vulkan-tutorial.com/en/Drawing_a_triangle/Setup/Instance" rel="noreferrer">this</a> Vulkan tutorial.</p>
<p>An extra excercise was writing a function which checks if the hardware you are running on supports the extensions other libraries require (GLFW in this case).</p>
<p>All the code is here:</p>
<pre><code>#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <iostream>
#include <stdexcept>
#include <cstdlib>
#include <vector>
#include <unordered_set>
#include <functional>
const uint32_t WIDTH = 800;
const uint32_t HEIGHT = 600;
enum Verbosity : bool {
VERBOSE = true,
TERSE = false,
};
//todo: enumerate the available extensions, print them
// and check if the ones required by glfw are in that list
class HelloTriangleApplication {
public:
void run() {
initWindow();
initVulkan();
mainLoop();
cleanup();
}
private:
GLFWwindow* window;
VkInstance instance;
void initWindow() {
glfwInit();
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
window = glfwCreateWindow(WIDTH, HEIGHT, "vulkan",
nullptr, nullptr);
}
void initVulkan() {
createInstance();
}
void createInstance() {
VkApplicationInfo appInfo{};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Hello Triangle";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "No Engine";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo createInfo{};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.pApplicationInfo = &appInfo;
uint32_t glfwExtensionCount = 0;
const char ** glfwExtensions;
glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount);
try {
checkRequiredExtensions(std::vector<std::string>(glfwExtensions, glfwExtensions + glfwExtensionCount),
VERBOSE);
} catch (std::exception &e) {
throw;
}
createInfo.enabledExtensionCount = glfwExtensionCount;
createInfo.ppEnabledExtensionNames = glfwExtensions;
createInfo.enabledLayerCount = 0;
if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS) {
throw std::runtime_error("failed to create instance!");
}
}
void checkRequiredExtensions(std::vector<std::string> requiredExtensions, const Verbosity &&verbose) {
if (verbose) {
std::cerr << "Required extensions: ";
for (auto &extension: requiredExtensions)
std::cerr << extension << ", ";
std::cerr << '\n';
}
uint32_t extensionCount = 0;
vkEnumerateInstanceExtensionProperties(
nullptr, &extensionCount, nullptr);
std::vector<VkExtensionProperties> supportedExtensions(extensionCount);
vkEnumerateInstanceExtensionProperties(nullptr,
&extensionCount, supportedExtensions.data());
std::unordered_set<std::string> supportedExtensionNames;
std::transform(supportedExtensions.begin(), supportedExtensions.end(),
std::inserter(supportedExtensionNames, supportedExtensionNames.begin()),
[](const auto& extension) {
return extension.extensionName;
});
if (verbose) {
std::cerr << "Available extensions: ";
for (auto &extension: supportedExtensionNames) {
std::cerr << extension << ", ";
}
std::cerr << '\n';
}
if(std::any_of(requiredExtensions.begin(), requiredExtensions.end(),
[&](const auto& extension) {
return !supportedExtensionNames.contains(extension);
})) {
throw std::runtime_error("Hardware does not support the required Vulkan extensions");
}
if (verbose) {
std::cerr << "Hardware supports required extensions\n";
}
}
void mainLoop() {
while(!glfwWindowShouldClose(window)) {
glfwPollEvents();
}
}
void cleanup() {
vkDestroyInstance(instance, nullptr);
glfwDestroyWindow(window);
glfwTerminate();
}
};
int main() {
HelloTriangleApplication app;
try {
app.run();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
</code></pre>
<p>I'm specifically interested in the code I wrote in <code>void checkRequiredExtensions(std::vector<std::string> requiredExtensions, const Verbosity &&verbose)</code>.</p>
<p>Am I handling exceptions correctly? Have I chosen a good way of selecting the verbosity mode of the function?</p>
<p>I find graphics programs super hard to debug so like logging everything and want the best way to do this.</p>
<p>I'm also worried about runtime overhead (as those if conditions need to be evaluated multiple times). Is there a way to avoid this? Am I making any dumb mistakes?</p>
|
[] |
[
{
"body": "<h1>Write clear and concise error messages</h1>\n<p>You will notice that almost any program will not log anything when things are fine. That's desired, because you don't want to be distracted by information that is not useful. When things go wrong though, you want to get a message that explains exactly what went wrong, without overloading you with details that do not matter.</p>\n<p>So if all the required extensions are present, you should not log anything. If an extension is missing, you should log exactly which extension(s) you are missing. So what I would write is something like:</p>\n<pre><code>void checkRequiredExtensions(const std::vector<std::string> &requiredExtensions) {\n // Get list of supported extensions\n ...\n \n std::vector<std::string> missingExtensions;\n\n for (extension: requiredExtensions) {\n if (supportedExtensionNames.contains(extension)) {\n missingExtensions.push_back(extension);\n }\n }\n\n if (!missingExtensions.empty()) {\n std::cerr << "Missing required Vulkan extensions:\\n"\n\n for (auto extensions: missingExtensions) {\n std::cerr << "- " << extension << "\\n";\n }\n\n throw std::runtime_error("missing required Vulkan extensions");\n }\n}\n</code></pre>\n<p>Now I no longer have to manually compare the list of required extensions with available extensions to find out what is missing. It also avoids the need for a verbosity level.</p>\n<h1>When you catch an exception, do something useful or don't catch at all</h1>\n<p>The following code is not doing anything useful:</p>\n<pre><code>try {\n checkRequiredExtensions(...);\n} catch (std::exception &e) {\n throw;\n}\n</code></pre>\n<p>This is equivalent to not using <code>try...catch</code> at all. Also in <code>main()</code> you write:</p>\n<pre><code>try {\n app.run();\n} catch (const std::exception& e) {\n std::cerr << e.what() << std::endl;\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>Here what you are doing in the <code>catch</code>-block is almost identical to what would happen if you didn't catch the exception at all, since uncaught exceptions are printed and then the program is aborted with a non-zero exit code.</p>\n<h1>Avoid premature optimization</h1>\n<p>I would not create a <code>std::unordered_set</code> here, you should only have to check supported extensions once at the start of the program, so efficiency is much less important here than maintainability. So I would write:</p>\n<pre><code>uint32_t extensionCount = 0;\nvkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr);\n\nstd::vector<VkExtensionProperties> supportedExtensions(extensionCount);\nvkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, supportedExtensions.data());\n\nstd::vector<std::string> missingExtensions;\n\nfor (auto extension: supportedExtensions) {\n if (std::find(requiredExtensions.begin(), requiredExtensions.end(), extension.extensionName) == requiredExtensions.end()) {\n missingExtensions.push_back(extension.extensionName);\n }\n}\n</code></pre>\n<p>If you really feel performance is critical here, then I would still not create a <code>std::unordered_set</code>, but rather <code>std::sort()</code> <code>supportedExtensions</code>, and use <code>std::binary_search()</code> to do efficient lookups. This avoids creating yet another container. And if you can ensure <code>requiredExtensions</code> is also sorted, you can avoid <code>std::binary_search()</code> as well and just do a linear scan through both sorted vectors.</p>\n<h1>Consider writing <code>checkMissingExtensions()</code> instead</h1>\n<p>It would be a bit cleaner to write a function named <code>checkMissingExtensions()</code> that just returns a vector with the missing extensions. This way, the function does not have to throw exceptions or write error messages, this can then be done by the caller. This also gives the caller more flexibility; for example if you want to use a certain extension but have fall-back code if it isn't present, then you can also use this function without an error message being printed unconditionally.</p>\n<h1>Debugging Vulkan programs</h1>\n<p>While you are developing your Vulkan application, you should have <a href=\"https://vulkan-tutorial.com/Drawing_a_triangle/Setup/Validation_layers\" rel=\"noreferrer\">validation layers</a> enabled. These will provide you with error messages when you are using the API incorrectly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:08:41.893",
"Id": "485579",
"Score": "0",
"body": "Good point about validation layers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:31:21.767",
"Id": "485584",
"Score": "0",
"body": "Maps + hash have worked great for me for performance critical string vector searches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T22:11:15.543",
"Id": "485610",
"Score": "0",
"body": "@anki Me too. Loops were at least a couple of orders of magnitude faster, when I changed from directly searching strings to using hashes."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T15:45:27.920",
"Id": "247950",
"ParentId": "247948",
"Score": "6"
}
},
{
"body": "<p>The use of classes and its member functions seems wrong to me:</p>\n<ul>\n<li><p>Destructor should also clean up if your code throws. In case <code>initVulkan</code> throws, your <code>cleanup</code> will never be reached and you get a resource leak. Also, having a destructor makes sure that when <code>HelloTriangleApplication app</code> goes out of scope, i.e. when <code>main</code> ends, all resources are cleaned-up without <em>explicitly calling</em> any special function.</p>\n</li>\n<li><p>The public member function doing <em>everything</em> (construction, destruction, capture events) is bad design. It should do one thing.</p>\n</li>\n</ul>\n<hr>\n<p>Put <code>initWindow()</code> into the constructor of <code>HelloTriangleApplication</code>: <code>HelloTriangleApplication()</code>.</p>\n<p>Put <code>cleanup()</code> into the destructor of <code>HelloTriangleApplication</code>: <code>~HelloTriangleApplication()</code>.</p>\n<p>Put <code>initVulkan()</code> (which only calls <code>create_instance()</code>) and <code>mainLoop()</code> into a public function like <code>check_compat</code>.</p>\n<p>Delete <code>run()</code>.</p>\n<p>Make <code>checkRequiredExtensions</code> a non-member function. Since it doesn't access any <em>private members</em> of the Class, it shouldn't be a member function. Also this will let you write tests for it.</p>\n<hr>\n<p>Use const in cases like:</p>\n<pre><code>auto &extension : supportedExtensionNames\nstd::exception &e\n</code></pre>\n<hr>\n<p>Adding to the point about exception G Sliepen raised,</p>\n<blockquote>\n<p>When you catch an exception, do something useful or don't catch at all</p>\n</blockquote>\n<p>Add extra info to the exception if you need it later on and <em>then</em> throw it. See more details at</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/2360597/c-exceptions-questions-on-rethrow-of-original-exception\">https://stackoverflow.com/questions/2360597/c-exceptions-questions-on-rethrow-of-original-exception</a></li>\n</ul>\n<hr>\n<p>Use <code>std::cout</code> and <code>std::cerr</code> when need arises. Don't stream everything to <code>std::cerr</code>. One reason is to conveniently separate <code>stdout</code> and <code>stderr</code> later on if this program is run via command-line.</p>\n<p>Another reason is the use of <code>std::endl</code>. All errors should be visible in <code>stderr</code> right when they occur. So use <code>std::endl</code>. And this is not required in <code>std::cout</code> since those messages are not the ones you want to log.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:07:59.030",
"Id": "485578",
"Score": "0",
"body": "Your observations are sound, but that is part of the tutorial. See https://vulkan-tutorial.com/Drawing_a_triangle/Setup/Base_code#page_Resource-management"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:09:07.010",
"Id": "485581",
"Score": "0",
"body": "But the tutorial writer didn't seek review from me ;) OP's question reads like an open ended one to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:17:01.143",
"Id": "485582",
"Score": "0",
"body": "Added some more points."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:04:43.870",
"Id": "247952",
"ParentId": "247948",
"Score": "3"
}
},
{
"body": "<p>Here are some general comments and some things that may help you improve your program.</p>\n<h2>Consider whether this is the right API for you</h2>\n<p>Vulkan is a very powerful but very difficult and verbose API to use.</p>\n<blockquote>\n<p>I find graphics programs super hard to debug so like logging everything and want the best way to do this.</p>\n</blockquote>\n<p>If you find graphics programs super hard to debug, Vulkan is going to make your life even more difficult. Consider getting up to speed with something a little easier to master such as OpenGL.</p>\n<p>With that said, almost all of the code in the question is verbatim from the tutorial, so I will restrict my review solely to the <code>checkRequiredExtensions</code> call you created.</p>\n<h2>Pass by value for small parameters</h2>\n<p>The code currently declares the function like so:</p>\n<pre><code>void checkRequiredExtensions(std::vector<std::string> requiredExtensions, const Verbosity &&verbose);\n</code></pre>\n<p>The second argument does not need to be a move reference. Just pass it by value.</p>\n<pre><code>void checkRequiredExtensions(std::vector<std::string>& requiredExtensions, const Verbosity verbose);\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/questions/15673889/correct-usage-of-rvalue-references-as-parameters\">this question</a> for an more detailed explanation.</p>\n<h2>Consider the use of <code>std::copy</code></h2>\n<p>Printing the extensions is currently done like this:</p>\n<pre><code>for (auto &extension: requiredExtensions)\n std::cerr << extension << ", ";\nstd::cerr << '\\n';\n</code></pre>\n<p>That's not terrible (although I would use <code>const auto&</code> instead), but you might also consider using <code>std::copy</code> for this:</p>\n<pre><code>std::copy(requiredExtensions.begin(), requiredExtensions.end(), \n std::ostream_iterator<std::string>(std::cerr, ", "));\n</code></pre>\n<p>If you want to get fancy and omit the final <code>,</code>, see if your compiler and libraries support <a href=\"https://en.cppreference.com/w/cpp/experimental/ostream_joiner\" rel=\"nofollow noreferrer\"><code>std::experimental::ostream_joiner</code></a>.</p>\n<p>Also, note that you could print the required extensions directly using <code>copy</code>:</p>\n<pre><code>std::copy(glfwExtensions, &glfwExtensions[glfwExtensionCount],\n std::ostream_iterator<const char *>(std::cerr, ", "));\n</code></pre>\n<h2>Check for errors</h2>\n<p>The calls to <code>vkEnumerateInstanceExtensionProperties</code> can fail, so you should check for a return value of <code>VK_SUCCESS</code> at the very least.</p>\n<h2>Simplify by avoiding copies</h2>\n<p>The code gathers a vector of <code>VkExtensionProperties</code> but then copies it into an unordered set. There's not much point to that, since you could simply print directly from the vector:</p>\n<pre><code>std::cerr << "Available extensions: ";\nfor (auto &extension: supportedExtensions) {\n std::cerr << extension.extensionName << ", ";\n}\nstd::cerr << '\\n';\n</code></pre>\n<h2>Understand the API</h2>\n<p>The code to check for the presence of required extensions is not really required. The way Vulkan works is that the required extensions are enumerated explicitly:</p>\n<pre><code>createInfo.enabledExtensionCount = glfwExtensionCount;\ncreateInfo.ppEnabledExtensionNames = glfwExtensions;\n</code></pre>\n<p>When <code>vkCreateInstance</code> is called, it will return <code>VK_ERROR_EXTENSION_NOT_PRESENT</code> if any of the enumerated extensions are missing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:05:43.217",
"Id": "247953",
"ParentId": "247948",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "247950",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T13:58:24.840",
"Id": "247948",
"Score": "6",
"Tags": [
"c++",
"graphics"
],
"Title": "ad hoc logging in c++ projects"
}
|
247948
|
<p>I am writing wrapper classes in Java which override methods of an existing implementation, in order to handle an edge case. The full implementation is a bit more complex than needs to be posted here, so I've written a simplified class containing only the parts I'm requesting assistance on.</p>
<p><strong>Problem Summary</strong></p>
<p>I am extending two classes:</p>
<p>One class designed as an "enumeration" class, abstracting a directory on a filesystem which contains symbolic links to other directories. (Real world: "/sys/block".). It has two methods, a <code>scan()</code> method to generate the list of (linked) subdirectories, and a <code>getFirst()</code> to return the first element of the list.</p>
<p>The second class is an "entry" class, abstracting the pointed-to directory enumerated by the first class. It has two methods, a <code>getName()</code> method to return the directory's path as a string, and a <code>getNext()</code> method to iterate to the next element.</p>
<p><strong>Constraints</strong></p>
<ul>
<li>Compatibility with JDK 8 or earlier</li>
<li>Single-threaded use may be assumed</li>
<li>Constructors may be altered as required.</li>
<li>Must implement (at least) the two specified classes and the two methods on each.</li>
</ul>
<p><strong>Focus of review</strong></p>
<p>The <code>scan()</code> method is my struggle here. I think I may have overcomplicated the solution in two ways:</p>
<ul>
<li>The nested <code>try ... catch</code> blocks in the <code>scan()</code> method seem unusual. Am I missing a simpler way to handle this?</li>
<li>(UPDATE: Self-answered this second question, below.) The implemented pattern is obviously a singly linked list that I'm working around by passing around an <code>ArrayList</code> implementation. I can imagine the <code>DirEntry</code> class containing only its <code>Path</code> and a <code>DirEntry next</code> object, but attempts to generate such a list seem even more complex or less performant than the workaround I've created.</li>
</ul>
<pre><code>import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DeviceList {
/**
* Class representing a parent directory which contains symbolic links to other
* directories
*/
static class DirEnumerator {
private Path dirPath;
private List<DirEntry> entryList = Collections.emptyList();
public DirEnumerator(String path) {
dirPath = FileSystems.getDefault().getPath(path);
}
/**
* Scans the directory for entries
*
* @return The number of entries found
*/
public int scan() {
try (Stream<Path> paths = Files.walk(dirPath)) {
List<Path> linkedDirs = paths.filter(Files::isSymbolicLink).map(p -> {
try {
return Files.readSymbolicLink(p);
} catch (IOException e) {
return p;
}
}).collect(Collectors.toList());
this.entryList = new ArrayList<>();
for (int i = 0; i < linkedDirs.size(); i++) {
this.entryList.add(new DirEntry(entryList, linkedDirs.get(i), i));
}
return this.entryList.size();
} catch (IOException e) {
this.entryList = Collections.emptyList();
return 0;
}
}
/**
* Gets the first entry in the scanned list
*
* @return The first entry if it exists; null otherwise
*/
public DirEntry getFirst() {
return entryList.isEmpty() ? null : entryList.get(0);
}
}
/**
* Class representing a directory
*/
static class DirEntry {
private List<DirEntry> entryList;
private Path path;
private int index;
public DirEntry(List<DirEntry> entryList, Path path, int i) {
this.entryList = entryList;
this.path = path;
this.index = i;
}
/**
* Gets the path name of the directory entry
*
* @return a string representing the path
*/
public String getName() {
return this.path.toString();
}
/**
* Gets the next entry in the list
*
* @return the next entry if it exists; null otherwise
*/
public DirEntry getNext() {
int nextIndex = index + 1;
return nextIndex < entryList.size() ? entryList.get(nextIndex) : null;
}
}
public static void main(String[] args) {
// Test on any directory containing symbolic links to other directories
DirEnumerator de = new DirEnumerator("/sys/block");
int n = de.scan();
System.out.println("Found " + n + " directories.");
DirEntry e = de.getFirst();
while (e != null) {
System.out.println("Directory: " + e.getName());
e = e.getNext();
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:59:58.683",
"Id": "485585",
"Score": "0",
"body": "It seems like the getNext method should be a method of the Enumeration class, not the Entry class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T17:21:47.993",
"Id": "485586",
"Score": "0",
"body": "@GilbertLeBlanc I agree, but unfortunately those are the constraints I'm working under for the class I'm extending. I think I did figure out a way to do that list portion and may self-answer the second question momentarily. First question still valid."
}
] |
[
{
"body": "<p>I have figured out a simpler way to do the second question, building the Linked List by iterating backwards from the generated paths.</p>\n<pre><code> static class DirEnumerator {\n\n private Path dirPath;\n private DirEntry first = null;\n\n // ...\n\n public int scan() {\n try (Stream<Path> paths = Files.walk(dirPath)) {\n List<Path> linkedDirs = paths.filter(Files::isSymbolicLink).map(p -> {\n try {\n return Files.readSymbolicLink(p);\n } catch (IOException e) {\n return p;\n }\n }).collect(Collectors.toList());\n this.first = null;\n int i = linkedDirs.size();\n while (i-- > 0) {\n this.first = new DirEntry(linkedDirs.get(i), first);\n }\n return linkedDirs.size();\n } catch (IOException e) {\n this.first = null;\n return 0;\n }\n }\n\n // ...\n }\n\n static class DirEntry {\n private Path path;\n private DirEntry next;\n\n public DirEntry(Path path, DirEntry next) {\n this.path = path;\n this.next = next;\n }\n\n // ...\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T17:27:03.100",
"Id": "247958",
"ParentId": "247951",
"Score": "0"
}
},
{
"body": "<p>I think you are overkilling your task. Consider the following:</p>\n<pre><code>import java.io.IOException;\nimport java.nio.file.FileSystems;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\npublic class DirectoryEnumerator {\n\n private final Path rootPath;\n private final List<Path> paths = new ArrayList<>();\n \n public DirectoryEnumerator(String path) {\n this.rootPath = FileSystems.getDefault().getPath(path);\n }\n \n public int scan() throws IOException {\n try (Stream<Path> pathStream = Files.walk(rootPath)) {\n List<Path> linkedPaths = pathStream.map(p -> {\n try {\n return Files.readSymbolicLink(p);\n } catch (IOException ex) {\n return p;\n }\n }).collect(Collectors.toList());\n \n linkedPaths.forEach(path -> {\n paths.add(path); \n });\n \n return paths.size();\n } \n }\n \n public List<Path> getTraversedPaths() {\n return Collections.unmodifiableList(paths);\n }\n \n public static void main(String[] args) {\n DirectoryEnumerator de =\n new DirectoryEnumerator(\n "C:\\\\Users\\\\username\\\\Documents");\n \n try {\n System.out.println("Scanned: " + de.scan());\n de.getTraversedPaths().forEach(System.out::println);\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n }\n}\n</code></pre>\n<p>Essentially, all you do is providing a class with two methods:</p>\n<ol>\n<li>scanning the directory tree starting from some root directory,</li>\n<li>obtain the list of the <code>Path</code> objects as the result of the 1. method.</li>\n</ol>\n<p>Questions? Leave me a message, and I will see what I can do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T06:58:45.387",
"Id": "267850",
"ParentId": "247951",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T15:51:19.793",
"Id": "247951",
"Score": "3",
"Tags": [
"java",
"linked-list",
"file-system"
],
"Title": "Linked List implementation of FileSystem directories"
}
|
247951
|
<p><strong>BACKGROUND</strong></p>
<p>I have a function where i cache file from aws s3. I provide it the path on s3 and also the local path of where i want the cached file to live. Sometimes if the file does not exist on s3 it will return a 404 error. That makes sense but i want to handle it gracefully. What i want to do is if the file i am trying to cache does not exist I want my get_overview_stream function to return None.</p>
<p><strong>CODE</strong></p>
<pre><code>def get_overview_stream(*, environment, proxy_key):
s3_overview_file_path = f"s3://{FOO_TRACK_BUCKET}/{environment}"
overview_file = f"{proxy_key}.csv"
local_path = cache_directory(environment)
try:
cache.cache_file(s3_overview_file_path, local_path, overview_file)
overview_file_cache = local_path / f"{proxy_key}.csv"
return overview_file_cache.open("r")
except botocore.exceptions.ClientError as e:
if e.response["Error"]["Code"] == "404":
return None
else:
raise
</code></pre>
<p><strong>Attempted Solution Issue</strong></p>
<p>I am very new to python so i am not sure if this the best way to handle this exception and if there is a more cleaner way. If so i would love to hear feedback.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T17:57:24.133",
"Id": "485590",
"Score": "1",
"body": "Honestly, I've never used to libraries involved here, but I don't see anything wrong with this approach. The exception handling seems fine to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:05:55.613",
"Id": "485598",
"Score": "0",
"body": "The only thing I would change here is adding a docstring and type information. You could move the last 2 lines in the try block outside. raising a custom exception instead of returning the sentinel value None might also be an improvement, but that last point id a matter of taste /habit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:06:59.837",
"Id": "485599",
"Score": "0",
"body": "Also, always open a file with a context manager instead of a bare open()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T11:51:07.040",
"Id": "485802",
"Score": "0",
"body": "@MaartenFabré can you show example of what you mean by custom exception?"
}
] |
[
{
"body": "<p>I would suggest not opening the file in your function but instead returning the path or <code>None</code>, such that the caller can open the file using a <code>with</code> statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T03:51:42.453",
"Id": "248071",
"ParentId": "247954",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248071",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T16:31:44.680",
"Id": "247954",
"Score": "3",
"Tags": [
"python"
],
"Title": "Clean way to handle file not found exception"
}
|
247954
|
<p>Original post: <a href="https://codereview.stackexchange.com/questions/247856/sorting-algorithm-visualizer-in-c-and-sdl2">Sorting algorithm visualizer in C++ and SDL2</a> <br>
I followed the advice you gave me and improved my code. I also added two more sorting algorithms.
I'm mainly looking for code readability advice (Built on Windows with cmake and ninja)</p>
<h1>Demonstration</h1>
<p><img src="https://i.stack.imgur.com/i3n7g.gif" alt="Demonstration" />
<br>props to @Zeta for the demonstration</p>
<h1>main.cpp</h1>
<pre><code>#include "Engine.h"
#undef main
int main()
{
try
{
// If the max number is higher than the window width it draws nothing other than a black screen :^)
// Default draw method is line
// Default sorting algorithm is bubble sort
SortVis::Engine visualization(
{ 1024, 768 },
1024,
SortVis::Engine::SortAlgorithm::insertionSort,
SortVis::Engine::DrawMethod::point
);
visualization.run();
}
catch (std::runtime_error& error)
{
std::cerr << error.what() << "\n";
}
}
</code></pre>
<h1>Engine.h</h1>
<pre><code>#ifndef ENGINE_H
#define ENGINE_H
#include "Coord.h"
#include <SDL.h>
#include <vector>
#include <iostream>
namespace SortVis
{
class Engine
{
public:
enum class DrawMethod
{
line,
point
};
enum class SortAlgorithm
{
selectionSort,
insertionSort,
bubbleSort
};
// Random number generation
Engine() = delete;
Engine(Coord windowSize, int maxNumber);
Engine(Coord windowSize, int maxNumber, SortAlgorithm algorithm);
Engine(Coord windowSize, int maxNumber, SortAlgorithm algorithm, DrawMethod method);
Engine(Coord windowSize, int maxNumber, const char* windowTitle);
Engine(Coord windowSize, int maxNumber, const char* windowTitle, SortAlgorithm algorithm);
Engine(Coord windowSize, int maxNumber, const char* windowTitle, SortAlgorithm algorithm, DrawMethod method);
// Load from file
Engine(Coord windowSize, const char* pathToNumbersFile);
Engine(Coord windowSize, const char* pathToNumbersFile, SortAlgorithm algorithm);
Engine(Coord windowSize, const char* pathToNumbersFile, SortAlgorithm algorithm, DrawMethod method);
Engine(Coord windowSize, const char* pathToNumbersFile, const char* windowTitle);
Engine(Coord windowSize, const char* pathToNumbersFile, const char* windowTitle, SortAlgorithm algorithm);
Engine(Coord windowSize, const char* pathToNumbersFile, const char* windowTitle, SortAlgorithm algorithm, DrawMethod method);
~Engine();
void run();
private:
const Coord windowSize;
const SortAlgorithm selectedSortAlgorithm = SortAlgorithm::bubbleSort;
const DrawMethod selectedDrawMethod = DrawMethod::line;
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
std::vector<int> numbers = { };
int columnWidth = 0;
int maxValue = 0;
bool running = true;
void initWindow(Coord windowSize, const char* windowTitle);
void initRenderer();
void calculateNumbers();
void loadFile(const char* pathToNumbersFile);
void handleEvents();
void draw();
void drawSelection();
void drawColumns();
void drawPoints();
void step();
void stepBubbleSort();
void stepInsertionSort();
void stepSelectionSort();
std::vector<int> generateRandom(int maxNumber);
};
}
#endif // ENGINE_H
</code></pre>
<h1>Engine.cpp</h1>
<pre><code>#include "Engine.h"
#include <filesystem>
#include <fstream>
#include <random>
#include <utility>
#include <algorithm>
#include <numeric>
#include <string>
// --- CONSTRUCTORS --- (fml)
SortVis::Engine::Engine(Coord windowSize, int maxNumber)
: windowSize(windowSize), numbers(generateRandom(maxNumber))
{
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, "Sort visualizer");
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, int maxNumber, SortAlgorithm algorithm)
: windowSize(windowSize), numbers(generateRandom(maxNumber)), selectedSortAlgorithm(algorithm)
{
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, "Sort visualizer");
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, int maxNumber, SortAlgorithm algorithm, DrawMethod method)
: windowSize(windowSize), numbers(generateRandom(maxNumber)),
selectedSortAlgorithm(algorithm), selectedDrawMethod(method)
{
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, "Sort visualizer");
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, int maxNumber, const char* windowTitle)
: windowSize(windowSize), numbers(generateRandom(maxNumber))
{
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, windowTitle);
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, int maxNumber, const char* windowTitle, SortAlgorithm algorithm)
: windowSize(windowSize), numbers(generateRandom(maxNumber)), selectedSortAlgorithm(algorithm)
{
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, windowTitle);
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, int maxNumber, const char* windowTitle, SortAlgorithm algorithm, DrawMethod method)
: windowSize(windowSize), numbers(generateRandom(maxNumber)),
selectedSortAlgorithm(algorithm), selectedDrawMethod(method)
{
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, windowTitle);
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, const char* pathToNumbersFile)
: windowSize(windowSize)
{
if (!std::filesystem::exists(pathToNumbersFile))
{
throw std::runtime_error("That file does not exist. Make sure the path is correct.");
}
else
{
loadFile(pathToNumbersFile);
}
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, "Sort visualizer");
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, const char* pathToNumbersFile, SortAlgorithm algorithm)
: windowSize(windowSize), selectedSortAlgorithm(algorithm)
{
if (!std::filesystem::exists(pathToNumbersFile))
{
throw std::runtime_error("That file does not exist. Make sure the path is correct.");
}
else
{
loadFile(pathToNumbersFile);
}
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, "Sort visualizer");
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, const char* pathToNumbersFile, SortAlgorithm algorithm, DrawMethod method)
: windowSize(windowSize), selectedSortAlgorithm(algorithm), selectedDrawMethod(method)
{
if (!std::filesystem::exists(pathToNumbersFile))
{
throw std::runtime_error("That file does not exist. Make sure the path is correct.");
}
else
{
loadFile(pathToNumbersFile);
}
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, "Sort visualizer");
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, const char* pathToNumbersFile, const char* windowTitle)
: windowSize(windowSize)
{
if (!std::filesystem::exists(pathToNumbersFile))
{
throw std::runtime_error("That file does not exist. Make sure the path is correct.");
}
else
{
loadFile(pathToNumbersFile);
}
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, windowTitle);
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, const char* pathToNumbersFile, const char* windowTitle, SortAlgorithm algorithm)
: windowSize(windowSize), selectedSortAlgorithm(algorithm)
{
if (!std::filesystem::exists(pathToNumbersFile))
{
throw std::runtime_error("That file does not exist. Make sure the path is correct.");
}
else
{
loadFile(pathToNumbersFile);
}
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, windowTitle);
initRenderer();
}
SortVis::Engine::Engine(Coord windowSize, const char* pathToNumbersFile, const char* windowTitle, SortAlgorithm algorithm, DrawMethod method)
: windowSize(windowSize), selectedSortAlgorithm(algorithm), selectedDrawMethod(method)
{
if (!std::filesystem::exists(pathToNumbersFile))
{
throw std::runtime_error("That file does not exist. Make sure the path is correct.");
}
else
{
loadFile(pathToNumbersFile);
}
calculateNumbers();
if (SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
{
throw std::runtime_error("Could not initialize SDL");
}
initWindow(windowSize, windowTitle);
initRenderer();
}
// --- END OF CONSTRUCTORS ---
SortVis::Engine::~Engine()
{
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
}
void SortVis::Engine::run()
{
// Sets render draw color to black
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
while (running)
{
handleEvents();
if (!std::is_sorted(numbers.begin(), numbers.end()))
{
step();
}
draw();
}
}
void SortVis::Engine::step()
{
switch (selectedSortAlgorithm)
{
case SortAlgorithm::bubbleSort:
stepBubbleSort();
break;
case SortAlgorithm::insertionSort:
stepInsertionSort();
break;
case SortAlgorithm::selectionSort:
stepSelectionSort();
break;
default:
break;
}
}
void SortVis::Engine::stepBubbleSort()
{
static int i = 0;
static int size = numbers.size();
for (int j = 0; j < size - i - 1; ++j)
{
if (numbers[j] > numbers[j + 1])
{
std::swap(numbers[j], numbers[j + 1]);
}
}
++i;
}
void SortVis::Engine::stepInsertionSort()
{
static int i = 1;
for (int j = i; j > 0 && numbers[j - 1] > numbers[j]; --j)
{
std::swap(numbers[j - 1], numbers[j]);
}
++i;
}
void SortVis::Engine::stepSelectionSort()
{
static int i = 0;
std::swap(numbers[i], numbers[std::min_element(numbers.begin() + i, numbers.end()) - numbers.begin()]);
++i;
}
void SortVis::Engine::draw()
{
SDL_RenderClear(renderer);
drawSelection();
SDL_RenderPresent(renderer);
}
void SortVis::Engine::drawSelection()
{
switch (selectedDrawMethod)
{
case DrawMethod::line:
drawColumns();
break;
case DrawMethod::point:
drawPoints();
break;
default:
break;
}
}
void SortVis::Engine::drawColumns()
{
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
SDL_Rect column;
for (int i = numbers.size(); i > 0; --i)
{
column.x = (i-1) * columnWidth;
column.w = columnWidth;
column.h = (numbers[i - 1] * windowSize.Y) / maxValue;
column.y = windowSize.Y - column.h;
SDL_RenderFillRect(renderer, &column);
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
}
void SortVis::Engine::drawPoints()
{
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
// SDL_Point point;
for (int i = numbers.size(); i > 0; --i)
{
// point.x = i - 1;
// point.y = windowSize.Y - ((numbers[i - 1] * windowSize.Y) / maxValue);
SDL_RenderDrawPoint(renderer, i - 1, windowSize.Y - ((numbers[i - 1] * windowSize.Y) / maxValue));
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
}
void SortVis::Engine::handleEvents()
{
SDL_Event Event;
while (SDL_PollEvent(&Event))
{
switch (Event.type)
{
case SDL_QUIT:
running = false;
break;
default:
break;
}
}
}
std::vector<int> SortVis::Engine::generateRandom(int maxNumber)
{
std::mt19937 seed(std::random_device{}());
std::vector<int> num(maxNumber);
std::iota(num.begin(), num.end(), 0);
std::shuffle(num.begin(), num.end(), seed);
std::cout << "Generated random number sequence.\n";
return num;
}
void SortVis::Engine::calculateNumbers()
{
columnWidth = windowSize.X / numbers.size();
maxValue = *std::max_element(numbers.begin(), numbers.end());
}
void SortVis::Engine::loadFile(const char* pathToNumbersFile)
{
std::ifstream NumbersFile(pathToNumbersFile);
if (NumbersFile.is_open())
{
std::string Number;
while (std::getline(NumbersFile, Number))
{
numbers.push_back(std::stoi(Number));
}
}
else
{
throw std::runtime_error("Couldn't open numbers file.");
}
if (numbers.empty())
{
throw std::runtime_error("Numbers file is empty.");
}
std::cout << "Loaded numbers file.\n";
}
void SortVis::Engine::initWindow(Coord windowSize, const char* windowTitle)
{
window = SDL_CreateWindow(
windowTitle,
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
windowSize.X,
windowSize.Y,
SDL_WINDOW_SHOWN
);
if (window == nullptr)
{
throw std::runtime_error("Could not initialize SDL window");
}
}
void SortVis::Engine::initRenderer()
{
renderer = SDL_CreateRenderer(
window,
-1,
SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED
);
if (renderer == nullptr)
{
throw std::runtime_error("Could not initialize SDL renderer");
}
}
</code></pre>
<h1>Coord.h</h1>
<pre><code>#ifndef COORD_H
#define COORD_H
namespace SortVis
{
struct Coord
{
int X;
int Y;
};
}
#endif // COORD_H
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T17:23:57.753",
"Id": "485587",
"Score": "0",
"body": "To build this more easily you can find the github repo here: https://github.com/Nadpher/SortVisualization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T18:10:16.013",
"Id": "485591",
"Score": "0",
"body": "Keep in mind that if the output still looks the same, you can show the same demonstration that's already in your original post :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T18:16:11.543",
"Id": "485593",
"Score": "0",
"body": "True, thanks for the heads up!"
}
] |
[
{
"body": "<h1>Use <code>namespace SortVis {...}</code> in <code>Engine.cpp</code></h1>\n<p>You can avoid repeating the namespace in each function definition in <code>Engine.cpp</code> by wrapping all the code inside <code>namespace SortVis</code>, just like you did in <code>Engine.h</code>. It's also common to not indent the code inside a <code>namespace {...}</code> block that covers the whole file, to avoid code running off the right hand of the screen too often.</p>\n<h1>Too many constructors</h1>\n<p>You have 12 different constructors, that is a bit much. Also imagine that you might want to add another optional parameter in the future, then you double the number of constructors required. This is not maintainable in the long run. I see two ways to cut down the number of constructors required:</p>\n<ol>\n<li><p>Use default argument values, like so:</p>\n<pre><code>Engine(Coord windowSize, int maxNumber,\n const char *windowTitle = "Sort visualizer",\n SortAlgorithm algorithm = SortAlgorithm::bubbleSort,\n DrawMethod method = DrawMethod::line);\n</code></pre>\n<p>With this approach, you only need two constructors. It might be slightly more annoying to use if you only want to specify another <code>DrawMethod</code>, but it is a small price for much improved maintainablility.</p>\n</li>\n<li><p>Don't specify the input values, algorithm and drawing method in the constructor, allow these to be set by member functions, like so:</p>\n<pre><code>Engine(Coord windowSize, const char *windowTitle = "Sort visualizer");\nvoid generateNumbers(int maxNumber);\nvoid loadNumbers(const char *pathToNumbersFile);\nvoid setAlgorithm(SortAlgorithm algorithm);\nvoid setDrawMethod(DrawMethod method);\n</code></pre>\n</li>\n</ol>\n<p>In general, only do in the constructor what really needs to be done at construction time. Initializing SDL and opening a window is crucial to a working visualization engine, so that is good to do in the constructor.</p>\n<h1>Consider not generating/loading numbers in <code>class Engine</code></h1>\n<p>Instead of having <code>Engine</code> generate random numbers or load them from a file, you can simplify it by not doing that at all, but rather just allow it to use any vector that you give it. So for example:</p>\n<pre><code>void run(const std::vector<int> &input) {\n numbers = input;\n ...\n}\n</code></pre>\n<p>You can even consider passing it as non-const, and have <code>run()</code> modify the given input vector.</p>\n<h1>Consider splitting visualization from sorting</h1>\n<p>A big issue is that you have to split your sorting algorithms into steps, and have a <code>switch()</code> statement in <code>step()</code> to pick the right algorithm. You also need to enumerate the possible algorithms. Instead of doing that, consider making <code>Engine</code> just visualize a vector of numbers, and instead of <code>Engine</code> driving the steps of the algorithm, have an algorithm drive <code>Engine</code> to show the state of the vector at each step. You can do this by changing <code>Engine::draw()</code> to take a reference to a vector of numbers:</p>\n<pre><code>void Engine::draw(const std::vector<int> &numbers) {\n ...\n}\n</code></pre>\n<p>And a sorting algorithm can just become a single function:</p>\n<pre><code>void bubbleSort(std::vector<int> &numbers, Engine &visualization) {\n for (size_t i = 0; i < numbers.size() - 1; ++i) {\n for (size_t j = 0; j < numbers.size() - 1; ++j) {\n if (numbers[j] > numbers[j + 1])) {\n std::swap(numbers[j], numbers[j + 1]);\n }\n }\n\n visualization.draw(numbers);\n }\n}\n</code></pre>\n<p>And then your <code>main()</code> could look like so:</p>\n<pre><code>int main() {\n std::vector<int> numbers = {...}; // generate some vector here\n\n SortVis::Engine visualization({1024, 768});\n SortVis::bubbleSort(numbers, visualization);\n}\n</code></pre>\n<p>The benefits to this approach are that you separate concerns. The <code>Engine</code> now only has to visualize a vector (it probably should be renamed to something like <code>Visualizer</code>). You can easily add new sorting algorithms without having to change <code>Engine</code>.</p>\n<p>One issue with the above is that it no longer handles SDL events. You could do this in <code>draw()</code>, and have <code>draw()</code> return a <code>bool</code> indicating whether the algorithm should continue or not.</p>\n<h1>Check for errors after reading a file, not before</h1>\n<p>In <code>Engine::loadFile()</code>, you check whether the file is opened correctly, but you never check whether there was an error during reading. A possible way is:</p>\n<pre><code>std::ifstream NumbersFile(pathToNumbersFile);\n\nstd::string Number;\nwhile (std::getline(NumbersFile, Number) {\n numbers.push_back(std::stoi(Number));\n}\n\nif (!NumbersFile.eof()) {\n throw std::runtime_error("Error while reading numbers file.");\n}\n</code></pre>\n<p>Here we use the fact that the <code>eofbit</code> is only set if it succesfully reached the end of the file, it will not be set if the file failed to open or if an error occurred before reaching the end of the file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:34:11.890",
"Id": "247983",
"ParentId": "247956",
"Score": "2"
}
},
{
"body": "<p>The program is definitely improved from the earlier version. Nice job! Here are some things that may help you improve it further.</p>\n<h2>Don't Repeat Yourself (DRY)</h2>\n<p>There are eleven repetitions of the constructor, which seems a bit excessive to me, especially because the code is nearly identical. I would reduce those to exactly one:</p>\n<pre><code>Engine(\n Coord windowSize, \n std::vector<int>&& numbers, \n SortAlgorithm algorithm = SortAlgorithm::bubbleSort, \n DrawMethod method = DrawMethod::point,\n const char* windowTitle = "Sort visualizer"\n); \n</code></pre>\n<p>By providing a single constructor with default parameters, the repetitions are eliminated and flexibility is enhanced. Note also that the array of numbers is passed as an argument.</p>\n<h2>Reduce the size of the interface to only what is needed</h2>\n<p>These two functions are generic and don't need to be class members:</p>\n<pre><code>std::vector<int> SortVis::loadFile(std::istream& numberFile);\nstd::vector<int> SortVis::generateRandom(int maxNumber);\n</code></pre>\n<p>By reducing the size of the interface to the minimal needed, the class is smaller and easier to read, understand, test, use, maintain and adapt. Note also that the first argument takes a <code>std::istream&</code> instead of a filename. This allows for such handy things as loading from a socket or a stringstream.</p>\n<h2>Prefer to fail early</h2>\n<p>If the <code>SDL_InitSubSystem</code> call in the constructor fails, there's not much point to continuing. For that reason, the more time-consuming <code>calculateNumbers</code> call should probably come after rather than before.</p>\n<h2>Only set the color if you're going to draw something</h2>\n<p>The only places that <code>SDL_SetRenderDrawColor</code> should be used is just before something is actually drawn on the screen. For that reason, it can appear exactly twice in this code: once at the top of <code>drawSelection</code> and once at the top of <code>draw</code>.</p>\n<h2>Move work outside of loops where practical</h2>\n<p>Instead of recalculating all four portions of <code>column</code> every time through the loop, it's possible to simply change the ones that need to change:</p>\n<pre><code>SDL_Rect column{ 0, 0, columnWidth, 0 };\nfor (const auto n : numbers)\n{\n column.h = n * windowSize.Y / maxValue;\n column.y = windowSize.Y - column.h;\n SDL_RenderFillRect(renderer, &column);\n column.x += columnWidth;\n}\n</code></pre>\n<h2>Use objects instead of <code>switch</code>es</h2>\n<p>The code currently contains this:</p>\n<pre><code>void SortVis::Engine::step()\n{\n switch (selectedSortAlgorithm)\n {\n case SortAlgorithm::bubbleSort:\n stepBubbleSort();\n break;\n\n case SortAlgorithm::insertionSort:\n stepInsertionSort();\n break;\n\n case SortAlgorithm::selectionSort:\n stepSelectionSort();\n break;\n\n default:\n break;\n }\n}\n</code></pre>\n<p>This requires the evaluation of <code>selectedSortAlgorithm</code> every iteration. The better way to do this is to create a virtual base class that demonstrates the interface and then allow the user to create a derived class with any new kind of sort they like. Here's one way to do it:</p>\n<pre><code>using Collection = std::vector<int>;\nstruct Sorter {\n std::string_view name;\n virtual bool step(Collection &) = 0;\n Sorter(Sorter&) = delete;\n Sorter(std::string_view name) \n : name{name}\n {\n }\n virtual void reset(Collection& numbers) {\n a = original_a = 0;\n original_b = numbers.size();\n }\n virtual ~Sorter() = default;\n std::size_t a;\n std::size_t original_a; \n std::size_t original_b;\n};\n\nstruct BubbleSorter : public Sorter {\n BubbleSorter() : Sorter{"Bubble Sort"} { }\n bool step(Collection& numbers) {\n auto lag{original_a};\n for (auto it{lag + 1}; it < original_b; ++it, ++lag) {\n if (numbers[lag] > numbers[it]) {\n std::swap(numbers[lag], numbers[it]);\n } \n }\n return ++a != original_b;\n }\n};\n</code></pre>\n<p>Now for maximum flexibility, you can pass such an object to the <code>Engine</code> in its constructor:</p>\n<pre><code>Engine visualization{\n { 1024, 768 },\n generateRandom(1024),\n std::make_unique<BubbleSorter>()\n};\n</code></pre>\n<h2>Use a pointer to a member function</h2>\n<p>A similar thing can be done for the drawing method if you like, but it's a little trickier since it uses a pointer to a member function which has a syntax that can be difficult to get right. We might declare the variable within <code>Engine</code> like this:</p>\n<pre><code>void (Engine::*drawSelection)();\n</code></pre>\n<p>I've repurposed your <code>drawSelection</code> name here. Within the constructor we can use this:</p>\n<pre><code>drawSelection{method == DrawMethod::point ? &Engine::drawPoints : &Engine::drawColumns}\n</code></pre>\n<p>And finally to call it, we need to use the pointer-to-member access operator. Here it is in context:</p>\n<pre><code>void SortVis::Engine::draw() {\n // Sets render draw color to black\n SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);\n SDL_RenderClear(renderer);\n SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n (this->*(drawSelection))();\n SDL_RenderPresent(renderer);\n}\n</code></pre>\n<h2>Don't do work that isn't needed</h2>\n<p>Right now, the main loop in <code>run</code> is this:</p>\n<pre><code>while (running)\n{\n handleEvents();\n if (!std::is_sorted(numbers.begin(), numbers.end()))\n {\n step();\n }\n draw();\n}\n</code></pre>\n<p>It doesn't make much sense to me to make a call to <code>std::is_sorted</code> within a program that demonstrates sorting! It seemed to me that I'd want to close the program when it was done sorting and I modified the sorting routines to return <code>bool</code> with value of <code>false</code> only when it's finished running and the vector is sorted. So for that, the loop turns into this:</p>\n<pre><code>while (running) {\n handleEvents();\n running &= sorter->step(numbers);\n draw();\n}\n</code></pre>\n<h2>Consider adding features</h2>\n<p>I'd suggest that it might be nice to add some features. Here's what I did:</p>\n<pre><code>void SortVis::Engine::handleEvents() {\n SDL_Event Event;\n while (SDL_PollEvent(&Event)) {\n switch (Event.type) {\n case SDL_QUIT:\n running = false;\n break;\n case SDL_KEYDOWN:\n switch (Event.key.keysym.sym) {\n case SDLK_r:\n numbers = generateRandom(maxValue);\n sorter->reset(numbers);\n break;\n case SDLK_b:\n numbers = generateRandom(maxValue);\n sorter = std::move(std::make_unique<BubbleSorter>());\n sorter->reset(numbers);\n break;\n case SDLK_i:\n numbers = generateRandom(maxValue);\n sorter = std::move(std::make_unique<InsertionSorter>());\n sorter->reset(numbers);\n break;\n case SDLK_s:\n numbers = generateRandom(maxValue);\n sorter = std::move(std::make_unique<SelectionSorter>());\n sorter->reset(numbers);\n break;\n case SDLK_l:\n drawSelection = &Engine::drawColumns;\n break;\n case SDLK_p:\n drawSelection = &Engine::drawPoints;\n break;\n case SDLK_q:\n running = false;\n break;\n }\n\n default:\n break;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T15:07:53.440",
"Id": "485672",
"Score": "0",
"body": "I really have to thank you for the advice you've been giving me throughout my coding journey. Sometimes i think i'm already good, but people like you show me i still have a lot to learn and keep me on my toes. Sincerely thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T17:06:51.573",
"Id": "485683",
"Score": "2",
"body": "I find I often learn things (or re-learn) in reviewing other people's code as well, so thank you for posting an interesting question. The information flow is definitely not solely one way!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:29:40.690",
"Id": "247991",
"ParentId": "247956",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T17:19:50.630",
"Id": "247956",
"Score": "5",
"Tags": [
"c++",
"sorting",
"data-visualization",
"sdl"
],
"Title": "Sorting algorithm visualizer in C++ and SDL2 Improved"
}
|
247956
|
<p>In c there is the macro <code>assert</code> and while it works I don't picturality like it mainly because it has no good way for printing a string. As a result I attempted to create a better version of <code>assert</code> for c++. However, I over engineered it leaving me with something that slows compile times, and something that I would not use. How can I improve it?</p>
<p><code>assert.hh</code></p>
<pre><code>#ifndef ASSERT_HH
#define ASSERT_HH
#include <iostream>
#include <utility>
#include <tuple>
namespace turtle
{
/* these macros are needed because #__VA_ARGS__ will include the comma in the string
* for example: macro(...) __VA_ARGS__
* macro(a,b) -> expands to "a,b"
* instead of "a","b"
*/
#define TURTLE_FIRST_(a, ...) a
#define TURTLE_SECOND_(a, b, ...) b
#define TURTLE_FIRST(...) TURTLE_FIRST_(__VA_ARGS__,)
#define TURTLE_SECOND(...) TURTLE_SECOND_(__VA_ARGS__,)
#define TURTLE_EMPTY()
#define TURTLE_EVAL(...) TURTLE_EVAL1024(__VA_ARGS__)
#define TURTLE_EVAL1024(...) TURTLE_EVAL512(TURTLE_EVAL512(__VA_ARGS__))
#define TURTLE_EVAL512(...) TURTLE_EVAL256(TURTLE_EVAL256(__VA_ARGS__))
#define TURTLE_EVAL256(...) TURTLE_EVAL128(TURTLE_EVAL128(__VA_ARGS__))
#define TURTLE_EVAL128(...) TURTLE_EVAL64(TURTLE_EVAL64(__VA_ARGS__))
#define TURTLE_EVAL64(...) TURTLE_EVAL32(TURTLE_EVAL32(__VA_ARGS__))
#define TURTLE_EVAL32(...) TURTLE_EVAL16(TURTLE_EVAL16(__VA_ARGS__))
#define TURTLE_EVAL16(...) TURTLE_EVAL8(TURTLE_EVAL8(__VA_ARGS__))
#define TURTLE_EVAL8(...) TURTLE_EVAL4(TURTLE_EVAL4(__VA_ARGS__))
#define TURTLE_EVAL4(...) TURTLE_EVAL2(TURTLE_EVAL2(__VA_ARGS__))
#define TURTLE_EVAL2(...) TURTLE_EVAL1(TURTLE_EVAL1(__VA_ARGS__))
#define TURTLE_EVAL1(...) __VA_ARGS__
#define TURTLE_DEFER1(m) m TURTLE_EMPTY()
#define TURTLE_DEFER2(m) m TURTLE_EMPTY TURTLE_EMPTY()()
#define TURTLE_IS_PROBE(...) TURTLE_SECOND(__VA_ARGS__, 0)
#define TURTLE_PROBE() ~, 1
#define TURTLE_CAT(a, b) a ## b
#define TURTLE_NOT(x) TURTLE_IS_PROBE(TURTLE_CAT(TURTLE__NOT_, x))
#define TURTLE__NOT_0 TURTLE_PROBE()
#define TURTLE_BOOL(x) TURTLE_NOT(TURTLE_NOT(x))
#define TURTLE_IF_ELSE(condition) TURTLE__IF_ELSE(TURTLE_BOOL(condition))
#define TURTLE__IF_ELSE(condition) TURTLE_CAT(TURTLE__IF_, condition)
#define TURTLE__IF_1(...) __VA_ARGS__ TURTLE__IF_1_ELSE
#define TURTLE__IF_0(...) TURTLE__IF_0_ELSE
#define TURTLE__IF_1_ELSE(...)
#define TURTLE__IF_0_ELSE(...) __VA_ARGS__
#define TURTLE_COMMA ,
#define TURTLE_HAS_ARGS(...) TURTLE_BOOL(TURTLE_FIRST(TURTLE__END_OF_ARGUMENTS_ __VA_ARGS__)())
#define TURTLE__END_OF_ARGUMENTS_() 0
#define TURTLE_MAP(m, first, ...) \
m(first) \
TURTLE_IF_ELSE(TURTLE_HAS_ARGS(__VA_ARGS__))( \
TURTLE_COMMA TURTLE_DEFER2(TURTLE__MAP)()(m, __VA_ARGS__) \
)( \
/* Do nothing, just terminate */ \
)
#define TURTLE__MAP() TURTLE_MAP
#define TURTLE__STRINGIZE(x) TURTLE___STRINGIZE(x)
#define TURTLE___STRINGIZE(x) #x
#define TURTLE_STRINGIZE(x) __FILE__ " line " TURTLE__STRINGIZE(__LINE__) ": assertion {" #x
template<typename... Args, typename Text>
constexpr auto assert_basic(const std::tuple<Args...> &arg, const Text &text)
{
if constexpr (sizeof...(Args) == 1) {
if (!std::get<0>(arg)) {
std::cerr << text << "} failed\n";
return true;
}
} else {
if (!std::get<0>(arg)) {
std::cerr << text << "} failed -> "
<< std::get<1>(arg) << '\n';
return true;
}
}
return false;
}
template<std::size_t Index, typename Result, typename... Args>
constexpr auto assert_tuple_args_helper(const Result &result, const std::tuple<Args...> &tuple_args_basic)
{
if constexpr (Index >= sizeof...(Args)) {
return result;
} else if constexpr (Index + 1 >= sizeof...(Args) &&
std::is_convertible_v<std::tuple_element_t<Index, std::decay_t<decltype(tuple_args_basic)>>, int>) {
return assert_tuple_args_helper<Index + 1>(std::tuple_cat(result,
std::tuple<decltype(std::tuple{
std::get<Index>(tuple_args_basic)})>{
std::tuple{std::get<Index>(
tuple_args_basic)}}),
tuple_args_basic);
} else if constexpr (
std::is_convertible_v<std::tuple_element_t<Index, std::decay_t<decltype(tuple_args_basic)>>, int>
&&
std::is_convertible_v<std::tuple_element_t<Index + 1, std::decay_t<decltype(tuple_args_basic)>>, int>) {
return assert_tuple_args_helper<Index + 1>(
std::tuple_cat(result, std::tuple<decltype(std::tuple{std::get<Index>(tuple_args_basic)})>{
std::tuple{std::get<Index>(tuple_args_basic)}}), tuple_args_basic);
} else if constexpr (
std::is_convertible_v<std::tuple_element_t<Index, std::decay_t<decltype(tuple_args_basic)>>, int>
&& !std::is_convertible_v<std::tuple_element_t<
Index + 1, std::decay_t<decltype(tuple_args_basic)>>, int>) {
return assert_tuple_args_helper<Index + 2>(
std::tuple_cat(result, std::tuple<decltype(std::tuple{std::get<Index>(tuple_args_basic),
std::get<Index + 1>(
tuple_args_basic)})>
{std::tuple{std::get<Index>(tuple_args_basic),
std::get<Index + 1>(
tuple_args_basic)}}), tuple_args_basic);
}
}
template<std::size_t TupleIndex, typename Result, typename... Args>
constexpr auto assert_tuple_text_indices_helper(const Result& result, std::size_t old_index, const std::tuple<Args...>& tuple)
{
if constexpr (TupleIndex < std::tuple_size_v<std::decay_t<decltype(tuple)>>) {
std::size_t next_index = old_index + std::tuple_size_v<std::decay_t<decltype(std::get<TupleIndex>(tuple))>>;
return assert_tuple_text_indices_helper<TupleIndex+1>(std::tuple_cat(result, std::tuple{old_index}), next_index, tuple);
} else {
return result;
}
}
template<typename Text, typename... Args>
constexpr auto assert(const Text& text, Args &&... args)
{
const auto &tuple_args = assert_tuple_args_helper<0>(std::tuple{}, std::tuple{args...});
constexpr auto tuple_text_indices = assert_tuple_text_indices_helper<0>(std::tuple{}, 0, decltype(tuple_args){});
[&]<std::size_t... Indices>(std::index_sequence<Indices...>) {
if ((assert_basic(std::get<Indices>(tuple_args), text[std::get<Indices>(tuple_text_indices)]) | ...)) {
std::exit(1);
}
}(std::make_index_sequence<std::tuple_size_v<std::decay_t<decltype(tuple_args)>>>{});
}
}
#define assert(...) turtle::assert(std::array{TURTLE_EVAL(TURTLE_MAP(TURTLE_STRINGIZE, __VA_ARGS__))}, __VA_ARGS__)
#endif /* ASSERT_HH */
</code></pre>
<p><code>main.cc</code></p>
<pre><code>#include "assert.hh"
/* testing */
int main()
{
int a, b, c, d;
std::cin >> a >> b >> c >> d;
assert(__LINE__ % 2 == 1, a < b, "a must be less than b", b < c, "b must be less than c", c < d, "c must be less than d");
assert(__LINE__ % 2 == 1, __FILE__[2] < 80);
}
</code></pre>
|
[] |
[
{
"body": "<p>When you're looking for performance bottlenecks, it may help to focus on the parts named <code>TURTLE</code>. ;) But I don't even think that's your main problem here.</p>\n<p>It seems like all you want to do is attach a message to the assertion, right?</p>\n<pre><code>#define myAssert(x, msg) assert((x) && msg)\n</code></pre>\n<p>This works as long as you're conscientious to always double the parentheses on invocations that need double parens:</p>\n<pre><code>myAssert(x < 2, "x is too large");\nmyAssert((foo<int,int> < 2), "foo<int,int> is too large");\n</code></pre>\n<p>If you want to eliminate the parens, I'd reduce that problem to <a href=\"https://stackoverflow.com/questions/24009797/how-can-i-retrieve-the-last-argument-of-a-c99-variadic-macro\">"How do I extract the last macro argument from a pack?"</a> One sensible answerer suggests that you unask <em>that</em> question and just put the message as the first argument:</p>\n<pre><code>#define myAssert(msg, ...) assert((__VA_ARGS__) && msg)\nmyAssert("x is too large", x < 2);\nmyAssert("foo<int,int> is too large", foo<int,int> < 2);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T21:17:32.033",
"Id": "485606",
"Score": "0",
"body": "So is this a good solution https://hatebin.com/pslchawusb ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T14:57:51.127",
"Id": "485671",
"Score": "0",
"body": "That certainly seems simpler! So yes, if it achieves your goal, it's good. Personally I'd still drop the `turtle::and_all` helper — I'd require the caller to write `assert(\"foo\", a && b && c)` instead of letting them write `assert(\"foo\", a, b, c)`. I don't see any big advantage in letting the caller replace `&&` with `,`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T18:54:48.567",
"Id": "247962",
"ParentId": "247957",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "247962",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T17:26:02.640",
"Id": "247957",
"Score": "1",
"Tags": [
"c++"
],
"Title": "assert function"
}
|
247957
|
<p>I am trying to transfer my c ++ experience to the Go area. I'm new to Go, so not sure if the implementation is correct. In any case, it looks very ugly compared to C ++ code. Is there a nicer solution? Both solutions are executable in playground and give same result.</p>
<p>c++ playground: <a href="https://code.sololearn.com/c67xbW2AEWW2/#cpp" rel="nofollow noreferrer">https://code.sololearn.com/c67xbW2AEWW2/#cpp</a></p>
<pre><code>#include <iostream>
using namespace std;
// Abstract class
class AbstractGenerator
{
public:
AbstractGenerator() {}
std::string generate(std::string some_internal_data)
{
_some_internal_data = some_internal_data;
return step1() + step2();
}
protected:
// some shared fuctions
std::string generationHelper1(std::string s) { return s + _some_internal_data + "123"; }
std::string generationHelper2(std::string s) { return s + _some_internal_data + "456"; }
// abstract fucntions
virtual std::string step1() = 0;
virtual std::string step2() = 0;
private:
std::string _some_internal_data;
};
// Implementation
class MyGenerator : public AbstractGenerator
{
public:
MyGenerator() {}
protected:
std::string step1() override { return generationHelper1("my step1") + generationHelper2("my step1"); }
std::string step2() override { return "my step2"; }
};
int main() {
MyGenerator my_gen;
AbstractGenerator* abstract_gen = &my_gen;
cout << abstract_gen->generate("data");
return 0;
}
</code></pre>
<p>Go playground: <a href="https://play.golang.org/p/e3iXfYar4YJ" rel="nofollow noreferrer">https://play.golang.org/p/e3iXfYar4YJ</a></p>
<pre><code>package main
import "fmt"
// some shared fuctions - interface
type ImplementationHelper interface {
generationHelper1(s string) string
generationHelper2(s string) string
}
// abstract fucntions - interface
type Implementation interface {
step1() string
step2() string
}
// Public main interface
type Generator interface {
Generate(s string) string
}
type AbstractGenerator struct {
someInternalData string
implementation Implementation
}
func NewAbstractGenerator(i Implementation) *AbstractGenerator {
g := new(AbstractGenerator)
g.implementation = i
return g
}
func (g *AbstractGenerator) Generate(s string) string {
g.someInternalData = s
return g.implementation.step1() + g.implementation.step2()
}
func (g *AbstractGenerator) generationHelper1(s string) string { return s + g.someInternalData + "123" }
func (g *AbstractGenerator) generationHelper2(s string) string { return s + g.someInternalData + "456" }
// Implementation of AbstractGenerator
type MyGenerator struct {
basic *AbstractGenerator
}
// MyGenerator constructor
func NewMyGenerator() *MyGenerator {
myGen := new(MyGenerator)
myGen.basic = NewAbstractGenerator(myGen)
return myGen
}
// Interface Generator
func (i *MyGenerator) Generate(s string) string {
return i.basic.Generate(s)
}
// Interface Implementation
func (i *MyGenerator) step1() string {
return i.basic.generationHelper1("my step1") + i.basic.generationHelper2("my step1")
}
func (i *MyGenerator) step2() string {
return "my step2"
}
func main() {
myGen := NewMyGenerator()
var abstractGen Generator
abstractGen = myGen
fmt.Println(abstractGen.Generate("data"))
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:25:55.487",
"Id": "485665",
"Score": "1",
"body": "yeah, this code sucks. Whats does it try to achieve ? Thinking about it, i just dont see the point in abstracting anything in *this example*. I would just have two concrete implementations, and if i need to communicate instances to a third party, let it declare a private interface to receive this or that implementation...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:33:56.220",
"Id": "485666",
"Score": "0",
"body": "the constructor `NewMyGenerator` is really funny. It creates a `MyGenerator` that is given to an `AbstractGenerator` that in turn is registered as a delegate to `MyGenerator`. That is not good. This complexity is unjustified."
}
] |
[
{
"body": "<p>This:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>g := new(AbstractGenerator)\ng.implementation = i\nreturn g\n</code></pre>\n<p>Can be more simply written as:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>return &AbstractGenerator{implementation: i}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:47:58.713",
"Id": "247965",
"ParentId": "247963",
"Score": "1"
}
},
{
"body": "<p>I dont understand OP code goals, it floats in thin air.</p>\n<p>But i would simply not abstract anything unless required.</p>\n<pre><code>package main\n\nimport "fmt"\n\ntype GeneratorA struct {\n}\n\nfunc (g GeneratorA) Generate(data string) string {\n return "generator A"\n}\n\ntype GeneratorB struct {\n}\n\nfunc (g GeneratorB) Generate(data string) string {\n return "generator B"\n}\n\nfunc main() {\n consumeGenerator(GeneratorA{})\n consumeGenerator(GeneratorB{})\n}\n\nfunc consumeGenerator(g interface{ Generate(string) string }) {\n fmt.Println(g.Generate("whatever"))\n}\n\n</code></pre>\n<p>anyways, reproducing OOP in a language that promotes composition is just not going to work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:38:05.223",
"Id": "247992",
"ParentId": "247963",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247992",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T19:28:24.020",
"Id": "247963",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"comparative-review",
"go"
],
"Title": "An example of transferring the C ++ class hierarchy to Golang. Is it done correctly?"
}
|
247963
|
<ul>
<li>Kotlin <code>1.3.+</code></li>
<li>RxJava <code>3.0.+</code></li>
<li>Kotest <code>4.1.+</code></li>
</ul>
<pre><code>// SingleValueCache.kt
package com.example
import io.reactivex.rxjava3.core.Single
import java.util.concurrent.Semaphore
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
abstract class SingleValueCache<V> {
protected abstract fun retrieve(): Single<V>
protected abstract fun validate(cached: V): Single<Boolean>
private inner class Cached(val version: Int, val value: V)
private val mutex: Semaphore = Semaphore(1)
private val cached: AtomicReference<Cached> = AtomicReference()
fun get(): Single<V> =
Single.defer { cached.get() ?.let(::existing) ?: initial() }.map { it.value }
private fun initial(): Single<Cached> = retrieve(1)
private fun existing(cached: Cached): Single<Cached> =
validate(cached.value).concatMap { valid ->
if (valid)
Single.just(cached)
else
retrieve(cached.version + 1)
}
private fun retrieve(version: Int): Single<Cached> = Single.defer {
val unlock: () -> Unit = lock()
val curr = cached.get()?.takeIf { it.version >= version }
when (curr) {
null ->
retrieve()
.map { v ->
Cached(version, v).also { fresh ->
cached.set(fresh)
unlock()
}
}
.doOnDispose { unlock() }
.doOnError { unlock() }
else ->
Single.just(curr).also { unlock() }
}
}
private fun lock(): () -> Unit {
mutex.acquire()
// i've observed some strange scenarios where the lock was released more than once,
// which is why the AtomicBoolean is being used here -
// to make absolutely sure that the lock is released *exactly* once
val locked = AtomicBoolean(true)
return {
val wasLocked = locked.getAndSet(false)
if (wasLocked)
mutex.release()
}
}
}
</code></pre>
<pre><code>// SingleValueCacheTest.kt
package com.example
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.shouldBe
import io.reactivex.rxjava3.core.Completable
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import java.util.concurrent.atomic.AtomicInteger
class SingleValueCacheTest : FreeSpec() {
companion object {
fun setup(): Pair<SingleValueCache<Int>, () -> Unit> {
val target = AtomicInteger(1)
val cache: SingleValueCache<Int> = object : SingleValueCache<Int>() {
val curr = AtomicInteger(0)
override fun retrieve(): Single<Int> = Single.fromCallable { curr.incrementAndGet() }
override fun validate(cached: Int): Single<Boolean> = Single.just(cached == target.get())
}
return Pair(cache, { target.incrementAndGet() ; Unit })
}
}
init {
"get" {
val (cache, invalidate) = setup()
val (par, trials) = (10 to 100)
val trial = Flowable
.fromCallable { cache.get() }
.repeat(par.toLong())
.parallel(par, 1)
.runOn(Schedulers.io())
.flatMap { it.toFlowable() }
.sequential()
val results = trial
.concatWith(Completable.fromCallable { invalidate() })
.repeat(trials.toLong())
.toList()
.blockingGet()
results shouldBe ((1..trials).flatMap { v -> (1..par).map { v } })
}
}
}
</code></pre>
<p>The above seems to work well, but I'm a bit concerned about correctly releasing the lock in edge cases. Specifically, is calling <code>unlock()</code> sufficient in the <code>doOnError</code> and <code>doOnDispose</code>? I haven't been able to find any detailed docs around the lifecycle and proper places for releasing resources - there are many <code>doOn*</code> variations and, personally, I find it confusing to understand how to use those callbacks correctly and effectively.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:07:35.513",
"Id": "247964",
"Score": "2",
"Tags": [
"kotlin",
"rx-java"
],
"Title": "How to implement a single-value cache in RxJava 3?"
}
|
247964
|
<p>This is a project that finds a specific anime (show) and checks to see if there is a new episode of it .</p>
<p>this is also the first time that i used <code>def</code> like this and wanted to ask how this project looks and how i could improve it ?</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.keys import Keys
import time
path = "c:/users/admin/appdata/local/programs/python/python38-32/chromedriver.exe"
driver = webdriver.Chrome(path)
chose = int(input("Press 1 for Black Clover \nPress 2 for Fire Force : "))
class BlackClover:
def __init__(self, title):
# lets the user chose which anime(show) he or she wants to watch.
self.title = title
# goes to the website that i want .
self.url = driver.get("https://www.gogoanime.movie/")
# i let it sleep for a few seconds before it goes to the next task
time.sleep(3)
# goes the english speaking anime (shows)
self.dub = driver.find_element_by_xpath('//*[@id="load_recent_release"]/div[1]/h2/a[2]')
self.dub.send_keys(Keys.RETURN)
# will be used later to filter out the episode number .
self.numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
self.divider = []
# the anime name (shows name).
self.clover = "Black Clover (TV) (Dub)"
def checker(self):
# will be used to retrieve the episode of the anime (show).
global episode
# will be used to go through the li element (HTML)
global n
n = 1
total = 0
# checks to see if the first li element is equal to "Black Clover (TV) (Dub)".
first_anime = WebDriverWait(driver, 3).until(ec.visibility_of_element_located(
(By.XPATH, '//*[@id="load_recent_release"]/div[2]/ul/li[1]/p[1]/a'))).get_attribute("innerHTML")
if first_anime == "Black Clover (TV) (Dub)":
print("first good")
driver.find_element_by_xpath('//*[@id="load_recent_release"]/div[2]/ul/li[1]/p[1]/a').send_keys(Keys.RETURN)
# if it is not equal to "Black Clover (TV) (Dub)" it will loop through the next li element until it finds it.
else:
while True:
# the next li element
name = WebDriverWait(driver,3).until(ec.visibility_of_element_located(
(By.XPATH, f'//*[@id="load_recent_release"]/div[2]/ul/li[{n}]/p[1]/a'))).get_attribute("innerHTML")
if name == self.clover:
print("good")
# checks which episode it's on and looks if it's a new episode
episode = WebDriverWait(driver,2).until(ec.visibility_of_element_located(
(By.XPATH, f'//*[@id="load_recent_release"]/div[2]/ul/li[{n}]/p[2]'))).get_attribute("innerHTML")
# retrieves the episode number
self.episodes()
break
if name != self.clover:
print("bad")
total += 1
n+= 1
if total == 20:
print("nothing")
break
</code></pre>
<p>EDIT : i let the user chose which anime(show) he or she wants to check by entering 1 or 2 in the input variable called <code>chose</code> at the top.</p>
<p>Thanks to @fabrizzio_gz .</p>
<pre><code> def episodes(self):
global joiner
# divider is a empty list
divider = self.divider
# copies the the variable "episode"
k= list(episode)
splitter = list(episode)
# gets the last three numbers in "k".
number = len(k)-3
last_number = k[number:]
last_number_2 = k[-1]
# checks to see if there are any numbers in the the variable "splitter" .
for i in splitter:
# if the i in splitter isn't a number it replaces it with a empty string.
if i not in self.numbers:
t = splitter.index(i)
splitter[t] = ""
print(splitter)
# if i is a number then it will add to the list with the variablename "divider" .
if i in self.numbers:
divider.append(i)
if divider == last_number and self.title == "Black Clover (TV) (Dub)":
# this joins all the numbers together in the list
joiner = ''.join(divider)
# checks to see if the episode is greater then 129
if int(joiner) > 129:
time.sleep(2)
# when the episode is greater then 129 it clicks the anime (show).
click = driver.find_element_by_xpath(f'//*[@id="load_recent_release"]/div[2]/ul/li[{n}]/p[1]/a')
click.send_keys(Keys.RETURN)
break
else :
# if the episode isn't greater then 129 then it returns the following .
return print("no new episode of : BLACK CLOVER ")
else:
joiner = ''.join(divider)
if int(joiner) >= 4:
time.sleep(2)
# when the episode is greater then 4 it clicks the anime (show).
click = driver.find_element_by_xpath(
f'//*[@id="load_recent_release"]/div[2]/ul/li[{n}]/p[1]/a')
click.send_keys(Keys.RETURN)
break
else:
# if the episode isn't greater then 4 then it returns the following .
return print("no new episode of : FIRE FORCE ")
if chose == 1:
main = BlackClover(title="Black Clover (TV) (Dub)")
main.checker()
if chose == 2:
main = BlackClover(title="Enen no Shouboutai: Ni no Shou (Dub)")
main.checker()
</code></pre>
|
[] |
[
{
"body": "<p>It's looking good and it's an interesting project. I'm not familiar with selenium, but since you create a Class for each anime show sharing most of the code, you could implement a parent anime show Class and inherit the methods to each child Class. Or maybe have each anime show as an instance of the same Class, just changing the anime show title or the necessary attributes.</p>\n<p>EDIT: You could use the same class for both anime shows as follows. Instead of two classes, you create a new class <code>AnimeShow</code> with the same attributes and methods. You add the parameter <code>anime_show</code> to the <code>__init__</code> function so that you can initialize anime shows with different titles . You would also need to change your code to use the new attribute <code>self.title</code> where necessary.</p>\n<pre><code>class AnimeShow():\n \n # Adding anime_show parameter\n def __init__(self, anime_show):\n # Same attributes as you had before\n # ...\n self.title = anime_show\n\n # Rest of class methods\n # ...\n\nif __name__ == '__main__':\n # Creating different anime shows with the same class\n clover = AnimeShow("Black Clover (TV) (Dub)")\n fire = AnimeShow("Enen no Shouboutai: Ni no Shou (Dub)")\n clover.checker()\n fire.checker()\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T22:21:39.323",
"Id": "485612",
"Score": "0",
"body": "i have a question about what you sad about \" you could implement a parent anime show Class and inherit the methods to each child Class\" . Do you mean that i should put other Classes inside the main Class that i started with ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T23:09:57.580",
"Id": "485614",
"Score": "0",
"body": "I edited my answer to show how to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T00:29:03.040",
"Id": "485617",
"Score": "0",
"body": "thanks for the tip . I have changed a few things in my code thanks to you ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T01:59:46.047",
"Id": "485620",
"Score": "0",
"body": "You are welcome. Good luck."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T21:05:10.177",
"Id": "247967",
"ParentId": "247966",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T20:53:02.900",
"Id": "247966",
"Score": "3",
"Tags": [
"python",
"selenium",
"webdriver",
"google-chrome"
],
"Title": "Project : My Anime Finder"
}
|
247966
|
<p>Instead of the obvious decision, parsing using given <code>std::io::Lines/std::io::Bytes</code> or crates like <code>nom</code>, I decided to explore writing my own specialized scanner that operates on <code>std::io::BufRead</code>.</p>
<p>I have two (self inflicted) problems.</p>
<p>Firstly, scanner must operate on bytes, utf8 validation given by rust <code>String</code> would really work just as well, but is "overkill", this is what <a href="https://www.x.org/docs/BDF/bdf.pdf" rel="nofollow noreferrer"><code>BDF 2.1</code></a> specification says about it:</p>
<blockquote>
<p>Character bitmap information will be distributed in an USASCII-encoded, human-readable form. Each file
is encoded in the printable characters (octal 40 through 176) of USASCII plus carriage return and linefeed.
Each file consists of a sequence of variable-length lines. Each line is terminated either by a carriage return
(octal 015) and linefeed (octal 012) or by just a linefeed.</p>
</blockquote>
<p>Secondly, I want to avoid as many "needless" allocations as possible, in other words, allow the user of the scanner to manage allocations. While this can be seen as premature optimization, I'd like if we looked at it as a zero-cost abstraction or all the power to the user or maybe even just a different code style from what is common in rust.</p>
<p>Criticism I'm looking for is specifically more focused on code readability and managing errors with constraints above than performance, although if anything I wrote here is a pessimization, I'd like to know about it aswell.</p>
<p>Note that I'm aware that "documentation" on Scanner methods is horrible, that is because its not documentation, just exactly my thoughts on them.</p>
<pre><code>use std::{
error, fmt,
io::{BufRead, ErrorKind},
};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
StdIo(std::io::Error),
UnexpectedByte { current: u8, expected: u8 },
Eof,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::StdIo(ref e) => e.fmt(f),
Error::UnexpectedByte { current, expected } => {
write!(f, "Read byte {:#0X} while expecting {:#0X}", current, expected)
},
Error::Eof => write!(f, "Reached end of file"),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match *self {
Error::StdIo(ref e) => Some(e),
Error::UnexpectedByte { .. } => None,
Error::Eof => None,
}
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::StdIo(e)
}
}
pub struct Scanner<R> {
r: R,
}
impl<R> Scanner<R>
where
R: BufRead,
{
/// Peek at a next byte
///
/// This is the root of all functionality provided in this scanner.
///
/// Given the fact that we will only perform very small reads (1 byte, yes), this might be whole
/// 1 boolean check (observation, not aim: https://doc.rust-lang.org/src/std/io/buffered.rs.html#265)
/// if BufReader buffer is empty, more efficient than Read::read(std::slice::from_mut(&mut byte)),
/// besides, we cannot even peek at buffer without fill_buf (guaranteed to be filled or eof'd),
/// or BufReader::buffer (not guaranteed to be filled)
fn peek(&mut self) -> Result<u8> {
loop {
return match self.r.fill_buf() {
Ok(bytes) => bytes.first().copied().ok_or(Error::Eof),
Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
Err(e) => Err(Error::StdIo(e)),
};
}
}
/// Could instead just be implemented as `self.r.read_exact(std::slice::from_mut(&mut byte))`?
fn advance(&mut self) -> Result<u8> {
let byte = self.peek()?;
self.r.consume(1);
Ok(byte)
}
/// Same as advance, but instead asserts that byte matches, does nothing otherwise,
/// useful for optional characters like `\r` and for enforcing structure, for example, BDF
/// format tokens are separated by spaces, `scanner.skip(b' ')?` ensures that parsing stops
/// if space is missing.
pub fn skip(&mut self, expected: u8) -> Result<()> {
let current = self.peek()?;
if current != expected {
Err(Error::UnexpectedByte { current, expected })
} else {
self.r.consume(1);
Ok(())
}
}
/// Unlike skip, operates on multiple bytes; naming inconsistency?
///
/// This is also, unlike skip, not optional, if byte doesn't exist somewhere in the middle,
/// reader is likely to be in unpredictable state.
pub fn consume(&mut self, bytes: &[u8]) -> Result<()> {
for &expected in bytes {
let current = self.advance()?;
if current != expected {
return Err(Error::UnexpectedByte { current, expected });
}
}
Ok(())
}
/// BDF keyword
///
/// Writes keyword into provided buffer until the end, returns length of it in a result.
///
/// It is a good idea to preallocate your buffer beforehand, most BDF fonts I looked at don't
/// have tokens longer than 64 bytes, I preallocate 128 just in case.
///
/// If length is 0, keyword is missing entirely or data is malformed (multiple spaces between
/// tokens and so on), but that's your job to deal with it.
pub fn keyword(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
let mut read = 0;
loop {
match self.peek()? {
// Keyword must be SCREAMCASE ASCII ONLY
byte @ 0x41 ..= 0x5A => {
buf.push(byte);
read += 1;
self.r.consume(1);
},
_ => break,
}
}
Ok(read)
}
// TODO: strings, bit arrays, arbitrary reads till eol...
}
impl<R> From<R> for Scanner<R>
where
R: BufRead,
{
fn from(r: R) -> Scanner<R> {
Scanner { r }
}
}
static FONT: &[u8] = b"STARTFONT 2.1\n?";
fn main() {
let mut scanner = Scanner::from(FONT);
let mut buf: Vec<u8> = Vec::with_capacity(128);
// forced keyword, reader must start on keyword or we leave
match scanner.keyword(&mut buf) {
Ok(0) => panic!("No keyword?"),
Ok(_) => {
print!("{}", std::str::from_utf8(&buf).unwrap());
buf.clear();
},
Err(e) => panic!("{:?}", e),
}
// forced skip of a single space
// this "parser" is anal about there being a single space for now, but this could be
// used as optional skip until all spaces are gone if that is required.
match scanner.skip(b' ') {
Ok(_) => {
print!("<SPACE>");
},
Err(e) => panic!("{:?}", e),
}
// BDF is either 2.1 or we leave.
match scanner.consume(b"2.1") {
Ok(_) => {
print!("2.1");
},
Err(e) => panic!("{:?}", e),
}
// optionally avoid legacy, errors like eof will be noticed in non-optional tokens
if let Ok(_) = scanner.skip(b'\r') {
print!("<CR>");
}
// forced skip of newline as we finished with this BDF item.
match scanner.skip(b'\n') {
Ok(_) => println!("<LF>"),
Err(e) => panic!("{:?}", e),
}
// begin parsing next BDF item, but fail (panics won't exist in real parser)
match scanner.keyword(&mut buf) {
Ok(0) => panic!("No keyword?"),
Ok(_) => {
print!("{}", std::str::from_utf8(&buf).unwrap());
buf.clear();
},
Err(e) => panic!("{:?}", e),
}
}
</code></pre>
<p>Result of this example:</p>
<pre><code>STARTFONT<SPACE>2.1<LF>
thread 'main' panicked at 'No keyword?', src/bin/main.rs:182:18
</code></pre>
<p>As you can see, this works as expected and I believe that code above is hard to improve, I want to be really sure about that, though.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T21:12:20.367",
"Id": "247969",
"Score": "2",
"Tags": [
"parsing",
"rust"
],
"Title": "Prototype of a scanner/tokenizer for Bitmap Distribution Format parser"
}
|
247969
|
<p>I wrote a discord bot that listens for links to the d20pfsrd rulebook in discord chat, checks if they are feats or magic, and then scrapes the page, formats it, and spits it back into chat as formatted text. The pages I'm checking are formulaic enough, so even though the cheerio selectors I'm using are probably fairly brittle, it seems to work in most cases. The text formatters are some ugly beasts though (though the logic is probably unique), and the axios calls could use some cleaning up as well.</p>
<p>My problem is as follows: I suspected a good 40% of the code can be refactored out of existence if I properly generalized it. My solution was to do something that could probably be described as an abuse of the spread operator:</p>
<pre><code>async function getPage(msg, url){
let message = "placeholder";
await axios.get(url).then( (response) => {
message = responder(...selectResponder(url), response);
}
).catch((error) => {
console.error(error.message);
});
sendMessage(message, msg);
}
</code></pre>
<p>A week later I'm now realizing I wrote the functions in a way that causes them to read backwards? Aesthetics aside, this is how it ends up working out:</p>
<pre><code>function selectResponder(siteUrl){
if (siteUrl.startsWith("https://www.d20pfsrd.com/feats/")){
return feats.featsConfig;
} else if (siteUrl.startsWith("https://www.d20pfsrd.com/magic/")){
return magic.magicConfig;
}
}
function responder(parser, formatter, messageFormatter, response){
const replyData = parser(response.data);
const formattedData = formatter(replyData);
return messageFormatter(formattedData);
}
</code></pre>
<p>The idea is that as much unique logic as I could separate out exists in magic.js and feats.js as possible. How can I clean this section up? The github repo is <a href="https://github.com/JasonMadeSomething/discord-pathfinder-searcher" rel="nofollow noreferrer">here</a> and I would love and feedback on the entire project. I did most of that because I thought it as weird to have a big if block here and duplicating the axios calls:</p>
<pre><code>client.on('message', msg => {
if(validateUrl(msg.content)){
const siteUrl = encodeURI(msg.content);
getPage(msg, siteUrl);
}
});
</code></pre>
<p>Also I wrote up <a href="https://gist.github.com/JasonMadeSomething/4e557989e3b9fbd71a0bd21ec2168aac" rel="nofollow noreferrer">this gist</a> on how I deployed it to a raspberry pi. That works, so suggestions on how to improve it would be greatly appreciated</p>
<p>In broad strokes this program:</p>
<ol>
<li>Listens for a message</li>
<li>Validates the message</li>
<li>Gets the page content at the message url</li>
<li>Parses the page content</li>
<li>Re-formats the page content</li>
<li>Converts the page content into a message</li>
<li>Sends the message</li>
</ol>
|
[] |
[
{
"body": "<p>Here's how I would do it. Move the logic about which pages a parser consumes into the code for said parser. Also organizing your helper files into objects could reduce complexity in terms of the number of variables you pass around but that's more a matter of personal preference.</p>\n<pre><code>class SpecificPageParser {\n match(url) {\n return (\n url.startswith('https://www.d20pfsrd.com/magic/') &&\n !url.endsWith('/magic/')\n );\n }\n format(response) {\n // do your parsing stuff\n const formatted = {...response,'extra':'info'};\n return formatted;\n }\n}\n\nconst responders = [new SpecificPageParser(),new SomeOtherParser()];\n\nasync function getPage(msg, url){\n try {\n const responder = responders.find(responder=>responder.match(url));\n if (!responder) return;\n const response = await axios.get(url);\n const message = responder.format(response);\n sendMessage(message, msg);\n }\n catch(error) {\n console.error(error);\n }\n }\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T20:11:52.807",
"Id": "485860",
"Score": "0",
"body": "So i've been trying to implement this, and I'm noticing that my reflex seems to be to recreate the ungeneralized responder in the format function of each parser class. The logic of responder would be nearly identical for both classes with only the function names varying. Is that simply the trade off at play here, or can I generalize the passing of the data around to the parsing steps so each class can implement it? (would that be an abstract class?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T23:13:28.323",
"Id": "485866",
"Score": "0",
"body": "I managed to implement the classes for the parsers, and I'm seeing how it cuts way down on the amount of code I used. I suppose I would have to write a lot more if I want to avoid replicating the 3 lines of the formatter logic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T01:56:17.033",
"Id": "485872",
"Score": "1",
"body": "If the logic ends up similar with only minor differences in specific functions you could add the specific functions as methods on your parsers and then writing your overall format() function once using the generic methods."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T03:57:13.537",
"Id": "247976",
"ParentId": "247970",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "247976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-15T23:15:05.300",
"Id": "247970",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"web-scraping",
"raspberry-pi"
],
"Title": "d20pfsrd Discord Bot Scraper Abstraction and Deployment"
}
|
247970
|
<p>A few days back I found an interesting problem which reads the following:</p>
<p>Given two vector spaces generate the resulting set of its cartesian product.
<span class="math-container">\begin{gather}
\text{Let: } \mathcal{V}, \mathcal{W} \text{ be vector spaces}\\
\mathcal{V} \times \mathcal{W} = \{ (v,w) \mid v \in \mathcal{V} \land w \in \mathcal{W} \}
\end{gather}</span></p>
<ul>
<li>Hint 1: A vector space is a set of elements called vectors which accomplishes some properties</li>
<li>Hint 2: Design the solution for finite vector spaces</li>
<li>Tip 1: It is recommended to use structures</li>
<li>Constraint: You are forbidden to use any stl class</li>
</ul>
<p>I solved this problem with the next approach:</p>
<pre class="lang-cpp prettyprint-override"><code>struct vector_pair
{
double *vector_a;
double *vector_b;
size_t a_dimension;
size_t b_dimension;
};
struct cartesian_product_set
{
vector_pair *pairs;
size_t pairs_number;
};
cartesian_product_set vector_spaces_cartesian_product(double **space_v, size_t v_vectors,
size_t v_dimension, double **space_w, size_t w_vectors, size_t w_dimension)
{
cartesian_product_set product_set{new vector_pair[v_vectors * w_vectors], v_vectors * w_vectors};
for (size_t i = 0, j, k = 0; i < v_vectors; i++)
for (j = 0; j < w_vectors; j++)
product_set.pairs[k++] = vector_pair{space_v[i], space_w[j], v_dimension, w_dimension};
return product_set;
}
</code></pre>
<p>How could I improve this code if possible?</p>
<p>Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T14:16:50.097",
"Id": "485670",
"Score": "0",
"body": "Are you sure the result should contain `vector_pairs`? The question might also suggest you have to return a single vector of dimension `a_dimension + b_dimension`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T15:21:46.027",
"Id": "485673",
"Score": "0",
"body": "A cartesian product generates pairs, it doesn't operate the objects which it takes. It is like a combinatorial of each element in V with each element in W by pairs; The dimension of those vectors doesn't affect the product."
}
] |
[
{
"body": "<ol>\n<li>const-correctness</li>\n<li>use references in favor of pointers where possible</li>\n<li>The fact that you leave the obligation to free the memory that you allocate to the caller is generally not a good practice</li>\n<li>a common pattern in your code is that you have pointers to arrays and their length - why not make a structure to bundle them up?</li>\n<li>try to make use of iterators and range-based-for-loops when you don't really need the index (which you don't in your example)</li>\n<li>since we don't really care about the type of the elements in a vector space you could use templates to generalize your algorithm</li>\n</ol>\n<p>And just to see if it would be possible, I tried to come up with a compile-time version of the algorithm:</p>\n<pre><code>template<typename T>\nstruct pair\n{\n T first;\n T second;\n};\n\ntemplate<std::size_t N, typename T>\nstruct cvp\n{\n pair<T> pairs[N];\n};\n\ntemplate <typename T, size_t NV, size_t NW>\nauto get_cvp(const T (&vs)[NV], const T (&ws)[NW])\n{\n cvp<NV*NW, T> result;\n auto it_pairs = std::begin(result.pairs);\n for (const auto v : vs) {\n for (const auto w : ws) {\n *(it_pairs++) = {v, w};\n }\n }\n return result;\n}\n</code></pre>\n<p>you can try the code here: <a href=\"https://godbolt.org/z/e8GvEf\" rel=\"nofollow noreferrer\">https://godbolt.org/z/e8GvEf</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:23:43.000",
"Id": "485812",
"Score": "0",
"body": "Thank you so much, your explanation is concise and you provide an actual example with templates. The only thing I would change would be `cvp` by `cartesian_product` because as this algorithm generalizates the pairs it is not different from a cartesian between two sets (which is more abstract)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T08:28:14.323",
"Id": "248078",
"ParentId": "247972",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248078",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T01:08:27.237",
"Id": "247972",
"Score": "6",
"Tags": [
"c++",
"performance"
],
"Title": "cartesian product of two vector spaces"
}
|
247972
|
<p>I made a tic tac toe bot with the following rules (it's not unbeatable):</p>
<ol>
<li>If bot is about to win, it will find the winning move.</li>
<li>If bot is about to lose, it will find a move that prevents the other player from winning.</li>
<li>if none of rule 1 or 2 is found, then it will play a random move</li>
</ol>
<p>I think it's highly inefficient, so if you could give optimization advice, that would be great!</p>
<pre class="lang-py prettyprint-override"><code>class Cell(str): # a class for strings with unique ids, every time
pass
def mediumbot_move(self, player):
"""
medium level bot player - allows a bot with two rules to play
1) If bot is about to win, it will find the winning move.
2) If bot is about to lose, it will find a move that prevents the other player from winning.
3) if none of rule 1 or 2 is found, then it will play a random move
"""
print('Making move level "medium"')
opponent = self.other_player[player]
board = self.board.board # the board represented as an array like ["X", "O", " ", "O", ...]
winning_three = set(itertools.permutations([player, player, " "])) # permutation for all the winning positions
losing_three = set(itertools.permutations([opponent, opponent, " "])) # permutation for all the losing positions
# the three across positions
horizontals = [board[i:i+3] for i in range(0, 7, 3)]
verticals = [board[i:9:3] for i in range(3)]
diagonals = [board[0:9:4], board[2:7:2]]
# if a winning pattern found win
for pattern in (horizontals + verticals + diagonals):
pattern = tuple(pattern)
if pattern in winning_three:
for winning_pattern in winning_three:
if pattern == winning_pattern:
position_id = id(pattern[pattern.index(" ")]) # storing the id of the empty spot to place player on to win
for i in range(9): # looping through the board (array) to find the stored id, to place player
if id(board[i]) == position_id:
self.board.board[i] = Cell(player)
return
# if no winning patterns found, choose a move, that would not result in a loss
for pattern in (horizontals + verticals + diagonals):
pattern = tuple(pattern)
if pattern in losing_three:
for losing_pattern in losing_three:
if pattern == losing_pattern:
position_id = id(pattern[pattern.index(" ")])
for i in range(9):
if id(board[i]) == position_id:
self.board.board[i] = Cell(player)
return
# if no patterns found, choose a random move
available_indexes = [index for index in range(9) if board[index] == " "]
bot_index = random.choice(available_indexes)
self.board.board[bot_index] = Cell(player)
</code></pre>
|
[] |
[
{
"body": "<p>First of all, this is too big for one function. You have 7 levels of indentation. Split it up, or remove levels.</p>\n<p>Second, you say "I think this is inefficient". Why? Have you timed it? How long does it take? How long do you think it should take? It is a bad idea to try to speed things up before measuring — maybe there is no problem. Maybe some other part of your program is the slow part.</p>\n<p>If you are trying to figure out how to make your program efficient, you normally only need to look at the <code>for</code> loops:</p>\n<pre><code>for pattern in (horizontals + verticals + diagonals):\n for losing_pattern in losing_three:\n for i in range(9):\n</code></pre>\n<p>It should take (8 * 3 * 9)=216 iterations. Actually less, because you have <code>if</code> branches, but that's the maximum. You could make this smaller, yes (both of the two inner loops can be removed). But also, 216 iterations is just not that many — your computer executes a billion operations per second.</p>\n<p>You should remove your third <code>for</code> loop, and every use of <code>id</code>, because it is confusing and hard to read, not because it's a loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:28:54.767",
"Id": "251578",
"ParentId": "247973",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T02:55:13.290",
"Id": "247973",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"tic-tac-toe"
],
"Title": "A Tic-Tac-Toe AI based on two rules"
}
|
247973
|
<p>I am trying to write a <code>Person</code> class in Ruby which has some methods and properties. The below is how I have implemented it now.</p>
<pre><code>class Person
attr_accessor :name, :gender, :mother, :spouse
def initialize(name, gender, mother = nil)
@name = name
@gender = gender
@mother = mother
@spouse = nil
end
def add_spouse(spouse)
if spouse
@spouse = spouse
spouse.spouse = self
end
end
def father(self)
return [self.mother.spouse]
end
end
</code></pre>
<p>I want to access the methods like this:</p>
<pre><code>m = Person.new('mom', 'Female')
d = Person.new('dad', 'Male')
d.add_spouse(m)
p = Person.new('Jack', 'Male', m)
</code></pre>
<p>If I want to get the <code>father</code> of <code>p</code>, then I want to get it like this: <code>p.father</code>.</p>
<p>So is the above implementation correct?</p>
<p>In python if I want a class method as a property then <code>@property</code> is used. In Ruby is there anything like that or is the above method for <code>father</code> property correct?
Also I have seen examples with <code>self.some_variable</code> and <code>@some_variable</code> in Ruby. Here <code>name</code> and <code>gender</code> variables are defined at the object creation and never changed but other variables like <code>mother</code>, <code>children</code> can be <code>nil</code> initially and can be added by some other external method. For eg: By a method <code>add_member</code> in <code>class Family</code>. So for that is the above definition correct?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:05:08.227",
"Id": "485648",
"Score": "0",
"body": "This question if off-topic on [codereview.se], as per the [help]. [codereview.se] is for review of *working code*, so the question \"is this code correct\" is off-topic. Besides that, the code has a trivial `SyntaxError`, it isn't even legal Ruby. You might get better help on [so], but please make sure to produce a *minimal reproducible example*. In particular, the `SyntaxError` can be trivially reproduced in one line, it doesn't require 22 lines of code to show."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T14:11:40.030",
"Id": "485726",
"Score": "0",
"body": "\"So is the above implementation correct?\" Did you test it? Please see our [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T15:11:28.107",
"Id": "485732",
"Score": "0",
"body": "I had put `self` in `def father` initially. Then I changed it in my code but while typing the question I mistyped it. I have changed it now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T15:30:29.510",
"Id": "485733",
"Score": "1",
"body": "Please do not update the code in your question after receving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Next time, make sure your first revision is the right one."
}
] |
[
{
"body": "<p>Your code has an error in the definition of father.\nIn ruby, there is no need to add self as a parameter.\nIn addition you return an array with the mother. This may be correct under some legal systems, but I think you didn't want to implement this..</p>\n<p>It is fine, if you use:</p>\n<pre><code>def father()\n return self.mother.spouse\nend\n</code></pre>\n<p>Then you can use it as <code>son.father</code>.</p>\n<hr />\n<p>Ruby defines instance variables as <code>@varname</code>, you can use them inside the class.</p>\n<p>If you want to have access from outside, you must define accessors (setter, getter or both). From outside you don't see a difference between accessors and "normal" methods. You call a method and get a result.</p>\n<p>Inside a class I recommend to use the accessor if it is defined. If you ever replace the standard accessor with a programm logic, then you don't need to adapt the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T18:18:55.463",
"Id": "485686",
"Score": "1",
"body": "Most coding styles would just write `def father`, without the parentheses, instead of `def father()` and just `mother.spouse` instead of `return self.mother.spouse`, neither the return nor the self are necessary here"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T15:42:04.353",
"Id": "247995",
"ParentId": "247975",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "247995",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T03:27:34.317",
"Id": "247975",
"Score": "-1",
"Tags": [
"ruby"
],
"Title": "Correct way to define variables and methods in Ruby"
}
|
247975
|
<p><a href="https://i.stack.imgur.com/sfkTY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sfkTY.png" alt="enter image description here" /></a></p>
<p>Image transcription:</p>
<p>A company registers for an IPO. All shares are available on the website for bidding during a time frame called the bidding window. At the end of the bidding window an auction logic is used to decide how many available shares go to which bidder until all shares have been allocated, or all the bidders have received the shares they bid for, whichever comes first.</p>
<p>The bids arrive from users in the form of [userid, # shares, bidding price, timestamp] until the bidding window is closed.</p>
<p>The auction logic assigns shares as follows:</p>
<ol>
<li><p>The bidder with the highest price gets the # of shares they bid for</p>
</li>
<li><p>If multiple bidders have bid at the same price, the bidders are assigned shares in the order in which they places their bids (earliest bids first)</p>
</li>
</ol>
<p>List the userids of all the users who didn't get even 1 share after all shares have been allocated.</p>
<h2>Input</h2>
<ul>
<li>bids<br />
list of lists of ints representing [userid, # shares, $bid, timestamp]</li>
<li>totalShares<br />
total # of shares to be distributed.</li>
</ul>
<h2>Todo</h2>
<p>distribute shares amongst bidders and return userids of bidders that got 0 shares.</p>
<p>Share distribution logic:</p>
<ol>
<li>bidder with highest offer gets all the shares they bid for, and then</li>
<li>if there are ties in $ bid price, assign shares to earlier bidder.</li>
</ol>
<p>I feel like the solution I came up with is relatively simple. It seems to pass all edge cases I can think of.</p>
<h2>Question</h2>
<p>I have found a questionable situation:<br />
Bid price and times are the same and there aren't enough shares for all bidders ie: <code>bids</code> is <code>[[0,2,10,0], [1,2,10,0]]</code> and <code>totalShares</code> is <code>2</code>. It's unclear if 1 share should be given to each, or if userid 0 just gets both.</p>
<h2>Code</h2>
<p>Can my solution be optimized in anyway?</p>
<pre><code>def getUnallocatesUsers(bids, totalShares):
s = 0
for b in bids:
s += b[1]
if totalShares >= s: return [] # no losers because enough shares to go around
bids.sort(key = lambda x: (-x[2],x[3])) # sort by highest bid, then timestamp for ties
losers = []
for b in bids:
if totalShares <= 0: losers.append(b[0])
else:
totalShares -= b[1]
return losers
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T04:31:13.647",
"Id": "485627",
"Score": "3",
"body": "Please can you convert the image to text. Images are fairly inaccessible for our users that are blind. Additionally the image currently is illegible to me due to the resizing. Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T15:25:02.463",
"Id": "485674",
"Score": "0",
"body": "@Peilonrayz thanks, added"
}
] |
[
{
"body": "<p>Use the function name given in the problem:</p>\n<pre><code>def getUnallottedUsers(bids, totalShares):\n</code></pre>\n<p>The problem doesn't provide any information about the likelihood of there being enough shares for all bidders, so IMO the first for-loop is an example of premature optimization.</p>\n<p>Use constants instead of "magic numbers". Use meaningful names. Take a look at PEP8 about common formatting conventions. These things go a long way in making code readable.</p>\n<pre><code>USERID = 0\nSHARES = 1\nPRICE = 2\nTIME = 3\n\nbids.sort(key=lambda bid:(-bid[PRICE], bid[TIME]))\n\nfor index, bid in enumerate(bids):\n totalShares -= bid[SHARES]\n\n if totalShares <= 0:\n break\n</code></pre>\n<p>Answer the question that was asked: "The function must return a list of integers, each an id for those bidders who receive no shares, <strong>sorted ascending</strong>"</p>\n<pre><code>return sorted(bid[USERID] for bid in bids[index + 1:])\n</code></pre>\n<p>All together:</p>\n<pre><code>USERID = 0\nSHARES = 1\nPRICE = 2\nTIME = 3\n\ndef getUnallottedUsers(bids, totalShares):\n bids.sort(key=lambda bid:(-bid[PRICE], bid[TIME]))\n\n for index, bid in enumerate(bids):\n totalShares -= bid[SHARES]\n\n if totalShares <= 0:\n break\n\n return sorted(bid[USERID] for bid in bids[index + 1:])\n</code></pre>\n<p>Or use an iterator:</p>\n<pre><code> bids = iter(bids)\n while totalShares > 0:\n price = next(bid)[PRICE]\n totalShares -= price\n\n return sorted(bid[USERID] for bid in bids)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T02:39:57.767",
"Id": "248067",
"ParentId": "247977",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248067",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T04:11:11.627",
"Id": "247977",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Initial public offering auction"
}
|
247977
|
<p>I have a chunk of code here:</p>
<pre><code>public class ParserFactory
{
public static ParserClass getParserClass(InputStream is, CustomMap customMap,
DataHandler recordHandler, DataHandler columnHandler) throws JsonProcessingException
{
ParserClassType ParserClassType = ParserClassType.getParserClassType(customMap.getParser());
switch (ParserClassType)
{
case SPECIFIC_XML:
return new SpecificXMLParser(is, customMap.getProperties(), recordHandler, columnHandler);
case XML:
return new GenericXMLParser(is, customMap.getProperties(), recordHandler, columnHandler);
case JSON:
return new GenericJSONParser(is, customMap.getProperties(), recordHandler, columnHandler);
case SPECIAL:
return new SpecialParser(is, customMap.getProperties(), recordHandler, columnHandler);
case FW:
return new GenericFixedWidthParser(is, customMap.getProperties(), recordHandler, columnHandler);
case CSV:
return new GenericCSVParser(is, customMap.getProperties(), recordHandler, columnHandler);
default:
throw new IllegalArgumentException("ParserClassType not found.");
}
}
public static String getFileExtension(CustomMap customMap)
{
ParserClassType ParserClassType = ParserClassType.getParserClassType(customMap.getParser());
switch (ParserClassType)
{
case SPECIFIC_XML:
return SpecificXMLParser.FILE_TYPE_OUTPUT;
case XML:
return GenericXMLParser.FILE_TYPE_OUTPUT;
case JSON:
return GenericJSONParser.FILE_TYPE_OUTPUT;
case SPECIAL:
return SpecialParser.FILE_TYPE_OUTPUT;
case FW:
return GenericFixedWidthParser.FILE_TYPE_OUTPUT;
case CSV:
return GenericCSVParser.FILE_TYPE_OUTPUT;
default:
throw new IllegalArgumentException("ParserClassType not found.");
}
}
}
</code></pre>
<p>Now, it's not exactly too important what all these arguments are. In <code>getParserClass</code>, I retrieve an enum from <code>ParserClassType</code>. The switch handles all the possible values. A certain value will return a <code>ParserClass</code>.</p>
<p>The other function, <code>getFileExtension</code>, retrieves a static string from a parser class.</p>
<p>As my project grows, I will have many new parsers that I add. I want to make this as flexible and less-hectic as possible. I don't want to keep adding cases to this function. So.</p>
<p>I was looking into EnumMap. I was thinking of mapping an ENUM to a ParserClass name, so for example "XML" would make to "GenericXMLParser.class", and then I could use a ReflectionUtil to create the class with the arguments necessary or retrieve that string. Therefore, if I have to make any additions, all I need to do is add the ENUM to the enum class and make an addition to the map. But, ReflectionUtils seems to require me to provide the path of the parser. Something like "com.package.service.more.bs.SpecificXMLParser". I would rather not do that...</p>
<p>Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:31:27.417",
"Id": "485635",
"Score": "2",
"body": "Why not using interfaces instead of reflection?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:34:54.520",
"Id": "485637",
"Score": "0",
"body": "How would an interface solve my problem? They all extend from an abstract class (ParserClass); the only reason it isn't an interface is because the class also has a bunch of member variables that are shared across all the children classes. But also, in the second function, each parser has a different file output extension. Not sure how interfaces would help here... shed some light?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:40:47.660",
"Id": "485638",
"Score": "0",
"body": "For example the `IParserClass` interface should provide a `getFileExtension()` method and the implementation handles this internally. Thus you don't need a switch to determine it from concrete parser implementations. But without seeing more context of your code, it's impossible to give advice how to improve it in this direction."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:51:41.313",
"Id": "485640",
"Score": "0",
"body": "I see what you're saying. The specific function you're talking about in this class I shared needs to be called _before_ I have a Parser Instance. You can trust me on that. Otherwise, of course, I would totally agree with you and would have done that readily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:54:37.730",
"Id": "485641",
"Score": "0",
"body": "I recently faced this problem where I was returning various class objects based on the type. I will have a lot of types and switch case approach was not scalable for me. To solve this problem I used mapBinder https://stackoverflow.com/questions/27871631/gof-standard-factory-pattern-using-guice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:56:10.637",
"Id": "485642",
"Score": "1",
"body": "@JohnLexus You might be interested in looking at the [_Abstract Factory_ design pattern](https://sourcemaking.com/design_patterns/abstract_factory) and shift the knowledge about the concrete file extensions and corresponding parser class types there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:11:57.793",
"Id": "485649",
"Score": "3",
"body": "For the context vote closer(s), there is plenty of context to review, this does not look like stub code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T08:34:39.630",
"Id": "485710",
"Score": "0",
"body": "@DeepakPatankar thank you for your comment; this looks like it has a serious dependency? Guice? Would rather not add a heavy dependency for something like this..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T11:52:42.117",
"Id": "485716",
"Score": "1",
"body": "@JohnLexus In our project, we have multiple uses of guice, so for me, the solution I proposed was good. I agree with your point. It doesn't make sense to add this dependency just for this use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T06:59:00.993",
"Id": "485781",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T16:55:12.387",
"Id": "485845",
"Score": "0",
"body": "@BCdotWEB please suggest a title name :)"
}
] |
[
{
"body": "<p>The only problem I see with this code is, that for extending the enum, you need to change <em>two</em> methods in the code, which spreads out changes instead of keeping them local to a single place.</p>\n<p>You could however harness the power of the java enum (which can have fields and methods) to make the changes locally.</p>\n<p>Something along the lines of:</p>\n<pre><code>enum ParserClassType {\n SPECIFIC_XML(SpecificXMLParser.FILE_TYPE_OUTPUT) {\n public ParserClass createParser(InputStream is, etc, ...) {\n return new SpecificXMLParser(...);\n }\n },\n XML(GenericXMLParser.FILE_TYPE_OUTPUT) {\n public ParserClass createParser(InputStream is, etc, ...) {\n return new GenericXMLParser(...);\n }\n },\n ...\n\n private final String fileExtension;\n\n private ParserClassType(String fileExtension) {\n this.fileExtension = fileExtension;\n }\n\n public String getFileExtension() {\n return fileExtension;\n }\n\n public abstract ParserClass createParser(InputStream is, etc, ...);\n}\n\npublic static String getFileExtension(...) {\n ParserClassType parserClassType = ...\n return parserClassType.getFileExtension();\n}\n\npublic ParserClass getParserClass(...) {\n ParserClassType parserClassType = ...\n return parserClassType.createParser(...);\n}\n</code></pre>\n<p>As you see, when you add a new type, you simply have to extend the enum. All the client code stays unmodified.</p>\n<p>Apart from that, please look up the java naming conventions. Variables should start with lower case letters and definitely not shadow their class names.</p>\n<p>Furthermore, getParserClass() / ParserClass is badly named, as it clearly involves around a concrete parser / parserInstance, not around a <em>class</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T16:53:50.960",
"Id": "485844",
"Score": "0",
"body": "Thanks for this. The classes and function names have been modified; actually, this code is nowhere to be found in the actual code. Typing out the class names would reveal more than I would like to about what I'm working on. I'll consider this, though.."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T04:23:28.530",
"Id": "248072",
"ParentId": "247980",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T07:23:04.003",
"Id": "247980",
"Score": "1",
"Tags": [
"java"
],
"Title": "I have a Java Class that I suspect can use a ReflectionUtil here because there are too many switch/cases, any advice?"
}
|
247980
|
<p>So I answered <a href="https://stackoverflow.com/questions/63424959/csv-file-containing-solutions-of-polynomial-equation">this question on SO</a> and probably did someone's homework along the way.
In the original question the OP has the <code>answer</code> variable and wants it split to real and imaginary values with the original coefficient (<code>q</code> in the original post) as an array for each q from 1 to 10, so you get an array of arrays looking like:</p>
<pre><code>[[1,-0.39002422, 1.84237253, -0.39002422, -1.84237253, -0.10997578, 0.51949688,-0.10997578, -0.51949688j],
[2, ...]
...
[10, ...]]
</code></pre>
<p>There are two things I'm unsatisfied with in the answer I gave that are the reason I'm asking for a CR.</p>
<ol>
<li>The indexing: Isn't particularly readable, and I don't know how to make it more readable. For example <code>[q-1, 2*_+1]</code>. Would it have been better to create a variable <code>j = q-1</code> because <code>q-1</code> sees frequent use? Isn't that just moving the ugly to a different place?</li>
<li>The idea for the solution itself. The way I see it the original problem can be solved by splitting the answer array to a new array, but that feels somehow wrong. I can see several ways to create the new array, but I don't see a way to do it without creating the new array. Am I wrong and this is an OK solution or not, and why?</li>
</ol>
<p>Thanks.</p>
<pre><code>import numpy as np
export = np.empty([10,9])
for q in range(1,11):
a0=1
a1=3*q^2
a2=4*q
a3=np.sqrt(q)
a4=q
coeff=[a0, a1, a2, a3, a4]
answer = np.roots(coeff)
export[q-1, 0] = q
for _ in range(len(answer)):
export[q-1, 2*_+1] = answer[_].real
export[q-1, 2*(_+1)] = answer[_].imag
with open("/tmp/latest_foo.csv", "ab") as output_file:
np.savetxt(output_file, export, delimiter=",")
</code></pre>
|
[] |
[
{
"body": "<p>A more pythonic method for that last <code>for</code> loop would be to use nested list comprehensions. It's likely faster, as well:</p>\n<pre><code>[item for sublist in [[x.real, x.imag] for x in answer] for item in sublist]\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists\">this question</a> for details about what's happening here, if you're not already familiar with list comprehensions.</p>\n<p>In other words, instead of these four lines:</p>\n<pre><code>export[q-1, 0] = q\nfor _ in range(len(answer)):\n export[q-1, 2*_+1] = answer[_].real\n export[q-1, 2*(_+1)] = answer[_].imag\n</code></pre>\n<p>You could write this:</p>\n<pre><code>line = [q]\nline.extend([item for sublist in [[x.real, x.imag] for x in answer] for item in sublist])\nexport[q-1] = line\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T14:12:36.317",
"Id": "485727",
"Score": "0",
"body": "It might be worth mentioning what we *do* use for exponentiation, `**`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T14:35:17.127",
"Id": "247994",
"ParentId": "247981",
"Score": "2"
}
},
{
"body": "<p>Here is a review of the solution.</p>\n<ul>\n<li><p><code>^</code> is xor in Python. It is not for computation of exponentials.</p>\n</li>\n<li><p>When running code outside a method / class, it is a good practice to put the code inside a <em>main guard</em>. See <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">here</a> for more explanation.</p>\n<pre><code> if __name__ == "__main__":\n ...\n</code></pre>\n<p>When you are providing quick answers on a forum, the guard might not always be necessary. However, if you are writing reusable code for yourself, it is better to adopt the practice.</p>\n</li>\n<li><p>By convention, <code>_</code> is used to represent a don't-care variable, which won't be used after its value is assigned, e.g. <code>v = [[] for _ in range(4)]</code>. It is undesirable to refer to it in an expression like <code>answer[_]</code>.</p>\n</li>\n<li><p>The output is a pure text file. It is unnecessary to open it in binary mode (<code>b</code>). The original question does not suggest an append mode (<code>a</code>) either.</p>\n</li>\n<li><p>The <code>q-1</code> index would no longer work if <code>q</code> is changed to a different group of values. Therefore, it is better to use <code>enumerate</code> in this case:</p>\n<pre><code>for i, q in enumerate(RANGE_Q):\n ...\n export[i, 0] = q\n ...\n</code></pre>\n<p>A better approach is to use <code>zip</code>:</p>\n<pre><code>for q, output_row in zip(RANGE_Q, output_arr):\n ...\n output_row[0] = q\n ...\n</code></pre>\n</li>\n<li><p>The assignments to the output numpy array can be improved, as shown in my solution below.</p>\n</li>\n</ul>\n<p>Here is my solution.</p>\n<pre><code>import numpy as np\n\nif __name__ == "__main__":\n # Define constants\n RANGE_Q = range(1, 11) # Range of q values\n POLY_DEG = 4 # Degree of polynomial\n OUTPUT_PATH = "/tmp/latest_foo.csv" # Output csv path\n\n # Compute roots\n roots_arr = np.array([np.roots([1, 3*q*q, 4*q, np.sqrt(q), q]) for q in RANGE_Q])\n \n # Construct output array and assign values\n output_arr = np.empty(shape=(len(RANGE_Q), POLY_DEG * 2 + 1))\n output_arr[:, 0] = RANGE_Q\n output_arr[:, 1::2] = roots_arr.real\n output_arr[:, 2::2] = roots_arr.imag\n\n # Save results to output file\n np.savetxt(OUTPUT_PATH, output_arr, fmt="%.4g", delimiter=',')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T18:03:28.540",
"Id": "247999",
"ParentId": "247981",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "247999",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:10:07.407",
"Id": "247981",
"Score": "7",
"Tags": [
"python",
"array",
"numpy"
],
"Title": "How to clean the indexes, and ideally not create an additional array"
}
|
247981
|
<p>This is regarding leetcode <a href="https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/" rel="nofollow noreferrer">Question# 123</a>. I have solved the question (code below) but the solution is showing "Your runtime beats 5.89 % of cpp submissions."? Is there any additional optimization I can do to make it run faster?</p>
<pre><code>class Solution {
int maxProfitUtility(vector<int>& prices, int i, int buyOrSell, int k, vector<vector<vector<int>>>& dp){
if(i == prices.size() || k == 0){
return 0;
}
if(dp[i][buyOrSell][k] != INT_MIN){
return dp[i][buyOrSell][k];
}
int x, y;
if(buyOrSell == 0){
x = maxProfitUtility(prices, i + 1, 1, k - 1, dp) - prices[i];
y = maxProfitUtility(prices, i + 1, 0, k, dp);
}else{
x = maxProfitUtility(prices, i + 1, 0, k - 1, dp) + prices[i];
y = maxProfitUtility(prices, i + 1, 1, k, dp);
}
dp[i][buyOrSell][k] = max(x,y);
return max(x,y);
}
public:
int maxProfit(vector<int>& prices) {
int k = 4;
vector<vector<vector<int>>> dp(prices.size(), vector<vector<int>>(2, vector<int>(k + 1, INT_MIN)));
return maxProfitUtility(prices, 0, 0, k, dp);
}
};
</code></pre>
|
[] |
[
{
"body": "<p>Recursion comes with overheads. You need to push to the call stack and create a new context for your code to execute in.</p>\n<p>I would convert this to an iterative solution.</p>\n<p>You also don't need to allocate so much memory. Think closely about what information you actually need. HINT: If you could only go long on the stock, you would only need to store 2 ints as you iterate over the list to get your maximum profit.</p>\n<p>Furthermore leetcode has the option of viewing code from the fastest solutions. Check that out and if you don't understand why their solution is so much faster, post on stack overflow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:49:16.623",
"Id": "247984",
"ParentId": "247982",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T10:18:56.860",
"Id": "247982",
"Score": "2",
"Tags": [
"c++",
"performance",
"dynamic-programming"
],
"Title": "Why below recursive DP solution is so slow? (Leetcode Q# 123 - Best Time to Buy and Sell Stock III)"
}
|
247982
|
<p>I am a beginner in Python and I have written a program to convert binary numbers to decimal. It works, but are there any ways to improve the code and make it better?</p>
<pre><code>def binary_to_decimal_converter(binary_value):
print(f"Binary: {binary_value}")
decimal_value = 0
# Treating binary input as a string
# power is power of number 2
# power must be less than string length because computer starts counting from 0th index
power = len(str(binary_value)) - 1
loop_var = 0
while loop_var < len(str(binary_value)):
if str(binary_value)[loop_var] == str(1):
decimal_value += 2 ** power
power -= 1
loop_var += 1
return print(f"Decimal: {decimal_value}")
# Calling the function
binary_to_decimal_converter(1111101100)
</code></pre>
<p>Output:</p>
<pre><code>Binary: 1111101100
Decimal: 1004
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T12:39:01.017",
"Id": "485654",
"Score": "1",
"body": "Does this function really do what you meant to do? The input isn't really in binary, it's sort of \"decimal coded binary\" (one decimal digit encodes one binary digit). That's very strange."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T12:46:50.593",
"Id": "485655",
"Score": "0",
"body": "yeah the input is string.... the fucntion does the job.... but im not sure about the logic... and that's what im trying to figure out. Im a total newbee"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T12:57:55.213",
"Id": "485659",
"Score": "1",
"body": "Well that's the strange thing, the input isn't a string, but it could have been and then you wouldn't need `str(binary_value)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:08:57.563",
"Id": "485661",
"Score": "0",
"body": "Oh... Okay.. Understood. Thanks a lot :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:15:06.080",
"Id": "485662",
"Score": "0",
"body": "I think this is off-topic, as your code really doesn't do the job. You don't take binary (you take an int) and you don't convert to decimal (you produce an int). The only place converting to decimal is when you *print* an int, and that's not your code doing the job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T13:23:46.663",
"Id": "485664",
"Score": "0",
"body": "@HeapOverflow Okay... I undrestand. I've just started learning four days ago..... Just wanted to have some insights... Thanks."
}
] |
[
{
"body": "<h1>Do conversions once</h1>\n<p>As written, with the example input, <code>str(binary_value)</code> will be called 22 times, with the same input value, and returning the same value each time. This is very inefficient; it is wasted work. It would be better to call it once, and store the result, and use this stored value:</p>\n<pre><code>def binary_to_decimal_converter(binary_value):\n binary_value = str(binary_value)\n # ... rest of function, without any more str(binary_value) calls\n</code></pre>\n<p>But ...</p>\n<h1>Representing Binary Numbers</h1>\n<p>As pointed out by <a href=\"https://codereview.stackexchange.com/users/36018/harold\">harold</a> in the comments, the literal <code>1111101100</code> is an integer value slightly larger than one billion in Python. You should use a string to represent a binary number to be converted.</p>\n<pre><code># Calling the function\nbinary_to_decimal_converter("1111101100")\n</code></pre>\n<p>Since we're passing a string to the function, all of the calls to <code>str(binary_value)</code> are now completely unnecessary.</p>\n<h1>String Constants</h1>\n<pre><code> if str(binary_value)[loop_var] == str(1):\n</code></pre>\n<p>Again, using the example value, the expression <code>str(1)</code> will be evaluated ten times; once for each digit of the input. This will convert the numerical value one into the string <code>"1"</code>, which will be discarded immediately after use, only to be recreated on the next iteration. Why not just use the literal <code>"1"</code>? Not only is it more efficient; it is 3 characters shorter.</p>\n<h1>Loop like a Native</h1>\n<p>See <a href=\"https://youtu.be/EnSu9hHGq5o\" rel=\"nofollow noreferrer\">"Loop like a Native" by Ned Batchelder</a> on YouTube for more details, motivation, etc.</p>\n<h2>Part 1</h2>\n<p>Our modified code now looks like this:</p>\n<pre><code> loop_var = 0\n while loop_var < len(binary_value):\n # ...\n loop_var += 1\n</code></pre>\n<p><code>len(binary_value)</code> is computed once for each iteration through the loop; 11 times, including the last pass where the condition evaluates to <code>False</code> and the loop terminates. Since the string doesn't change inside the loop, the length won't change either, so this value is a constant.</p>\n<pre><code> loop_var = 0\n limit = len(binary_value)\n while loop_var < limit:\n # ...\n loop_var += 1\n</code></pre>\n<p>Now that we've recognized that <code>limit</code> is fixed, we can see this is actually a <code>for</code> loop, that starts at zero, counts up by 1, and stops when it reaches <code>limit</code>. Instead of manually adjusting the <code>loop_var</code> by 1, and manually doing the comparison, we should simply use the <code>for</code> loop, over the required <code>range</code>, which is much more efficient:</p>\n<pre><code> for loop_var in range(len(binary_value)):\n # ...\n</code></pre>\n<h2>Part 2</h2>\n<p>Our loop now looks like:</p>\n<pre><code> for loop_var in range(len(binary_value)):\n if binary_value[loop_var] == "1":\n # ...\n # ...\n</code></pre>\n<p>Indexing is expensive in Python. Anytime you see a <code>for</code> loop, using a <code>range(len(thing))</code>, and the loop variable is only used as a index into the <code>thing</code> which the range is looping over, <code>thing[loop_var]</code>, then we want to let Python do the indexing for us in the <code>for</code> statement:</p>\n<pre><code> for digit in binary_value:\n if digit == "1":\n # ...\n # ...\n</code></pre>\n<h1>Return Value</h1>\n<pre><code> return print(f"Decimal: {decimal_value}")\n</code></pre>\n<p>Is this function returning a value, or is it printing the result? Currently, it is taking the value which is returned by the <code>print()</code> function, and returning that. Ie)</p>\n<pre><code> temporary = print(f"Decimal: {decimal_value}")\n return temporary\n</code></pre>\n<p>But <code>print()</code> returns <code>None</code>, so this is effectively:</p>\n<pre><code> print(f"Decimal: {decimal_value}")\n return None\n</code></pre>\n<p>And if the function ends without a return statement, it automatically returns <code>None</code> anyway. So the <code>return</code> can simply be omitted.</p>\n<p>Note: It is better to return results from a function that does a calculation, without printing anything inside the function, and have the caller do the printing. This will create more flexible code in the future. Left to student.</p>\n<h1>Improved code</h1>\n<pre><code>def binary_to_decimal_converter(binary_value):\n print(f"Binary: {binary_value}")\n decimal_value = 0\n\n # power is power of number 2\n # power must be less than string length because computer starts counting from 0th index\n power = len(binary_value) - 1\n\n for digit in binary_value:\n if digit == "1":\n decimal_value += 2 ** power\n power -= 1\n\n print(f"Decimal: {decimal_value}")\n\n\n# Calling the function\nbinary_to_decimal_converter("1111101100")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:18:36.467",
"Id": "485744",
"Score": "1",
"body": "You should add a link to NetBat's talk if you're going to use his title: https://youtu.be/EnSu9hHGq5o"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T19:25:40.027",
"Id": "485752",
"Score": "0",
"body": "Meh, this still only does half the job. It now takes a binary number, but still only produces an int, not a decimal number. The whole work of converting the int to decimal is done by the f-string. You might as well cheat for the first half of the job as well and use `int(binary_value, 2)`. Btw, your digits are binary digits, a.k.a. bits, so I'd use the variable name `bit`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T19:45:42.480",
"Id": "485753",
"Score": "0",
"body": "@superbrain It does what the original program appears to be intended to do, with didactic improvements aimed at the apparent level of the OP. It is tagged [tag:reinventing-the-wheel] (admittedly, by me) because the OP is clearly trying to implement the binary-to-integer conversion themselves. If you feel this answer is incomplete, and only doing half the job, please provide your own complete answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T04:54:51.883",
"Id": "486107",
"Score": "0",
"body": "@AJNeufeld Thanks a lot for your time and input. It helps a lot."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T16:22:44.347",
"Id": "248039",
"ParentId": "247987",
"Score": "2"
}
},
{
"body": "<ul>\n<li><p>Personally, I find the function name <code>binary_to_decimal_converter</code> more explicit than necessary, I'd call it <code>binary_to_decimal</code>.</p>\n</li>\n<li><p>Your input type is wrong. A binary number is a string. Your input is a number (technically an <code>int</code>). Numbers don't have digits/bits/whatever and aren't binary/decimal/whatever. Number <em>representations</em> have digits/bits/whatever and are binary/decimal/whatever. At most you could argue that <code>int</code> is internally a binary representation, but that wouldn't really be true (I think it's base 2<sup>31</sup> or so) and also none of our business. For all we know, it's just a number, and we can do number things with it. Like multiplying it with other numbers. But you can't ask it for a digit. Because it doesn't have any. Try <code>3141[2]</code>, you'll get an error. Unlike <code>'3141'[2]</code>, which gives you <code>'4'</code>. So since you're talking about binary and decimal, your input and output should be strings. (End of numbers-vs-number-representations rant :-)</p>\n</li>\n<li><p>You compute the number from the "binary" with your own code, but then you make the f-string do the whole second half of the job, conversion from the number to decimal. Rather seems like cheating.</p>\n</li>\n<li><p>It's inefficient and more complicated than necessary to use powers like you do. Instead, you could just double the current value before adding the next bit.</p>\n</li>\n</ul>\n<p>Code doing all that, converting the given binary to a number (int) and then to decimal:</p>\n<pre><code>def binary_to_decimal(binary):\n number = 0\n for bit in binary:\n number *= 2\n if bit == '1':\n number += 1\n decimal = ''\n while number:\n digit = '0123456789'[number % 10]\n decimal = digit + decimal\n number //= 10\n return decimal or '0'\n</code></pre>\n<p>Test:</p>\n<pre><code>>>> binary_to_decimal('1111101100')\n'1004'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T13:11:26.440",
"Id": "486137",
"Score": "0",
"body": "Thanks a lot for the input... makes a lot of sense now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T20:35:44.450",
"Id": "248057",
"ParentId": "247987",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T12:26:40.263",
"Id": "247987",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"reinventing-the-wheel"
],
"Title": "Binary to Decimal conversion program"
}
|
247987
|
<p>I've created an email sender with providers for the email content, that will be changed based on the email type. I need some help to enhance it.</p>
<p>These two models are used to send</p>
<pre><code>public class EmailAddress
{
public string Name { get; set; }
public string Address { get; set; }
}
public class EmailMessage
{
public EmailMessage()
{
ToAddresses = new List<EmailAddress>();
CcAddresses = new List<EmailAddress>();
}
public List<EmailAddress> ToAddresses { get; set; }
public List<EmailAddress> CcAddresses { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
}
</code></pre>
<p>The content provider provides all the email information(subject, body, To and Cc)</p>
<pre><code>public interface IEmailContentProvider
{
EmailMessage Message { get; }
}
</code></pre>
<p>Then we have the abstracted email sender <code>IEmailSender</code> that has a single method <code>Send</code> which uses <code>IEmailContentProvider</code> parameter to get the email information</p>
<pre><code>interface IEmailSender
{
Task Send(IEmailContentProvider provider);
}
</code></pre>
<p>I have an example for the content provider <code>WelcomEmailProvider</code></p>
<pre><code>public class WelcomEmailProvider : IEmailProvider
{
public EmailMessage Message { get; }
public WelcomEmailProvider(string address, string name)
{
Message = new EmailMessage
{
Subject = $"Welcome {name}",
Content = $"This is welcome email provider!",
ToAddresses = new List<EmailAddress> { new EmailAddress { Address = address, Name = name} }
};
}
}
</code></pre>
<p>The <code>IEmailSender</code> implementation:</p>
<pre><code>public class EmailSender : IEmailSender
{
private readonly SmtpOptions _options;
public EmailSender(IOptions<SmtpOptions> options)
{
_options = options.Value;
}
public async Task Send(IEmailContentProvider provider)
{
var emailMessage = provider.Message;
var message = new MimeMessage();
message.From.Add(new MailboxAddress(_options.Sender.Name, _options.Sender.Address));
message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
message.Cc.AddRange(emailMessage.CcAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
message.Subject = emailMessage.Subject;
message.Body = new TextPart(TextFormat.Html) { Text = emailMessage.Content };
using var emailClient = new SmtpClient();
await emailClient.ConnectAsync(_options.Server, _options.Port, _options.EnableSsl);
await AuthenticatedData(emailClient);
await emailClient.SendAsync(message);
await emailClient.DisconnectAsync(true);
}
private async Task AuthenticatedData(SmtpClient smtpClient)
{
if (string.IsNullOrWhiteSpace(_options.Username) || string.IsNullOrWhiteSpace(_options.Password))
return;
emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
await emailClient.AuthenticateAsync(_options.Username, _options.Password);
}
}
</code></pre>
<p>And here is, how to use it and send an email:</p>
<pre><code>class Sample
{
private readonly IEmailSender _emailSender;
public Samole(IEmailSender emailSender)
{
_emailSender = emailSender;
}
public async Task DoSomethingThenSendEmail()
{
await _emailSender.Send(new WelcomEmailProvider("someone@example.com", "Someone"));
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>public EmailMessage()\n{\n ToAddresses = new List<EmailAddress>();\n CcAddresses = new List<EmailAddress>();\n}\n</code></pre>\n<p>Not necessary, I can understand if you just initiate the <code>ToAddress</code>, however, initiating the lists like this might consume a lot of memory (imagine you have large amount of <code>EmailMessage</code> instances! So, I would suggest to keep them as null, and use <code>null</code> validation to force initiating them when it's needed (like in sender).</p>\n<p>your overall design is good enough, however, you could do this directly :</p>\n<pre><code>public class EmailMessage \n{\n public EmailAddress From { get; set; }\n public IEnumerable<EmailAddress> To { get; set; }\n public IEnumerable<EmailAddress> Cc { get; set; }\n public IEnumerable<EmailAddress> Bcc { get; set; }\n public string Subject { get; set; }\n public string Body { get; set; }\n}\n\npublic interface IEmailProvider\n{\n IEmailServerSetting ServerSettings { get; set; }\n}\n</code></pre>\n<p><code>EmailMessage</code> should contain From(required), To(required), CC(optional),BCC(optional), Subject, and Body as a full model of the message. The reason behind that is that it will be always paired together as requirement to any message, later on, it would be also easier to implement on the database side. using <code>IEnumerable<EmailAddress></code> would open to use any collection that implements <code>IEnumerable</code>. So, it's not restricted to <code>List</code>.</p>\n<p>For <code>IEmailProvider</code> As an email provider should also contain its own settings as requirement. This would make things easier for you, to have each email message with it's own settings. This way, you can send multiple emails from different providers with no extra coding. <code>IOptions</code> is treated independently, but in reality, <code>IOptions</code> won't be useful by itself, and it would only used by <code>EmailProvider</code>, so if we add it to the contract, it'll always be implemented with the interface, this way you forced the provider to always have <code>IOptions</code>. Besides, <code>IOptions</code> should be renamed to something like <code>EmailServerSetting</code> or <code>EmailProviderSetting</code> to relate it to the main implementation. As these are settings and not options. Use <code>IOptions</code> to handle the email optional settings and features that can be managed like sending as text or html, disable/enable attachments, pictures ..etc.</p>\n<p>Also, you need a middle-ware class to wrap things up, and uses <code>SmtpClient</code>. This would give you the advantage of increasing the flexibility of your current work and wrap them under one roof along with ease things up for reusing code (such as <code>MimeMessage</code>, <code>TextPart</code> ..etc.) instead of reimplement it on each new sender. It also would give you the ability to create a collection to store multiple providers if you're going that far. also, you will be able to add new providers, handle them, handle messages, and keep your work scoped.</p>\n<p>Here is how I imagine the final usage :</p>\n<p>Creating a new provider :</p>\n<pre><code>// creating a new email provider \n public class SomeEmailProvider : IEmailProvider\n {\n // only set the settings internally but it's exposed to be readonly\n public EmailServerSetting ServerSettings { get; private set; }\n \n public SomeEmailProvider()\n {\n //set up the server settings\n ServerSettings = new EmailServerSetting \n {\n ServerType = EmailServerType.POP, \n Server = "pop.mail.com",\n Port = 995, \n Encryption = EmailServerEncryption.SSLOrTLS, \n EnableSsl = true\n }; \n }\n // some other related code \n }\n</code></pre>\n<p>now, creating a new mail message and sending it :</p>\n<pre><code>// can be single object or collection \nvar messages = new EmailMessage\n{\n From = new EmailAddress("Test", "test@mail.com"), \n To = new EmailAddress [] {\n new EmailAddress("Test1", "test1@mail.com"), \n new EmailAddress("Test2", "test2@mail.com")\n }, \n Subject = "Testing Subject", \n Body = "Normal Text Body" \n};\n\nusing(var client = new EmailClient(new SomeEmailProvider()))\n{\n client.Options = new EmailClientOptions \n {\n // would send it as plain text \n EnableHtml = false \n };\n \n client.Messages.Add(messages); \n \n client.Send(); \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T01:45:38.240",
"Id": "487342",
"Score": "1",
"body": "Initializing the lists as empty is much more expressive, and introducing null as a possible value complicates the other code. There could be a case where the memory usage is the limiting factor, but this shouldn't be assumed. By introducing the null-checks, the CPU must spend extra cycles when working with an EmailMessage."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-31T20:40:08.220",
"Id": "248729",
"ParentId": "247997",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248729",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T17:57:05.503",
"Id": "247997",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"email",
"asp.net-core"
],
"Title": "Abstracted email sender with content providers"
}
|
247997
|
<p>My objective is to find out on what other subreddit users from r/(subreddit) are posting on; you can see my code below. It works pretty well, but I am curious to know if I could improve it by:</p>
<p>First, restricting my code so that it only considers users only once (i.e. not collect the posting history twice for the same user) and, secondly, by adding a minimum of 5 posts per user before extracting his/her info (i.e. if the user wrote less than 5 posts in his reddit life, my code would not consider him).</p>
<pre><code>import praw
import pandas as data
import datetime as time
reddit = praw.Reddit(client_id = 'XXXX',
client_secret = 'XXXX',
username = 'XXXX',
password = 'XXXX',
user_agent = 'XXXX')
collumns = { "User":[], "Subreddit":[], "Title":[], "Description":[], "Timestamp":[]}
for submission in reddit.subreddit("ENTER SUBREDDIT").new(limit=100):
user = reddit.redditor('{}'.format(submission.author))
for sub in user.submissions.new(limit=100):
collumns["User"].append(sub.author)
collumns["Subreddit"].append(sub.subreddit)
collumns["Title"].append(sub.title)
collumns["Description"].append(sub.selftext)
collumns["Timestamp"].append(sub.created)
collumns_data = data.DataFrame(collumns)
def get_date(Timestamp):
return time.datetime.fromtimestamp(Timestamp)
_timestamp = collumns_data["Timestamp"].apply(get_date)
collumns_data = collumns_data.assign(Timestamp = _timestamp)
collumns_data.to_csv('DataExport.csv')
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T17:57:16.007",
"Id": "247998",
"Score": "3",
"Tags": [
"python",
"web-scraping"
],
"Title": "Scraping reddit using Python"
}
|
247998
|
<p>How can <code>StringEnumeration</code> be changed in the code below into a generic class, so that <code>ConsensusState</code> wouldn't need the <code>JsonConverter</code> attribute to enable instances of the class to be used as if they were serializable enums with associated string values?</p>
<p>I'm using <code>StringEnumeration</code> to allow checking instances of <code>ConsensusState</code> agains <code>string</code> objects in conditional statements or to print them directly to the console as <code>string</code> values, while also be able to use them as properties in <code>Serializable</code> classes. The serialization is made using <code>System.Text.Json.Serialization</code>.</p>
<p>Here are the classes:</p>
<pre><code>/// <summary>Consensus state returned by the server.</summary>
[Serializable]
[JsonConverter(typeof(StringEnumerationConverter<ConsensusState>))]
public class ConsensusState : StringEnumeration
{
/// <summary>Connecting.</summary>
public static readonly ConsensusState Connecting = new ConsensusState("connecting");
/// <summary>Syncing blocks.</summary>
public static readonly ConsensusState Syncing = new ConsensusState("syncing");
/// <summary>Consensus established.</summary>
public static readonly ConsensusState Established = new ConsensusState("established");
private ConsensusState(string value) : base(value) { }
}
/// <summary>JsonConverter used in string enumeration serialization.</summary>
public class StringEnumerationConverter<T> : JsonConverter<T>
{
/// <summary>Read the string value.</summary>
/// <param name="reader">Reader to access the encoded JSON text.</param>
/// <param name="typeToConvert">Type of the object to deserialize.</param>
/// <param name="options">Options for the deserialization.</param>
/// <returns>Underlying string enumeration type.</returns>
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return (T)Activator.CreateInstance(typeof(T), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { reader.GetString() }, null, null);
}
/// <summary>Write the string value.</summary>
/// <param name="writer">Writer to encode the JSON text.</param>
/// <param name="value">Object to serialize.</param>
/// <param name="options">Options for the serialization.</param>
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
writer.WriteStringValue((string)typeof(T).GetProperty("Value").GetValue(value, null));
}
}
/// <summary>Abstract base class used in string enumerations.</summary>
public abstract class StringEnumeration
{
/// <summary>Associated value.</summary>
public string Value { get; set; }
/// <summary>Initializes the enumeration from a string.</summary>
/// <param name="value">The associated value.</param>
public StringEnumeration(string value) { Value = value; }
/// <summary>Implicit conversion to string.</summary>
/// <param name="obj">And StringEnumeration object.</param>
/// <returns>string object.</returns>
public static implicit operator string(StringEnumeration obj)
{
return obj.Value;
}
/// <summary>Get the string associated value.</summary>
/// <returns>string object.</returns>
public override string ToString()
{
return Value;
}
/// <summary>Test whether a StringEnumeration is equal to another object.</summary>
/// <param name="a">StringEnumeration object.</param>
/// <param name="b">Another object.</param>
/// <returns>true if the two objects are equal.</returns>
public static bool operator ==(StringEnumeration a, object b)
{
var other = b as StringEnumeration;
if (other is null)
{
return false;
}
return a.Value == other.Value;
}
/// <summary>Test whether a StringEnumeration is different to other object.</summary>
/// <param name="a">StringEnumeration object.</param>
/// <param name="b">Another object.</param>
/// <returns>true if the two objects are different.</returns>
public static bool operator !=(StringEnumeration a, object b)
{
var other = b as StringEnumeration;
if (other is null)
{
return true;
}
return a.Value != other.Value;
}
/// <summary>Test whether a StringEnumeration is equal to another object.</summary>
/// <param name="obj">Another object.</param>
/// <returns>true if the objects are equal.</returns>
public override bool Equals(object obj)
{
var other = obj as StringEnumeration;
if (other is null)
{
return false;
}
return Value == other.Value;
}
/// <summary>Get the hash code of the associated value.</summary>
/// <returns>An integer value representing the hash of the associated value.</returns>
public override int GetHashCode()
{
return Value.GetHashCode();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The implementation of <code>StringEnumeration</code> below allows a subclass to behave as if it was a string enum, and also has some quality-of-life improvements like being able to specify the string associated value for each field using the attribute <code>JsonStringValue()</code>.</p>\n<pre><code>/// <summary>Attribute to assign the string value of fields in StringEnumeration.</summary>\n[AttributeUsage(AttributeTargets.Field)]\npublic class JsonStringValue : Attribute\n{\n /// <summary>String value.</summary>\n public string Value;\n\n /// <summary>Initializes the Attribute instance to a given value.</summary>\n public JsonStringValue(string value)\n {\n Value = value;\n }\n}\n\n/// <summary>JsonConverter used in string enumeration serialization.</summary>\npublic class StringEnumerationConverter : JsonConverter<StringEnumeration>\n{\n /// <summary>Whether a type is a subclass of <c>StringEnumeration</c>.</summary>\n /// <param name="typeToConvert">Type to check.</param>\n /// <returns>True if is a subclass.</returns>\n public override bool CanConvert(Type typeToConvert)\n {\n return typeof(StringEnumeration).IsAssignableFrom(typeToConvert);\n }\n\n /// <summary>Read the string value.</summary>\n /// <param name="reader">Reader to access the encoded JSON text.</param>\n /// <param name="typeToConvert">Type of the object to deserialize.</param>\n /// <param name="options">Options for the deserialization.</param>\n /// <returns>Underlying string enumeration type.</returns>\n public override StringEnumeration Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)\n {\n var obj = (StringEnumeration)FormatterServices.GetUninitializedObject(typeToConvert);\n obj.Value = reader.GetString();\n return obj;\n }\n\n /// <summary>Write the string value.</summary>\n /// <param name="writer">Writer to encode the JSON text.</param>\n /// <param name="value">Object to serialize.</param>\n /// <param name="options">Options for the serialization.</param>\n public override void Write(Utf8JsonWriter writer, StringEnumeration value, JsonSerializerOptions options)\n {\n writer.WriteStringValue(value);\n }\n}\n\n/// <summary>Abstract base class used in string enumerations.</summary>\npublic abstract class StringEnumeration\n{\n /// <summary>Associated value.</summary>\n public string Value { get; set; }\n\n /// <summary>Initializes all static fields in subclasses.</summary>\n static StringEnumeration()\n {\n var types = typeof(StringEnumeration).Assembly.GetTypes();\n foreach (var type in types)\n {\n if (type.BaseType == typeof(StringEnumeration))\n {\n var fields = type.GetFields(BindingFlags.Public | BindingFlags.Static);\n foreach (var field in fields)\n {\n var attribute = field.GetCustomAttribute<JsonStringValue>();\n var name = attribute is null ? field.Name : attribute.Value;\n var value = (StringEnumeration)FormatterServices.GetUninitializedObject(type);\n value.Value = name;\n field.SetValue(null, value);\n }\n }\n }\n }\n\n /// <summary>Implicit conversion to string.</summary>\n /// <param name="obj">And StringEnumeration object.</param>\n /// <returns>string object.</returns>\n public static implicit operator string(StringEnumeration obj)\n {\n if (obj is null)\n {\n return null;\n }\n return obj.ToString();\n }\n\n /// <summary>Get the string associated value.</summary>\n /// <returns>string object.</returns>\n public override string ToString()\n {\n return Value;\n }\n\n /// <summary>Test whether a StringEnumeration is equal to another object.</summary>\n /// <param name="a">StringEnumeration object.</param>\n /// <param name="b">Another object.</param>\n /// <returns>true if the two objects are equal.</returns>\n public static bool operator ==(StringEnumeration a, object b)\n {\n if (a is null)\n {\n return b is null;\n }\n return !(b is null) && a.Value == b.ToString();\n }\n\n /// <summary>Test whether a StringEnumeration is different to other object.</summary>\n /// <param name="a">StringEnumeration object.</param>\n /// <param name="b">Another object.</param>\n /// <returns>true if the two objects are different.</returns>\n public static bool operator !=(StringEnumeration a, object b)\n {\n return !(a == b);\n }\n\n /// <summary>Test whether a StringEnumeration is equal to another object.</summary>\n /// <param name="obj">Another object.</param>\n /// <returns>true if the objects are equal.</returns>\n public override bool Equals(object obj)\n {\n return this == obj;\n }\n\n /// <summary>Get the hash code of the associated value.</summary>\n /// <returns>An integer value representing the hash of the associated value.</returns>\n public override int GetHashCode()\n {\n return Value.GetHashCode();\n }\n}\n</code></pre>\n<p>This is how to use it:</p>\n<pre><code>/// <summary>Consensus state returned by the server.</summary>\n[Serializable]\n[JsonConverter(typeof(StringEnumerationConverter))]\npublic class ConsensusState : StringEnumeration\n{\n /// <summary>Connecting.</summary>\n [JsonStringValue("connecting")]\n public static ConsensusState Connecting;\n /// <summary>Syncing blocks.</summary>\n [JsonStringValue("syncing")]\n public static ConsensusState Syncing;\n /// <summary>Consensus established.</summary>\n [JsonStringValue("established")]\n public static ConsensusState Established;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T22:01:14.430",
"Id": "248108",
"ParentId": "248000",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T18:24:52.280",
"Id": "248000",
"Score": "3",
"Tags": [
"c#",
"json",
"generics",
"serialization"
],
"Title": "JSON serializable string enum in C# with generic JsonConverter"
}
|
248000
|
<p>I am trying to solve the following <a href="https://www.codewars.com/kata/5f134651bc9687000f8022c4/python" rel="nofollow noreferrer">Codewars kata</a>.</p>
<p>We are given a list as<br />
seq = [0, 1, 2, 2]</p>
<p>We will have to write a function that will, firstly, add elements in the list using the following logic.<br />
if n = 3 and as seq[n]=2, the new list will be seq = [0, 1, 2, 2, 3, 3]<br />
if n = 4 and as seq[n]=3, the new list will be seq = [0, 1, 2, 2, 3, 3, 4, 4, 4]<br />
if n = 5 and as seq[n]=3, the new list will be seq = [0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5] and so on.</p>
<p>Then the function will return the n-th element of the list.</p>
<p>Some elements of the list:<br />
[0, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19,
20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21]</p>
<p>Constraint for Python:<br />
0 <= n <= 2^41</p>
<p>My code runs successfully in my system for any value of n, including n=2^41 (within 2.2s). But it times out in Codewars. Can anyone help me in optimizing my code? Thanks in advance.</p>
<p>My code:</p>
<pre><code>def find(n):
arr = [0, 1, 2, 2]
if n <= 3:
return arr[n]
else:
arr_sum = 5
for i in range(3, n+1):
arr_sum += i * arr[i]
if arr_sum >= n:
x = (arr_sum - n) // i
return len(arr) + arr[i] - (x+1)
else:
arr += [i] * arr[i]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T20:40:19.113",
"Id": "485693",
"Score": "0",
"body": "I think your best bet is deriving a mathematical formula to calculate nth element of the sequence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T06:42:26.980",
"Id": "485704",
"Score": "0",
"body": "@superb rain\nLink to this kata is:\nhttps://www.codewars.com/kata/5f134651bc9687000f8022c4/python"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T06:44:39.627",
"Id": "485705",
"Score": "0",
"body": "@fabrizzio_gz, I have the same feeling... looking for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T16:57:50.017",
"Id": "485740",
"Score": "1",
"body": "@fabrizzio_gz The problem statement ends with *\"tip: you can solve this using smart brute-force\"*. And I just did. Now I can finally look at the code here and perhaps review :-). At first sight it looks similar to mine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T06:23:03.350",
"Id": "485778",
"Score": "0",
"body": "The challenge is not really understandable with the link, I think you omitted the most important part in the construction of the sequence."
}
] |
[
{
"body": "<p>Building the list takes a lot of time. Note that your <code> arr += [i] * arr[i]</code> repeats the same value <code>i</code> over and over again. This can be much compressed by just storing <code>repeat(i, arr[i])</code> instead. This succeeds in about 6 seconds, well under their 12 seconds limit:</p>\n<pre><code>from itertools import chain, repeat\n\ndef find(n):\n if n <= 3:\n return [0, 1, 2, 2][n]\n arr = [[2]]\n arr_sum = 5\n arr_len = 4\n for i, arr_i in enumerate(chain.from_iterable(arr), 3):\n arr_sum += i * arr_i\n if arr_sum >= n:\n x = (arr_sum - n) // i\n return arr_len + arr_i - (x+1)\n arr.append(repeat(i, arr_i))\n arr_len += arr_i\n</code></pre>\n<p>Note that in the <code>n > 3</code> case, we start already with the number 3, appending it twice to the list. Thus of the sequence start <code>[0, 1, 2, 2]</code> we only need <code>[2]</code>, so I start with <code>arr = [[2]]</code> (which is shorter than <code>[repeat(2, 1)]</code>, and <code>chain</code> doesn't mind).</p>\n<hr />\n<p>Alternatively... note that you're extending <code>arr</code> much faster than you're consuming it. For n=2<sup>41</sup>, you grow it to over 51 million elements, but you're actually reading fewer than the first 70 thousand. So you could stop truly extending the list at that point. This succeeds in about 4.7 seconds:</p>\n<pre><code>def find(n):\n arr = [0, 1, 2, 2]\n if n <= 3:\n return arr[n]\n arr_sum = 5\n arr_len = 4\n for i in range(3, n+1):\n arr_sum += i * arr[i]\n if arr_sum >= n:\n x = (arr_sum - n) // i\n return arr_len + arr[i] - (x+1)\n arr_len += arr[i]\n if arr_len < 70_000:\n arr += [i] * arr[i]\n</code></pre>\n<hr />\n<p>And... you can combine the above two improvements, i.e., apply that <code>if arr_len < 70_000:</code> to the <code>repeat</code>-version. That then succeeds in about 4.5 seconds.</p>\n<p>Benchmark results on my PC for n=2<sup>41</sup>:</p>\n<pre><code>Your original: 1.795 seconds\nMy first one: 0.043 seconds (42 times faster)\nMy second one: 0.041 seconds (44 times faster)\nThe combination: 0.026 seconds (69 times faster)\n</code></pre>\n<hr />\n<p>Oh and a style comment: You twice do this:</p>\n<pre><code>if ...:\n return ...\nelse:\n ...\n</code></pre>\n<p>The <code>else</code> and the indentation of all the remaining code are unnecessary and I'd avoid it. I've done so in the above solutions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T06:16:41.920",
"Id": "485898",
"Score": "0",
"body": "Thank you so much for your brilliant optimization suggestions. I am a newbie in the coding world and learnt quite a lot from your solutions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:13:53.150",
"Id": "248044",
"ParentId": "248001",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248044",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T18:38:08.633",
"Id": "248001",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Codewars kata - \"Repetitive Sequence\""
}
|
248001
|
<p>This is in a node and express API. I'm trying to figure out the best way to handle Promises that resolve, but return a 404 response. I have a method which uses node-fetch to make a POST call to update a row in a database. If an invalid profileId is provided, the Promise will resolve even though the response is a 404. I want to figure out the best way to make sure that any status other than OK is considered an error and handled as such.</p>
<p>The method is defined as:</p>
<pre><code>async function updateUserProfileSocketId(profileId, socketId) {
const body = { id: profileId, socketId };
try {
const response = await fetch(`${MATCH_API}/updateUserProfile`, {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
});
if (response.ok) {
return response;
}
throw new Error(`updateUserProfileSocketId Error: unexpected response ${response.statusText}`);
} catch (err) {
console.log(err);
}
return null;
}
</code></pre>
<p>And it is being called as such:</p>
<pre><code>// this is a class method
onInit(socket) {
socket.on('init', (profile) => {
updateUserProfileSocketId(profile.id, socket.id)
.then((response) => {
if (response !== null && response.ok) {
users.push(profile.id);
}
})
.catch((err) => {
socket.conn.close();
console.log(err);
});
});
}
</code></pre>
<p>This gets the job done but I'm not sure if this is the best way to handle this scenario and I'm not sure if this code has any redundancies. I'm from a Java background so looking for someone to help explain the best methods in dealing with such scenarios. Please let me know if you have any suggestions.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T19:36:16.480",
"Id": "248002",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"promise"
],
"Title": "Handling Promise that resolves but returns a 404"
}
|
248002
|
<p>I'm learning really basic java at school but I learn on my own at home.
I've had some experience with simple swing games, but this one exceeds all.
I want any opinion and advice someone may contribute.</p>
<pre><code>public class Display {
private JFrame frame;
private Canvas canvas;
private String title;
private int width, height;
public Display(String title, int width, int height) {
this.title = title;
this.width = width;
this.height = height;
createDisplay();
}
private void createDisplay() {
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
frame.add(canvas);
frame.pack();
}
public Canvas getCanvas() {
return canvas;
}
public void addKeyListner(KeyAdapter ka) {
canvas.addKeyListener(ka);
canvas.requestFocus();
}
}
public class Shape {
private int[] coords;
private int color;
private int pos;
public Shape(Shape shape) {
this(shape.coords, shape.color, shape.pos);
}
public Shape(int[] coords, int color) {
this(coords, color, 0);
}
public Shape(int[] coords, int color, int pos) {
this.coords = coords;
this.color = color;
this.pos = pos;
}
public void rotate() {
pos++;
if (pos == 4) pos = 0;
}
public int color() {
return color;
}
public int position() {
return pos;
}
public int[] coordinates() {
return coords;
}
}
public class Game implements Runnable {
private Display display;
private Board board;
private int width, height;
private String title;
private boolean running = false;
private Thread gameThread;
private int tickTime = 400;
private BufferStrategy bs;
private Graphics g;
private KeyKeeper keyKeeper;
public Game(String title, int width, int height) {
this.width = width;
this.height = height;
this.title = title;
}
private void initTick() {
while (running) {
try {
gameThread.sleep(tickTime);
} catch (InterruptedException ie) {}
tick();
}
}
private void init() {
display = new Display(title, width, height);
board = new Board(width - 100, height);
keyKeeper = new KeyKeeper();
display.addKeyListner(keyKeeper);
}
private void tick() {
board.tick();
}
private void render() {
bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//Draw Here!
//background
Tetris.drawBackground(g, board, 0, 0);
// board
Tetris.drawBoard(g, board, 0, 0);
//shape
Tetris.drawShape(g, board);
//End Drawing!
bs.show();
g.dispose();
}
public void run() {
init();
while (running) {
render();
}
stop();
}
public synchronized void start() {
if (running) {
return;
}
running = true;
gameThread = new Thread(this);
gameThread.start();
initTick();
}
public synchronized void stop() {
if (!running) {
return;
}
running = false;
try {
gameThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
class KeyKeeper extends KeyAdapter {
@Override
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_LEFT) {
board.moveShape(-1, 0);
} else if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {
board.moveShape(1, 0);
} else if (ke.getKeyCode() == KeyEvent.VK_DOWN) {
board.moveShape(0, 1);
} else if (ke.getKeyCode() == KeyEvent.VK_UP) {
board.hardDown();
}
else if (ke.getKeyCode() == KeyEvent.VK_SPACE)
board.rotateShape();
}
}
}
public class Board {
public static int width, height;
public static int tx, ty;
public static int xts;
public static int yts;
private int[][] boardCoor;
private int[][] coords;
private Shape noShape;
private Point shapeCoorPoint;
private boolean[] shapeUsed;
private int shapeCounter;
public Board(int width, int height) {
this.width = width;
this.height = height;
init();
}
private void init() {
tx = 12;
ty = 24;
xts = width / tx;
yts = height / ty;
boardCoor = new int[tx][ty];
for (int i = 0; i < ty; i++) {
for (int j = 0; j < tx; j++) {
boardCoor[j][i] = 7;
}
}
coords = new int[][]{
{0, 2, 4, 6},// I
{1, 2, 3, 4},// Z
{0, 2, 3, 5},// S
{0, 2, 3, 4},// T
{0, 2, 4, 5},// L
{1, 3, 5, 4},// J
{2, 3, 4, 5} // O
};
shapeCoorPoint = new Point();
shapeUsed = new boolean[]{false, false, false, false, false, false, false};
shapeCounter = 0;
initShape();
}
public int[][] getBoard() {
return boardCoor;
}
public Shape getShape() {
return noShape;
}
public Point getShapeCoorPoint() {
return shapeCoorPoint;
}
private void initShape() {
boolean changeShape = true;
int n;
while (changeShape) {
n = (int) (Math.random() * 7);
if (!shapeUsed[n]) {
noShape = new Shape(coords[n], n);
shapeUsed[n] = true;
shapeCounter++;
changeShape = false;
}
}
if (shapeCounter == 7) {
shapeUsed = new boolean[]{false, false, false, false, false, false, false};
shapeCounter = 0;
}
shapeCoorPoint.move(tx / 2 - 1, 0);
}
public void tick() {
if (Tetris.canFall(this)) {
shapeCoorPoint.translate(0, 1);
} else {
Tetris.update(this);
clearLines();
initShape();
}
}
public boolean moveShape(int dx, int dy) {
//dy=1 - down
//dx=-1 - right
//dx=1 - left
// ~~~ strategy ~~~
// create an instance point, then, check -
//if legal, translate the shape point.
Point instancePoint = new Point(shapeCoorPoint);
instancePoint.translate(dx, dy);
if (Tetris.isLegal(boardCoor, noShape, instancePoint)) {
shapeCoorPoint.translate(dx, dy);
return true;
}
return false;
}
public void hardDown() {
boolean stop;
do {
stop = moveShape(0, 1);
} while (stop);
}
public boolean rotateShape() {
//~~~ strategy ~~~
//create an instance shape, then, check -
//if legal, rotate
Shape instanceShape = new Shape(noShape);
instanceShape.rotate();
if (Tetris.isLegal(boardCoor, instanceShape, shapeCoorPoint)) {
noShape.rotate();
return true;
}
return false;
}
private void clearLines() {
boolean isFilled;
for (int row = 0; row < ty; row++) {
isFilled = true;
//check the first tile of the each rank
for (int col = 0; col < tx; col++) {
if (boardCoor[col][row] == 7) {
isFilled = false;
col = tx;
}
}
if (isFilled) {
for (int i = 0; i < tx; i++) {
for (int j = row; j > 0; j--) {
boardCoor[i][j] = boardCoor[i][j - 1];
boardCoor[i][j - 1] = 7;
}
}
}
}
}
}
public class Tetris {
//~~~graphic drawings~~~
public static void drawBackground(Graphics g, Board board, int x, int y) {
g.setColor(Color.black);
g.fillRect(x, y, board.width, board.height);
g.setColor(Color.white);
g.drawRect(x, y, board.width, board.height);
g.setColor(Color.gray);
for (int i = 1; i < board.ty; i++) {
g.drawLine(x, y + i * board.yts,
x + board.width, y + i * board.yts);
}
for (int i = 1; i < board.tx; i++) {
g.drawLine(x + i * board.xts, y,
x + i * board.xts, y + board.height);
}
}
public static void drawBoard(Graphics g, Board board, int x, int y) {
int[][] boardCoor = board.getBoard();
int c;
Color[] colors = new Color[]{
Color.red, Color.blue, Color.orange, Color.magenta,
Color.cyan, Color.green, Color.yellow, Color.black};
for (int i = 0; i < board.ty; i++) {
for (int j = 0; j < board.tx; j++) {
c = boardCoor[j][i];
g.setColor(colors[c]);
g.fillRect(x + j * board.xts + 1, y + i * board.yts + 1,
board.xts - 1, board.yts - 1);
}
}
}
public static void drawShape(Graphics g, Board board) {
Point point = board.getShapeCoorPoint();
Shape shape = board.getShape();
int[] coords = shape.coordinates();
int pos = shape.position();
int c = shape.color();
Color[] colors = new Color[]{
Color.red, Color.blue, Color.orange, Color.magenta,
Color.cyan, Color.green, Color.yellow, Color.black};
g.setColor(colors[c]);
int[] arr;
for (int i = 0; i < coords.length; i++) {
arr = getXY(coords[i], pos, point);
g.fillRect(
(arr[0]) * board.xts + 1, (arr[1]) * board.yts + 1,
board.xts - 1, board.yts - 1);
}
}
// ~~~game rules~~~
public static boolean canFall(Board board) {
return canFall(board.getBoard(), board.getShape(), board.getShapeCoorPoint());
}
public static boolean canFall(int[][] boardCoor, Shape shape, Point point) {
return canFall(boardCoor, shape.coordinates(), shape.position(), point);
}
public static boolean canFall(int[][] boardCoor, int[] coords, int pos, Point point) {
int[] arr;
for (int i = 0; i < coords.length; i++) {
arr = getXY(coords[i], pos, point);
if (arr[1] == Board.ty - 1 || boardCoor[arr[0]][arr[1] + 1] != 7) {
return false;
}
}
return true;
}
public static boolean isLegal(Board board) {
return isLegal(board.getBoard(), board.getShape(), board.getShapeCoorPoint());
}
public static boolean isLegal(int[][] boardCoor, Shape shape, Point point) {
return isLegal(boardCoor, shape.coordinates(), shape.position(), point);
}
public static boolean isLegal(int[][] boardCoor, int[] coords, int pos, Point point) {
int[] arr;
for (int i = 0; i < coords.length; i++) {
arr = getXY(coords[i], pos, point);
if (arr[1] >= Board.ty || arr[1] < 0 ||
arr[0] < 0 || arr[0] >= Board.tx ||
boardCoor[arr[0]][arr[1]] != 7) {
return false;
}
}
return true;
}
//~~~technical functions~~~
public static void update(Board board) {
update(board.getBoard(), board.getShape(), board.getShapeCoorPoint());
}
public static void update(int[][] boardCoor, Shape shape, Point point) {
update(boardCoor, shape.coordinates(), shape.color(), shape.position(), shape, point);
}
public static void update(int[][] boardCoor, int[] coords, int color, int pos, Shape shape, Point point) {
int[] arr;
for (int i = 0; i < coords.length; i++) {
arr = getXY(coords[i], pos, point);
boardCoor[arr[0]][arr[1]] = color;
}
}
private static int[] getXY(int value, int pos, Point point) {
int[] arr = new int[2];
if (pos == 0) {
arr[0] = value % 2 + point.x;
arr[1] = value / 2 + point.y;
return arr;
} else if (pos == 1) {
arr[0] = 2 - value / 2 + point.x;
arr[1] = 1 + value % 2 + point.y;
return arr;
} else if (pos == 2) {
arr[0] = 1 - value % 2 + point.x;
arr[1] = 3 - value / 2 + point.y;
return arr;
} else {
arr[0] = value / 2 - 1 + point.x;
arr[1] = 2 - value % 2 + point.y;
return arr;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have some suggestions for your code.</p>\n<h2>Always add curly braces to <code>loop</code> & <code>if</code></h2>\n<p>In my opinion, it's a bad practice to have a block of code not surrounded by curly braces; I saw so many bugs in my career related to that, if you forget to add the braces when adding code, you break the logic / semantic of the code.</p>\n<h2>Extract the expression to variables when used multiple times.</h2>\n<p>In your code, you can extract the expression into variables; this will make the code shorter and easier to read.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>if (ke.getKeyCode() == KeyEvent.VK_LEFT) {\n board.moveShape(-1, 0);\n} else if (ke.getKeyCode() == KeyEvent.VK_RIGHT) {\n board.moveShape(1, 0);\n} else if (ke.getKeyCode() == KeyEvent.VK_DOWN) {\n board.moveShape(0, 1);\n} else if (ke.getKeyCode() == KeyEvent.VK_UP) {\n board.hardDown();\n} else if (ke.getKeyCode() == KeyEvent.VK_SPACE)\n board.rotateShape();\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>int keyCode = ke.getKeyCode();\nif (keyCode == KeyEvent.VK_LEFT) {\n board.moveShape(-1, 0);\n} else if (keyCode == KeyEvent.VK_RIGHT) {\n board.moveShape(1, 0);\n} else if (keyCode == KeyEvent.VK_DOWN) {\n board.moveShape(0, 1);\n} else if (keyCode == KeyEvent.VK_UP) {\n board.hardDown();\n} else if (keyCode == KeyEvent.VK_SPACE) {\n board.rotateShape();\n}\n</code></pre>\n<p>There are other cases like this one in your code, I suggest you do the same thing for them (<code>new Dimension(width, height)</code>, ect).</p>\n<h2>Always uses a copy of the array when returning it or receiving it</h2>\n<p>Most of the containers (Map, List, Arrays) in java are mutable (exception for some implementations). If you return an instance in a getter, any class that have access to it can modify the collection; you lose the control of your own data this way. To overcome that, you need to create a new copy of the array / convert the collection to an implementation that cannot be modified and then, return the value.</p>\n<p>Always try to keep control over your own data, never share the collections directly with the others and when receiving a collection / array, copy the data to your internal collections.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int[] coordinates() {\n return coords;\n}\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>public int[] coordinates() {\n return Arrays.copyOf(coords, coords.length);\n}\n</code></pre>\n<p>They are multiple ways to <a href=\"https://stackoverflow.com/questions/5785745/make-copy-of-an-array\">copy an array</a>.</p>\n<h2>Uses getters instead of static variables</h2>\n<p>In the <code>Board</code> class, you use static variables to share the values; this is a bug and a bad habit, since the static variables will be shared across instances (if you create multiple instances of the board, the values will be changed in all instances). Instead, I suggest that you hide the data and create getters for them.</p>\n<h2>Replace the <code>for</code> loop with an enhanced 'for' loop</h2>\n<p>In your code, you don’t actually need the index provided by the loop, you can the enhanced version.</p>\n<p><strong>Before</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code> for (int i = 0; i < coords.length; i++) {\n //[...]\n }\n</code></pre>\n<p><strong>After</strong></p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int coord : coords) {\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T00:27:43.610",
"Id": "248013",
"ParentId": "248003",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T20:13:08.257",
"Id": "248003",
"Score": "4",
"Tags": [
"java",
"game",
"tetris"
],
"Title": "Basic java Tetris game"
}
|
248003
|
<p>I've written some F# code to handle commands in the context of event sourcing which works along the lines below:</p>
<ul>
<li>Read Events from a specific event store stream</li>
<li>Build the current state in the given business / domain context accordingly to the events that has just been read right above</li>
<li>Decide new events based on the current state + read events + a given command</li>
<li>Write the event that have been newly "decided" to a given stream</li>
<li>If there is a version mismatch (leading to a failure when it comes to writing the new events to the given stream), there a resilience policy to retry the whole process a certain number of times with a given number of intervals in between (akin to what you can find in Polly).</li>
</ul>
<p>There is basically two different implementations, a "standard" one and another one validating if some particular events are considered "not okay" slash errors, which makes the handle function returning a <code>Result<'Ok, 'Error></code>.</p>
<p>Note: The terminology is a bit off but I've found the terms in quite a few places in the "Event Sourcing world".</p>
<p>The code below works, but it's super-duper redundant and it does feel overly bloated, bear in mind that what is below has already been refactored a couple of times, but I'm not too sure about how I can take this code to a whole new level of clarity.</p>
<p>Not only the code is a bit hard to wrap my own head around, it actually also pains me to see that some paths leading to nowhere cannot be prevented upfront in a declarative way, things like:</p>
<pre><code>| None, Ok _
| Some _, Error _ -> NotImplementedException() |> raise
</code></pre>
<p>So what I'm asking is some help to refactor the code below into something easier to reason about, and if possible how can I avoid to process cases that aren't supposed to happen by design.</p>
<hr />
<p><code>CommandHandlerUtils.fs</code>:</p>
<pre><code>[<RequireQualifiedAccess>]
module My.EventSourcing.CommandHandlerUtils
open System
open FSharpPlus.Data
open My.FSharp.Resilience
open My.Infra.EventStore.Common
let internal getInvalidValueException _ _ = NotImplementedException()
let defaultWrongVersionRetryIntervals = Intervals.Seconds [1; 2; 4]
let createStreamKey aggregateName commandMessage =
{ FriendlyName = aggregateName; FriendlyId = commandMessage.AggregateId.ToString() }
/// Build the "history" states based on data available in the "history" events with the reBuild function
/// Note: "history": means "current" here.
let buildHistoryState reBuild (historyEvents: EventRead<'Data, 'Metadata> list) =
historyEvents
|> List.map (fun eventRead -> eventRead.Data)
|> reBuild
/// Read the available events (ascending versions) from a event store and build the current state on top of them.
/// Both values (ie. events and state) are returned.
let buildHistory reBuild (readEvents: ReadEvents<'Data, 'Metadata>) streamKey =
async {
let! historyEvents = readEvents streamKey (All Forward)
let historyState = buildHistoryState reBuild historyEvents
return (historyEvents, historyState)
}
/// Save the given events into an event store stream and return a result containing either:
/// - the events successfully written to the event store stream
/// - the error in case the operation has failed
let saveEvents (tryWriteEvents: TryWriteEvents<_, _, _>) historyEvents events streamKey =
async {
let eventsToWrite =
events
|> List.map (fun event ->
{ Causation = Root
Data = event
Metadata = () })
|> NonEmptyList.ofList
let writeVersion =
if List.isEmpty historyEvents
then Expected 1
else Expected ((List.last historyEvents).StreamVersion + 1)
return! tryWriteEvents streamKey writeVersion eventsToWrite
}
</code></pre>
<hr />
<p><code>GenericCommandHandler.fs</code>:</p>
<pre><code>[<RequireQualifiedAccess>]
module My.EventSourcing.GenericCommandHandler
open FSharpPlus.Data
open My.FSharp.Resilience
open My.Infra.EventStore.Common
// 1. Build history state from readEvents
// 2. Decide new events based on command message + history state
// 3. If any events:
// - a. Try Save / Write new events to given stream (ie. command message) into the Event Store
// - b. Return events + state if writing events did work, throw exception otherwise
// 4. If no events: Return events + state
// Note: default intervals => 4 attempts (1st attempt + 3 retries)
let handleWith aggregateName decide build reBuild readEvents tryWriteEvents commandMessage wrongVersionRetryIntervals =
let handleCore =
async {
let streamKey = CommandHandlerUtils.createStreamKey aggregateName commandMessage
let! (historyEventReads, historyState) = CommandHandlerUtils.buildHistory reBuild readEvents streamKey
let events = decide commandMessage.Command historyState
if List.isEmpty events then
return (None, events, historyState)
else
let state = build historyState events
let! eventWritesResult =
CommandHandlerUtils.saveEvents tryWriteEvents historyEventReads events streamKey
return (Some eventWritesResult, events, state)
}
let acceptOutcome last _ (eventWritesResult, events, state) =
match eventWritesResult with
| None
| Some (Ok _) -> Return (events, state)
| Some (Error (UnexpectedStreamVersion _)) when not last -> TryAgain
| Some (Error e) -> e |> WriteEventsException |> raise
Retry.onValue acceptOutcome CommandHandlerUtils.getInvalidValueException wrongVersionRetryIntervals handleCore
let handle aggregateName decide build reBuild readEvents tryWriteEvents commandMessage =
handleWith
aggregateName
decide
build
reBuild
readEvents
tryWriteEvents
commandMessage
CommandHandlerUtils.defaultWrongVersionRetryIntervals
</code></pre>
<hr />
<p><code>ValidatingGenericCommandHandler.fs</code>:</p>
<pre><code>[<RequireQualifiedAccess>]
module My.EventSourcing.ValidatingGenericCommandHandler
open System
open My.FSharp.Resilience
open My.Infra.EventStore.Common
// 1. Build history state from readEvents
// 2. Decide new events based on command message + history state
// 3. If any events:
// - A. Events are wrapped with Ok
// - a. Try Save / Write new events to given stream (ie. command message) into the Event Store
// - b. Return events + state if writing events did work, throw exception otherwise
// - B. Return events wrapped with Error
// 4. If no events: Return (no) events + history state wrapped with Ok
// Note: default intervals => 4 attempts (1st attempt + 3 retries)
let handleWith aggregateName decide build reBuild readEvents tryWriteEvents commandMessage wrongVersionRetryIntervals =
let handleCore =
async {
let streamKey = CommandHandlerUtils.createStreamKey aggregateName commandMessage
let! (historyEventReads, historyState) = CommandHandlerUtils.buildHistory reBuild readEvents streamKey
let eventsResult = decide commandMessage.Command historyState
match eventsResult with
| Error events ->
return (None, Error events, historyState)
| Ok events when List.isEmpty events ->
return (None, Ok events, historyState)
| Ok events ->
let state = build historyState events
let! writeEventsResult =
CommandHandlerUtils.saveEvents tryWriteEvents historyEventReads events streamKey
return (Some writeEventsResult, Ok events, state)
}
let acceptOutcome last _ (eventWritesResult, eventsResult, state) =
match eventWritesResult, eventsResult with
| None, Error events -> events |> Error |> Return
| Some (Ok _), Ok events -> (events, state) |> Ok |> Return
| Some (Error (UnexpectedStreamVersion _)), Ok _ when not last -> TryAgain
| Some (Error e), Ok _ -> e |> WriteEventsException |> raise
| None, Ok _
| Some _, Error _ -> NotImplementedException() |> raise
Retry.onValue acceptOutcome CommandHandlerUtils.getInvalidValueException wrongVersionRetryIntervals handleCore
let handle aggregateName decide build reBuild readEvents tryWriteEvents message =
handleWith
aggregateName
decide
build
reBuild
readEvents
tryWriteEvents
message
CommandHandlerUtils.defaultWrongVersionRetryIntervals
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T09:09:22.773",
"Id": "486523",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T10:07:03.787",
"Id": "486526",
"Score": "0",
"body": "@Zeta let me get this straight, shall I post another answer with the code above and details the changes compared to the accepted answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T10:10:16.577",
"Id": "486527",
"Score": "0",
"body": "[My question is about 3. Posting a self-answer + Give credit to any other users who may have helped you]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T15:47:48.090",
"Id": "486568",
"Score": "1",
"body": "Yes, that would be fine. Alternatively, you can ask for a new review on your new code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T16:19:08.957",
"Id": "486571",
"Score": "0",
"body": "Alright, thanks for clarifying the situation."
}
] |
[
{
"body": "<p>Using types to represent both successful results and error scenarios is generally a very good move, and F# certainly makes it easier to do this than other languages. As I think you've found though, it can get quite complicated as the number of scenarios grows! You're on the right track, but I'm going to suggest one thing you can do to simplify the approach and make it clearer in a couple of places.</p>\n<p>As you've identified, there are a couple of branches of code that in theory should not happen:</p>\n<ol>\n<li>The command is not valid but we still end up writing events to the store.</li>\n<li>The command is valid and produces events but we do not attempt to write anything to the store.</li>\n</ol>\n<p>These "impossible" branches stem from the <code>handleCore</code> function, from which we're returning a value that represents more options than are theoretically possible. To put it another way, the knowledge about what can actually happen inside this function is not being captured in its return type. We can tidy things up a great deal by defining the return value from the command handlers in a more formal way. I'll focus on the validating command handler since it's the more complex of the two:</p>\n<pre><code>type CommandHandlerResult =\n /// The command was not valid or could not be applied to the existing state.\n | CommandValidationFailed of error:ValidationError\n /// The command was applied successfully to the existing state, producing\n /// zero or more events and a new state.\n | CommandApplied of newEvents:Event list * newState:State\n /// The command was valid, but there was an error when writing new events to the store.\n | FailedToWriteEvents of error:WriteError\n</code></pre>\n<p>This is obviously fairly verbose, but that's kind of the point, because their intent is now much clearer than the nested combinations of Ok/Error/Some/None, which ultimately gave us more flexibility than we wanted or needed. This already should make some difference to the readability of the <code>handleCore</code> function:</p>\n<pre><code>let handleCore =\n async {\n // ...\n match decide commandMessage.Command historyState with\n | Error error -> return CommandValidationFailed error\n // Command was applied, but no change was required, so no need to\n // write any events because there are none!\n | Ok [] -> return CommandApplied ([], historyState)\n | Ok newEvents ->\n // Attempt to write the new events to the store.\n let! writeResult =\n CommandHandlerUtils.saveEvents tryWriteEvents historyEventReads newEvents streamKey\n match writeResult with\n | Error error -> return StateUpdateFailed error\n | Ok _ ->\n let newState = build historyState events\n return CommandApplied (newEvents, newState)\n }\n</code></pre>\n<p>Note that the return value from the <code>decide</code> function is no longer passed through as part of the <code>handleCore</code> result, we've instead transformed it completely into a <code>CommandHandlerResult</code> and have therefore captured the outcome of <code>handleCore</code> much more clearly. The real improvement in readability comes when handling the result of <code>handleCore</code> in the <code>acceptOutcome</code> function:</p>\n<pre><code>let acceptOutcome last _ (commandHandlerResult: CommandHandlerResult) =\n match commandHandlerResult with\n | CommandValidationFailed error -> error |> Error |> Return\n | CommandApplied (events, state) -> (events, state) |> Ok |> Return\n | FailedToWriteEvents (UnexpectedStreamVersion _) when not last -> TryAgain\n | FailedToWriteEvents writeError -> writeError |> WriteEventsException |> raise\n</code></pre>\n<p>In my opinion this is now much easier to understand. There are no "impossible" routes and you don't really need to know a great deal about what the command handler is doing because the outcome is encoded in a very descriptive way by its return type.</p>\n<p>Generally speaking, defining return types as discriminated unions can be a great way to deal with complex error/failure scenarios where <code>Option<'T></code> or <code>Result<'T, 'TFailure></code> are not quite flexible or descriptive enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T00:09:04.597",
"Id": "486489",
"Score": "1",
"body": "Thanks a ton! This is really insightful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T00:18:42.477",
"Id": "486490",
"Score": "1",
"body": "I'd add that your answer is probably the best code review I've ever got on this particular SE. Again, thank you so much for your time and effort!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T21:34:35.573",
"Id": "248388",
"ParentId": "248004",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248388",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T20:45:01.310",
"Id": "248004",
"Score": "7",
"Tags": [
"f#"
],
"Title": "Refactoring of two command handler implementations with F# in the context of event sourcing"
}
|
248004
|
<p><strong>Problem statement</strong> :
Given strings S and T, find the minimum (contiguous) substring W of S, so that T is a subsequence of W.</p>
<p>If there is no such window in S that covers all characters in T, return the empty string "". If there are multiple such minimum-length windows, return the one with the left-most starting index.</p>
<p>Example:
<code>Input: S = "abcdebdde", T = "bde" Output: "bcde" Explanation: "bcde" is the answer because it occurs before "bdde" which has the same length. "deb" is not a smaller window because the elements of T in the window must occur in order.</code></p>
<pre><code>public class MinimumWindowSubsequence {
public String minWindow(String s, String t) {
if (t.length() == 1) {
int index = s.indexOf(t.charAt(0));
return index == -1 ? "" : s.substring(index, index + 1);
}
int minLength = Integer.MAX_VALUE;
String result = "";
for (int leftPointer = 0; leftPointer < s.length(); leftPointer++) {
char currentChar = s.charAt(leftPointer);
if (currentChar == t.charAt(0)) {
int counter = 1;
int rightPointer = leftPointer + 1;
while (rightPointer < s.length()) {
if (counter < t.length() && s.charAt(rightPointer) == t.charAt(counter)) {
counter++;
if (counter == t.length()) {
int currentLength = rightPointer - leftPointer;
if (currentLength < minLength) {
result = s.substring(leftPointer, rightPointer + 1);
minLength = currentLength;
}
break;
}
}
rightPointer++;
}
}
}
return result;
}
}
</code></pre>
<p>My code works but it does not pass the tests on LC which is fine with me. Can you please give me feedback on the code and help me cross-check the runtime of this algorithm? I think it is linear run-time.</p>
<p>Thanks,</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T06:12:55.757",
"Id": "486003",
"Score": "0",
"body": "It seems me testing is available only for premium accounts, could you add some other string tests to your post ?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T21:28:22.990",
"Id": "248005",
"Score": "2",
"Tags": [
"java"
],
"Title": "Minimum Window Subsequence LeetCode Solution"
}
|
248005
|
<p>I made a scraper for Steam that get different info about a Steam game, such as the price, the specs and the supported platforms. The reason I made this was because I have a super slow laptop, so looking at many games would take a long time :)</p>
<p>Some things I would like to improve is have better error handling, as the web is a messy place and not all the pages are going to be the same.</p>
<p>Another thing I was thinking about doing is having better data management, such as using classes and objects for each game instead of storing all the values in a dictionary, that would make for simpler and maybe even shorter code.</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.firefox.options import Options
from sys import exit
games = {}
x = 0
# ask for games
while True:
if x == 0:
game = input('Type the game you want to find here: ')
else:
game = input('Type the game you want to find here (or enter nothing to continue): ')
if not game:
break
games[game] = {}
x += 1
# configure browser
print('Starting Browser')
firefox_options = Options()
firefox_options.headless = True
browser = webdriver.Firefox(options=firefox_options, service_log_path='/tmp/geckodriver.log')
print('Retrieving website')
browser.get('https://store.steampowered.com/')
for a_game in games:
print('Finding info for "' + a_game + '"')
# input & click
print('Waiting for page to load')
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#store_nav_search_term"))).send_keys(a_game)
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#search_suggestion_contents>a"))).click()
print('Navigating to game page')
# if age-restricted:
try:
browser.find_element_by_css_selector('.agegate_birthday_selector')
age_query = input('"' + a_game + '" is age-restricted, do you want to continue? y/n ')
if age_query != 'y':
print('Abort')
exit()
select = Select(browser.find_element_by_id('ageYear'))
select.select_by_value('2000')
browser.find_element_by_css_selector('a.btnv6_blue_hoverfade:nth-child(1)').click()
except NoSuchElementException:
pass
print('Waiting for game page to load')
# name of game
games[a_game]['name'] = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, '.apphub_AppName'))).text
# supported platforms
print('Retrieving supported platforms')
mac = False
linux = False
try:
browser.find_element_by_css_selector('div.game_area_purchase_game_wrapper:nth-child(1) > div:nth-child(1) > div:nth-child(2) > '
'span:nth-child(2)')
mac = True
except NoSuchElementException:
pass
try:
browser.find_element_by_css_selector('div.game_area_purchase_game_wrapper:nth-child(1) > div:nth-child(1) > div:nth-child(2) > '
'span:nth-child(3)')
linux = True
except NoSuchElementException:
pass
if mac and linux:
games[a_game]['platform'] = 'all'
elif mac:
games[a_game]['platform'] = 'mac'
elif linux:
games[a_game]['platform'] = 'linux'
else:
games[a_game]['platform'] = 'windows'
# price
print('Retrieving price')
discounted = False
try:
games[a_game]['price'] = browser.find_element_by_css_selector('div.game_purchase_action:nth-child(4) > div:nth-child(1) > div:nth-child(1)').text
except NoSuchElementException:
try:
games[a_game]['before_price'] = browser.find_element_by_class_name('discount_original_price').text
games[a_game]['after_price'] = browser.find_element_by_class_name('discount_final_price').text
except NoSuchElementException:
try:
games[a_game]['price'] = 'FREE'
except NoSuchElementException:
games[a_game]['bundle_price'] = browser.find_element_by_css_selector('div.game_purchase_action_bg:nth-child(2) > div:nth-child(1)')
except Exception:
games[a_game]['price'] = 'Error: Unable to get price'
# system requirements
print('Retrieving system requirements')
games[a_game]['specs'] = browser.find_element_by_css_selector('.game_area_sys_req').text
# close browser
print('Finished Retrieving data, closing browser \n')
print('********************************************')
browser.close()
for each_game in games.keys():
print('GAME: ' + games[each_game]['name'].upper())
# printing supported platforms
if games[each_game]['platform'] == 'all':
print('Supported Platforms: Windows, Mac and Linux')
elif games[each_game]['platform'] == 'mac':
print('Supported Platforms: Windows and Mac')
elif games[each_game]['platform'] == 'linux':
print('Supported Platforms: Windows and Linux')
else:
print('Supported Platforms: Windows Only')
print('\n')
# printing price
try:
print('Price: Discounted ' + games[each_game]['after_price'] + ' from ' + games[each_game]['before_price'])
except KeyError:
print('Price: ' + games[each_game]['price'])
except Exception:
print('Bundled Price: ' + games[each_game]['bundle_price'])
print('\n')
# printing system requirements
print('System Requirements: \n')
print('-------------------------------- \n')
print(games[each_game]['specs'])
print('--------------------------------')
input('Press enter to continue ')
print('Finished Successfully')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T15:54:01.013",
"Id": "487046",
"Score": "0",
"body": "That's a lot of effort, but you're making things more difficult for yourself by scraping the website instead of using API :("
}
] |
[
{
"body": "<h1>Break up logic into functions</h1>\n<p>Having separate functions for each of the following steps will make the code easier to read.</p>\n<ul>\n<li>Get game names</li>\n<li>Scrape game information</li>\n<li>Display game information</li>\n</ul>\n<h1>Guard your script's entry point</h1>\n<p>I'd recommend moving the script execution flow under an <code>if __name__ == "__main__":</code> guard. Doing this allows you to import the functions from this file into other files without running the script.</p>\n<h1>Avoid using <code>sys.exit()</code> for control flow</h1>\n<p>Calling <code>sys.exit()</code> shuts down the Python interpreter, which makes any code that calls it difficult to test. You should instead refactor the script so it terminates normally for all recoverable cases.</p>\n<p>For example, if the user doesn't want information for an age-restricted game, skip it and move on to the next game in the list. I think this would make for a better user experience anyway, because if we <code>exit()</code> we don't get to process the other remaining games in the list.</p>\n<h1>Supported platforms should be a list</h1>\n<p>In determining and printing supported platforms for a game, you have booleans <code>mac</code> and <code>linux</code> which are eventually translated to a string taking one of <code>all</code>, <code>mac</code>, <code>linux</code>, <code>windows</code>:</p>\n<pre class=\"lang-python prettyprint-override\"><code>if mac and linux:\n games[a_game]['platform'] = 'all' # windows, mac, linux\nelif mac:\n games[a_game]['platform'] = 'mac' # windows, mac\nelif linux:\n games[a_game]['platform'] = 'linux' # windows, linux\nelse:\n games[a_game]['platform'] = 'windows' # windows\n</code></pre>\n<p>I think it makes more sense to model this as a list, e.g. <code>["windows", "mac"]</code> so it's more explicit what platforms are supported. This will also save you from writing extra if/elif/else logic when printing these out.</p>\n<h1>Flat is better than nested</h1>\n<p>The nested try/except blocks in the price retrieval stage is very difficult to read.</p>\n<p>If you delegate the price retrieval to a function, you can structure the logic so it is flat instead of nested, like in the following pseudocode:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def get_price() -> str:\n element = find_element_for_bundle_price()\n if element:\n return element.text\n\n element = find_element_for_non_discounted_price()\n if element:\n return element.text\n\n element = find_element_for_discounted_price()\n if element:\n return element.text\n\n # If we don't find a price on the page, it's free?\n # Actually this is not always true, but for this example\n # we'll assume this is the case.\n return 'FREE'\n</code></pre>\n<h1>Misuse of exception handling</h1>\n<p>The script is catching <code>KeyError</code> and <code>Exception</code> to handle printing out three different types of prices: bundle, discounted, and standard. This is arguably a misuse of exception handling, especially since catching the general <code>Exception</code> is rarely a good idea because it can hide other errors you weren't expecting. Plus it's not needed here; we can just use an if/elif/else:</p>\n<pre class=\"lang-python prettyprint-override\"><code>game_dict = games[each_game]\nif 'bundle_price' in game_dict:\n # print bundle price\nelif 'before_price' in game_dict and 'after_price' in game_dict:\n # print discounted price\nelse:\n # print standard price\n</code></pre>\n<h1>Data management</h1>\n<p>You mentioned that you were thinking about having classes or objects for each game instead of using a dictionary. I think this is a good idea. It might not make the code shorter, but it would definitely improve the code's readability.</p>\n<p>A good candidate for this would be a simple data container like <a href=\"https://docs.python.org/3/library/typing.html#typing.NamedTuple\" rel=\"nofollow noreferrer\"><code>typing.NamedTuple</code></a>. As @MaartenFabré suggested in the comments, <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\"><code>dataclasses.dataclass</code></a> is another good choice for a data container like this.</p>\n<h1>Unhandled edge cases</h1>\n<p>The following search queries will result in the script timing out:</p>\n<ul>\n<li><p>Any search query that returns no suggestions on Steam. This could be something like a game that doesn't exist (yet), e.g. <code>"funkytown"</code>, or a non-empty string consisting only of whitespace, e.g. <code>" "</code>.</p>\n</li>\n<li><p>Any search query where the first suggestion is a Steam Package, e.g. <code>"the witcher 3 wild hunt game of the year"</code>.</p>\n</li>\n<li><p>Any search query where the first suggestion is a Steam Bundle, e.g. <code>"monkey island collection"</code>.</p>\n</li>\n</ul>\n<p>I mentioned this earlier, but the script incorrectly assumes that if a price is not displayed on the page, then the game is free. But there are unreleased games on Steam where the developer hasn't set a price, and at the same time they have not classified it as "free" or as a "free-to-play" game ("Spirit of Glace" is one concrete example I found). The price to display in this case should be something like "TBD" or "Unknown".</p>\n<p>Fortunately, and as a way of introducing the next section, there's an API we can use to distinguish between free and not free. This API exposes an <code>is_free</code> field that is <code>true</code> when a game is free or free-to-play. If you jump to the end of this review you can see how it's getting retrieved in my example script.</p>\n<h1>Prefer APIs to scraping</h1>\n<p>With APIs, data retrieval is faster -- and often orders of magnitude faster than scraping with Selenium. With APIs, data extraction is easier since the format of the response is often JSON.</p>\n<p>I always make a point of mentioning this whenever scraping comes up because the potential time and effort savings can be huge. Spend some time searching for an official API, or an unofficial API that's documented. If nothing turns up, poke around with an HTTP/S traffic inspector like Fiddler or Chrome DevTools and see if you can find any promising unofficial APIs. If at last you can't find anything, fall back to scraping as a last resort.</p>\n<p>In this case, there is actually an <a href=\"https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI\" rel=\"nofollow noreferrer\">unofficial Steam Store API</a> that's available. To use it we need the Steam App ID or Steam Package ID of the item we're in interested in, but we can get that from the API that powers the search suggestion drop-down menu, <code>https://store.steampowered.com/search/suggest</code>.</p>\n<h1>Example script using API</h1>\n<p>The following is an example script using the unofficial Steam Store API.</p>\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport re\nimport json\nimport requests\nfrom enum import Enum\nfrom bs4 import BeautifulSoup # type: ignore\nfrom typing import Any, Dict, List, Optional, NamedTuple, Union\n\nSEARCH_SUGGEST_API = "https://store.steampowered.com/search/suggest"\nAPP_DETAILS_API = "https://store.steampowered.com/api/appdetails"\nPACKAGE_DETAILS_API = "https://store.steampowered.com/api/packagedetails"\n\n\nclass Platform(Enum):\n WINDOWS = "windows"\n MAC = "mac"\n LINUX = "linux"\n\n def __str__(self) -> str:\n return str(self.value)\n\n\nclass Price(NamedTuple):\n initial: int # price in cents\n final: int # price in cents\n\n\nclass SteamGame(NamedTuple):\n app_id: int\n name: str\n platforms: List[Platform]\n is_released: bool\n is_free: bool\n price: Optional[Price]\n pc_requirements: str\n\n def __str__(self) -> str:\n if self.is_free:\n price = "Free"\n elif self.price:\n final = f"${self.price.final / 100}"\n if self.price.initial == self.price.final:\n price = final\n else:\n price = f"{final} (previously ${self.price.initial / 100})"\n else:\n price = "TBD"\n\n platforms = ", ".join(str(p) for p in self.platforms)\n is_released = "Yes" if self.is_released else "No"\n\n return "\\n".join(\n (\n f"Name: {self.name}",\n f"Released: {is_released}",\n f"Supported Platforms: {platforms}",\n f"Price: {price}",\n "",\n "PC Requirements:",\n self.pc_requirements,\n )\n )\n\n\nclass SteamBundle(NamedTuple):\n bundle_id: int\n name: str\n price: Price\n application_names: List[str]\n\n def __str__(self) -> str:\n final = f"${self.price.final / 100}"\n if self.price.initial == self.price.final:\n price = final\n else:\n price = f"{final} (without bundle: ${self.price.initial / 100})"\n\n return "\\n".join(\n (\n f"Name: {self.name}",\n f"Price: {price}",\n "",\n "Items included in this bundle:",\n *(f" - {name}" for name in self.application_names),\n )\n )\n\n\nclass SteamPackage(NamedTuple):\n package_id: int\n name: str\n platforms: List[Platform]\n is_released: bool\n price: Optional[Price]\n application_names: List[str]\n\n def __str__(self) -> str:\n if self.price:\n final = f"${self.price.final / 100}"\n if self.price.initial == self.price.final:\n price = final\n else:\n initial = f"${self.price.initial / 100}"\n price = f"{final} (without package: {initial})"\n else:\n price = "TBD"\n\n platforms = ", ".join(str(p) for p in self.platforms)\n is_released = "Yes" if self.is_released else "No"\n\n return "\\n".join(\n (\n f"Name: {self.name}",\n f"Released: {is_released}",\n f"Supported Platforms: {platforms}",\n f"Price: {price}",\n "",\n "Items included in this package:",\n *(f" - {name}" for name in self.application_names),\n )\n )\n\n\nSteamItem = Union[SteamGame, SteamBundle, SteamPackage]\n\n\ndef deserialize_bundle_data(encoded_bundle_json: str) -> Any:\n return json.loads(re.sub(r"&quot;", '"', encoded_bundle_json))\n\n\ndef extract_app_ids(bundle_data: Dict[str, Any]) -> List[int]:\n return [\n app_id\n for item in bundle_data["m_rgItems"]\n for app_id in item["m_rgIncludedAppIDs"]\n ]\n\n\ndef lookup_app_names(\n session: requests.Session, app_ids: List[int]\n) -> List[str]:\n app_names = []\n for app_id in app_ids:\n params = {"appids": app_id, "filters": "basic"}\n response = session.get(APP_DETAILS_API, params=params)\n response.raise_for_status()\n\n app_names.append(response.json()[str(app_id)]["data"]["name"])\n\n return app_names\n\n\ndef extract_bundle_price(bundle_data: Dict[str, Any]) -> Price:\n total_price = sum(\n item["m_nFinalPriceInCents"] for item in bundle_data["m_rgItems"]\n )\n total_price_with_bundle_discount = sum(\n item["m_nFinalPriceWithBundleDiscount"]\n for item in bundle_data["m_rgItems"]\n )\n\n return Price(total_price, total_price_with_bundle_discount)\n\n\ndef extract_package_information(\n package_id: int, package_data: Dict[str, Any]\n) -> SteamPackage:\n return SteamPackage(\n package_id=package_id,\n name=package_data["name"],\n platforms=[p for p in Platform if package_data["platforms"][str(p)]],\n is_released=not package_data["release_date"]["coming_soon"],\n price=Price(\n package_data["price"]["initial"], package_data["price"]["final"]\n ),\n application_names=[app["name"] for app in package_data["apps"]],\n )\n\n\ndef get_package(session: requests.Session, package_id: str) -> SteamPackage:\n params = {"packageids": package_id}\n response = session.get(PACKAGE_DETAILS_API, params=params)\n response.raise_for_status()\n\n return extract_package_information(\n int(package_id), response.json()[package_id]["data"]\n )\n\n\ndef extract_requirements_text(requirements_html: str) -> str:\n soup = BeautifulSoup(requirements_html, "html.parser")\n return "\\n".join(tag.get_text() for tag in soup.find_all("li"))\n\n\ndef extract_game_information(game_data: Dict[str, Any]) -> SteamGame:\n price_overview = game_data.get("price_overview")\n price = (\n Price(price_overview["initial"], price_overview["final"])\n if price_overview\n else None\n )\n\n requirements = game_data["pc_requirements"]\n minimum = extract_requirements_text(requirements["minimum"])\n recommended_html = requirements.get("recommended")\n recommended = (\n extract_requirements_text(recommended_html)\n if recommended_html\n else None\n )\n\n minimum_requirements = f"[Minimum]\\n{minimum}"\n if recommended:\n recommended_requirements = f"[Recommended]\\n{recommended}"\n pc_requirements = (\n minimum_requirements + "\\n\\n" + recommended_requirements\n )\n else:\n pc_requirements = minimum_requirements\n\n return SteamGame(\n app_id=game_data["steam_appid"],\n name=game_data["name"],\n platforms=[p for p in Platform if game_data["platforms"][str(p)]],\n is_released=not game_data["release_date"]["coming_soon"],\n is_free=game_data["is_free"],\n price=price,\n pc_requirements=pc_requirements,\n )\n\n\ndef get_game(session: requests.Session, app_id: str) -> SteamGame:\n params = {"appids": app_id}\n response = session.get(APP_DETAILS_API, params=params)\n response.raise_for_status()\n\n return extract_game_information(response.json()[app_id]["data"])\n\n\ndef get_game_information(games: List[str]) -> Dict[str, Optional[SteamItem]]:\n game_to_info = {}\n\n with requests.Session() as session:\n for game in games:\n params = {"term": game, "f": "games", "cc": "US", "l": "english"}\n response = session.get(SEARCH_SUGGEST_API, params=params)\n response.raise_for_status()\n\n # get first search suggestion\n result = BeautifulSoup(response.text, "html.parser").find("a")\n\n if result:\n bundle_id = result.get("data-ds-bundleid")\n package_id = result.get("data-ds-packageid")\n app_id = result.get("data-ds-appid")\n\n if bundle_id:\n name = result.find("div", class_="match_name").get_text()\n bundle_data = deserialize_bundle_data(\n result["data-ds-bundle-data"]\n )\n app_ids = extract_app_ids(bundle_data)\n app_names = lookup_app_names(session, app_ids)\n price = extract_bundle_price(bundle_data)\n\n info: Optional[SteamItem] = SteamBundle(\n bundle_id=int(bundle_id),\n name=name,\n price=price,\n application_names=app_names,\n )\n elif package_id:\n info = get_package(session, package_id)\n elif app_id:\n info = get_game(session, app_id)\n else:\n info = None\n else:\n info = None\n\n game_to_info[game] = info\n\n return game_to_info\n\n\ndef display_game_information(\n game_information: Dict[str, Optional[SteamItem]]\n) -> None:\n arrow = " =>"\n for game_query, game_info in game_information.items():\n result_header = f"{game_query}{arrow}"\n query_result = (\n game_info if game_info else f"No results found for {game_query!r}."\n )\n result = "\\n".join(\n (\n result_header,\n "-" * (len(result_header) - len(arrow)),\n "",\n str(query_result),\n "\\n",\n )\n )\n\n print(result)\n\n\nif __name__ == "__main__":\n games = [\n "slay the spire",\n "civ 6",\n "funkytown",\n "path of exile",\n "bless unleashed",\n "the witcher 3 wild hunt game of the year",\n "divinity source",\n "monkey island collection",\n "star wars squadrons",\n "spirit of glace",\n ]\n game_info = get_game_information(games)\n display_game_information(game_info)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T18:37:57.383",
"Id": "487057",
"Score": "0",
"body": "Why use NamedTuple instead of dataclasses.datadclass?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T19:26:22.403",
"Id": "487060",
"Score": "0",
"body": "@MaartenFabré Absolutely `dataclass` is another good option, which I can mention along with `NamedTuple`. The data containers (e.g. `SteamGame`) in my example script don't require mutability since we're just loading data into them once and printing them out later, so I chose to make them `NamedTuple`s. I know that `dataclass`es can also fulfill the same purpose via `dataclass(frozen=True)`, but whenever the situation calls for a simple, lightweight, immutable by default container, I generally prefer `NamedTuple`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T02:34:30.840",
"Id": "248589",
"ParentId": "248006",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248589",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T22:18:13.440",
"Id": "248006",
"Score": "5",
"Tags": [
"python",
"web-scraping",
"selenium"
],
"Title": "Game scraper for Steam"
}
|
248006
|
<p>While I have never had to swap two files I have always wondered if there was command for swapping two files and recently I decided to see if there was one. Eventually I found out that there wasn't one and as a result I decided to create one.</p>
<p>Here is the code: <code>main.cc</code></p>
<pre><code>#include <iostream>
#include <filesystem>
#include <cstring>
#include <cassert>
static auto print_help() -> void {
std::cout << "Usage: swap [file1] [file2]\n";
std::cout << "swaps the contents of file1 and file2\n";
std::cout << "use swap --help to print this message\n";
}
static auto validate_files(const std::filesystem::path& file1_path, const std::filesystem::path& file2_path) -> void {
{
/* check if file exists */
const auto file1_exists = std::filesystem::exists(file1_path);
const auto file2_exists = std::filesystem::exists(file2_path);
const auto exists = file1_exists && file2_exists;
if (!exists) {
if (!file1_exists) std::cerr << "cannot find file " << file1_path << '\n';
if (!file2_exists) std::cerr << "cannot find file " << file2_path << '\n';
exit(EXIT_FAILURE);
}
}
{
if (file1_path == file2_path) {
std::cerr << "swaping the same two files does nothing\n";
exit(EXIT_SUCCESS);
}
}
}
static auto get_temp_filename(char* template_name) -> void {
/* tmpnam_s does not work on linux */
#if defined(WIN32) || defined(_WIN32)
errno_t err = tmpnam_s(template_name, L_tmpnam);
assert(!err);
#else
int err = mkstemp(template_name);
assert(err != -1);
#endif
}
int main(int argc, char** argv) {
std::ios::sync_with_stdio(false);
switch (argc) {
case 2: {
/* convert the second arg to upper case */
std::transform(argv[1],
argv[1] + strlen(argv[1]),
argv[1],
::toupper);
if (!strcmp(argv[1], "--HELP")) {
print_help();
return EXIT_SUCCESS;
}
else {
std::cerr << "Invalid args see --help for usage\n";
return EXIT_FAILURE;
}
}
case 3:
break;
default: {
std::cerr << "Invalid args see --help for usage\n";
return EXIT_FAILURE;
}
}
const auto file1_path = std::filesystem::path{ argv[1] };
const auto file2_path = std::filesystem::path{ argv[2] };
validate_files(file1_path, file2_path);
char temp_filename[L_tmpnam] = "XXXXXX";
get_temp_filename(temp_filename);
const auto temp_filepath = std::filesystem::path{ temp_filename };
/* move-swap the files instead of copy-swaping */
/* renaming a file is the same as moving it */
std::filesystem::rename(file1_path, temp_filepath);
std::filesystem::rename(file2_path, file1_path);
std::filesystem::rename(temp_filepath, file2_path);
}
</code></pre>
<p>Here is an example of usage:</p>
<pre><code>swap doc1.txt doc2.txt
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T03:17:52.747",
"Id": "485700",
"Score": "2",
"body": "What would the expected behavior be if there is a path included in one or both filenames? How would you handle the two files being on different drives? Or if both files are on one file (that is not the current working directory), as the temp file would then be on a different drive?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T15:59:57.350",
"Id": "485734",
"Score": "0",
"body": "I don't know what the behavior would be but what do you do supposed I should do about it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T18:16:22.623",
"Id": "485745",
"Score": "2",
"body": "Expected `#ifdef RENAME_EXCHANGE renameat2(...) #else` to use the actual system call if possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T21:43:32.577",
"Id": "485758",
"Score": "1",
"body": "See https://man7.org/linux/man-pages/man2/rename.2.html for `RENAME_EXCHANGE` to \"atomically exchange oldpath and newpath\". Linux is common enough to be worth taking advantage of that feature that's existed since Linux 3.15."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T22:25:20.043",
"Id": "485761",
"Score": "0",
"body": "the Windows version of `std::filesystem::rename` uses https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw with the option `MOVEFILE_COPY_ALLOWED` which allows for moving files across different drives. However, the Linux version of `std::filesystem::rename` just uses `std::rename` which does not allow moving files across different drives."
}
] |
[
{
"body": "<ul>\n<li><p><code>file1_path == file2_path</code> surely tells that paths refer to the same file. However, even if <code>file1_path != file2_path</code> they still may refer to the same file.</p>\n</li>\n<li><p><code>file1_exists = std::filesystem::exists(file1_path);</code> introduces a TOC-TOU race condition. The file may exist at the time of test, yet disappear by the time of use. See the next bullet.</p>\n</li>\n<li><p><code>std::filesystem::rename</code> may fail. You call it tree times. If the second, or third call fails (with an exception!), the filesystem ends up not exactly in a state one would expect. Use a <code>noexcept</code> overload, test the <code>error_code</code> after each call, and roll back all actions prior to failure. That would also automagically take care of the nonexistent paths.</p>\n</li>\n<li><p>Do not <code>assert</code>. It is only good to catch bugs, not the runtime problems. In the production code (compiled with <code>-DNDEBUG</code>) it does nothing, and your program wouldn't detect an <code>mkstemp</code> failure.</p>\n</li>\n<li><p>The program silently does nothing if called with, say, 4 arguments. It also takes so much effort if called with 2 arguments. Calling <code>print_help()</code> any time <code>argc != 3</code> is much more straightforward.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T23:22:50.207",
"Id": "248010",
"ParentId": "248007",
"Score": "11"
}
},
{
"body": "<p>I'm guessing the 'question' is asking for code critiques. If I'm wrong about that, please be gentle.. LOL</p>\n<p>My first impression is the <em>readability</em> of main.\nThe large argument parsing switch is hiding the more important logic..</p>\n<p>Maybe make it easier to read (string objects and case insensitive compares?)..\nEven better: relegate to a housekeeping helper method.</p>\n<p>(Also: Sometimes <em>simplistic</em> is OK. If you don't receive two filename arguments you could immediately spit out the help, rather than telling user to explicitly ask for help.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-28T13:26:26.923",
"Id": "248545",
"ParentId": "248007",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248010",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T22:29:51.420",
"Id": "248007",
"Score": "6",
"Tags": [
"c++",
"file",
"file-system"
],
"Title": "A utility to swap two files"
}
|
248007
|
<p>I have a working logon for a WinForms Project. I use the <code>program.cs</code> file to launch the login form. I am not so sure there isn't a better way of implementing this.</p>
<p>Here is my program.cs file:</p>
<pre><code> using System;
using System.Windows.Forms;
using WindowsFormsApp.Presenters;
using WindowsFormsApp.Views;
using Autofac;
using DbContexts;
using Serilog;
namespace WindowsFormsApp
{
internal static class Program
{
public static IContainer Container { get; private set; }
public static string UserName { get; set; }
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
var builder = new ContainerBuilder();
builder.Register(c => new MyContext());
Container = builder.Build();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
.WriteTo.RollingFile("log-{Date}.txt")
.CreateLogger();
Log.Information("Application Started");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var loginForm = new LoginForm();
var results = loginForm.ShowDialog();
if (results == DialogResult.Cancel)
System.Environment.Exit(1);
while (results != DialogResult.OK)
{
results = loginForm.ShowDialog();
if (results == DialogResult.Cancel)
System.Environment.Exit(1);
}
var mainFormView = new MainFormView();
mainFormView.Tag = new MainFormPresenter(mainFormView);
Application.Run(mainFormView);
}
}
}
</code></pre>
<p>Any suggestions or comments are welcome.</p>
|
[] |
[
{
"body": "<p>The first thing I noticed. Code duplication. Whenever you see this your first thought should be,"There has to be a better way.".</p>\n<p>In this case assign the result variable to <code>DialogResult.None</code> then just show the dialog inside the loop:</p>\n<pre><code>var result = DialogResult.None;\nwhile(result != DialogResult.OK)\n{\n result = loginForm.ShowDialog();\n if(result == DialogResult.Cancel)\n {\n System.Environment.Exit(1);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T23:45:29.237",
"Id": "248012",
"ParentId": "248008",
"Score": "2"
}
},
{
"body": "<ol>\n<li>You have a public static property UserName that can be set by anyone, anywhere in your code. You didn't detail the usage of this property.</li>\n</ol>\n<ul>\n<li><p>If it's the logon form that should update it and it will never update again, have your Program class set this field.</p>\n</li>\n<li><p>If it's another class that updates this field, maybe this property doesn't belong here.</p>\n</li>\n</ul>\n<ol start=\"2\">\n<li><p>You have some code that is duplicated, so there must be a way to do better.</p>\n</li>\n<li><p>From my point view, you are doing many different things in your Main method, maybe you could put these operations in separate methods : Init, Login, Start.</p>\n</li>\n<li><p><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement\" rel=\"nofollow noreferrer\">Use using</a></p>\n</li>\n<li><p>You put the Presenter for MainForm in the Tag Property, which I think belongs to a specific property. That way the MainForm can control who has access to it, otherwise any object that has an access to the MainForm can recover the Tag and therefore the Presenter. Another problem is that the Tag property is an object, so you will have to convert it every time you want to use it.</p>\n</li>\n</ol>\n<p>So, all together that would become :</p>\n<pre><code>using System;\nusing System.Windows.Forms;\nusing WindowsFormsApp.Presenters;\nusing WindowsFormsApp.Views;\nusing Autofac;\nusing DbContexts;\nusing Serilog;\n\nnamespace WindowsFormsApp\n{\n internal static class Program\n {\n public static IContainer Container { get; private set; }\n public static string UserName { get; private set; }\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n private static void Main()\n {\n Init();\n Login();\n Start();\n }\n\n private void Init()\n {\n var builder = new ContainerBuilder();\n builder.Register(c => new MyContext()); \n Container = builder.Build();\n\n Log.Logger = new LoggerConfiguration()\n .MinimumLevel.Debug()\n .WriteTo.Console()\n .WriteTo.RollingFile("log-{Date}.txt")\n .CreateLogger();\n Log.Information("Application Started");\n\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n }\n\n private void Login()\n {\n using (loginForm = new LoginForm())\n {\n var results DialogResult.None;\n do\n {\n results = loginForm.ShowDialog();\n if (results == DialogResult.Cancel)\n System.Environment.Exit(1);\n } while (results != DialogResult.OK);\n //Since we logged on correctly, we can update UserName (I guess)\n UserName = loginForm.ValidatedUserName;\n }\n }\n \n private void Start()\n {\n using (var mainFormView = new MainFormView())\n {\n mainFormView.Presenter = new MainFormPresenter(mainFormView);\n Application.Run(mainFormView);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T09:18:45.140",
"Id": "248028",
"ParentId": "248008",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248028",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T22:38:40.417",
"Id": "248008",
"Score": "7",
"Tags": [
"c#",
"authentication",
"winforms"
],
"Title": "WinForm Logon Best Practices"
}
|
248008
|
<p>I'm new to using python and wanted to know how I could improve my program. I'm using the Luhn algorithm, the beginning numbers of the credit cards, and the number of digits in the credit card.</p>
<pre><code>from cs50 import get_string
import re
import sys
number = get_string("NUMBER: ")
check = []
if (len(number)) not in (13,15,16):
print("INVALID")
print(len(number))
sys.exit(1)
for i in range(len(number)): # for the length of the string,
if i%2 == (-2+len(number))%2: # if a counter is modulo 1
digits = str(int(number[i])*2) #obtains the value of the multiplication
for j in range(len(digits)):
check.append(int(digits[j]))
else:
check.append(int(number[i]))
total = str(sum(check))
if re.search("0$", total):
if re.search("^3(4|7)", number):
print("AMEX")
elif number[0] == str(4):
print("VISA")
elif re.search("^5(1|2|3|4|5)", number):
print("MASTERCARD")
else:
print("INVALID")
</code></pre>
|
[] |
[
{
"body": "<p>Your program would benefit from breaking up logic into functions. This also eliminates the global variables involved.</p>\n<pre><code>if i%2 == (-2+len(number))%2\n</code></pre>\n<p>This line is strange and not immediately obvious what it's doing. A reversed iteration would be easier to understand.</p>\n<pre><code>import re\n\ndef luhn_digit(digit,double):\n if double:\n doubled = digit*2\n return doubled-9 if doubled>9 else doubled\n else:\n return digit\n\ndef is_valid_luhn(card):\n check_digit = int(card[-1])\n luhn_sum = sum([\n luhn_digit(int(digit),i%2==0)\n for i,digit in enumerate(reversed(card[:-1]))\n ])\n total = check_digit+luhn_sum\n return total%10==0\n\ndef is_valid_card(card):\n return (\n len(card) in (13,15,16) and\n is_valid_luhn(card)\n )\n\ndef get_card_type(card):\n if not is_valid_card(card):\n return "INVALID"\n if re.search("^3(4|7)", card):\n return "AMEX"\n if card[0] == str(4):\n return "VISA"\n if re.search("^5(1|2|3|4|5)", card):\n return "MASTERCARD"\n return "INVALID"\n\nprint(get_card_type(input("NUMBER: ")))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T01:44:07.267",
"Id": "248171",
"ParentId": "248011",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248171",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-16T23:35:28.023",
"Id": "248011",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "checks validity of credit card in python (cs50 pset6)"
}
|
248011
|
<p>I'm an experienced python 3 programmer but I've recently started focusing more on JS to make client side applications for my website. So I'm not too familiar with advanced level techniques, best practices, etc in JavaScript. I'll post all the code here (HTML/CSS/JS) so you can run it, although the primary thing I'd like some pointers on is the JS. I'm not too focused on framerate/performance (as you'll see I unnecessarily compute certain things more than once per frame for convenience), although any optimizations are welcome. I'm more concerned with having an accurate simulation that works no matter what. I've tested it quite a bit, but there could be edge cases that I missed or other problems with my code. This uses the p5.js library to help draw the graphics. Your help is appreciated! Ok, first the HTML.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.js"></script>
<script src="pendulumSim.js"></script>
<link rel="stylesheet" type="text/css" href="pendulumSim.css">
<meta charset="utf-8" />
<title>Pendulum Simulation</title>
</head>
<body>
<div class="main-div">
<div id="gui-div">
<h4 style="font-weight: normal;">Pendulum Simulation</h4><hr>
<div class="interface-section">
<button class="sbtn" id="pause-btn" onclick="togglePause();">Pause</button>
<button class="sbtn" id="trace-btn" onclick="toggleTrace();">Disable trace</button>
<button class="sbtn" id="guides-btn" onclick="toggleGuides();">Disable guides</button>
<button class="sbtn" id="mode-btn" onclick="toggleModes();">Switch to double pendulum</button>
<button class="sbtn" id="time-reset-btn" onclick="resetSimTime();">Reset timer</button>
</div>
<div class="interface-section">
<div class="widget-container">
<p>This simulation assumes g=1000 and every pixel is one meter. Click in the pendulum area to set its angle.</p>
</div>
<div id="single-pendulum-widgets">
<div class="widget-container">
<label for="pen1-mass-slider">Mass</label>
<input type="range" id="pen1-mass-slider" min="1" max="10" value="1" onchange="pendulum.setMass(parseInt(this.value));"></input><br>
<label for="pen1-length-slider">String length</label>
<input type="range" id="pen1-length-slider" min="100" max="250" value="220" onchange="pendulum.setCordLength(parseInt(this.value));"></input>
</div>
</div>
<div id="double-pendulum-widgets" style="display:none;">
<div class="widget-container">
<label for="pen2-mass1-slider">Mass 1</label>
<input type="range" id="pen2-mass1-slider" min="1" max="10" value="1" onchange="pendulum.setMass1(parseInt(this.value));"></input><br>
<label for="pen2-mass2-slider">Mass 2</label>
<input type="range" id="pen2-mass2-slider" min="1" max="10" value="1" onchange="pendulum.setMass2(parseInt(this.value));"></input><br>
<label for="pen2-length1-slider">String length 1</label>
<input type="range" id="pen2-length1-slider" min="50" max="125" value="110" onchange="pendulum.setCordLength1(parseInt(this.value));"></input><br>
<label for="pen2-length2-slider">String length 2</label>
<input type="range" id="pen2-length2-slider" min="50" max="125" value="110" onchange="pendulum.setCordLength2(parseInt(this.value));"></input>
</div>
</div>
</div>
</div>
<div id="canvas-div"></div>
</div>
</body>
</html>
</code></pre>
<p>CSS:</p>
<pre><code>body {
margin: 0;
padding: 0;
color: white;
font-family: arial;
overflow: hidden;
}
#canvas-div {
border: 2px solid black;
padding: 0;
margin: 0;
}
#gui-div {
text-align: center;
flex: 1;
height: 300px;
overflow: auto;
background-color: #0b3954;
border-radius: 15px;
}
.sbtn {
width: 90%;
height: 10%;
font-size: 90%;
border-radius: 10px;
margin: 5px;
margin-top: 10px;
margin-bottom: 10px;
background-color: #eef5f6;
border: 2px solid #aaa;
}
.sbtn:hover {
background-color: #d5f0f4;
border: 2px solid #000;
}
.main-div {
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: stretch;
}
hr {
border-color: black;
}
.interface-section {
color: black;
background-color: white;
border-radius: 15px;
margin: 10px;
}
::-webkit-scrollbar {
width: 10px;
}
::-webkit-scrollbar-track {
/* box-shadow: inset 0 0 5px grey; */
background: #0b3954;
border-radius: 5px;
}
::-webkit-scrollbar-thumb {
background: gray;
border-radius: 5px;
}
.widget-container {
padding: 10px;
border: 2px solid black;
border-radius: 10px;
}
</code></pre>
<p>Finally, JavaScript:</p>
<pre><code>const colors = {
"black": p5.prototype.createVector(0, 0, 0),
"blue": p5.prototype.createVector(0, 0, 255),
};
const g = 1000;
const realisticG = 9.81;
const timeStep = 1 / 60;
const simpsonsRuleApproximation = (f, a, b, steps=100) => {
if (a > b) return -simpsonsRuleApproximation(f, b, a, steps);
if (steps % 2 !== 0) steps++;
let sum = 0, h = (b-a)/steps;
for (let j=2; j<=steps; j+=2) {
sum += f( a + h * (j-2) ) + 4 * f( a + h * (j-1) ) + f( a + h * j );
}
return h/3 * sum;
}
class Pendulum {
constructor(pivotX, pivotY, massDiameter=40, cordLength=150, mass=1, initialTheta=0, cordColor=colors.black, massColor=colors.blue) {
this.theta = initialTheta - HALF_PI;
this.theta0 = this.theta;
this.lastTheta = this.theta;
this.cordLength = cordLength;
this.massDiameter = massDiameter;
this.mass = mass;
this.cordColor = cordColor;
this.massColor = massColor;
this.pivotPos = createVector(pivotX, pivotY);
this.massPos = p5.Vector.add(this.pivotPos, createVector(sin(this.theta), cos(this.theta)).mult(this.cordLength));
this.lastPos = this.massPos;
this.vel = 0;
this.acc = 0;
this.factor = -g / this.cordLength;
}
getKineticEnergy() {
const tanVel = this.getTangentialVelocity();
return 0.5 * this.mass * tanVel * tanVel;
}
getPotentialEnergy() {
return this.mass * g * abs(this.massPos.y - this.pivotPos.y + this.cordLength - this.massDiameter / 2);
}
getPeriod() {
// return TWO_PI * sqrt(this.cordLength / g); / this only works for small angles. in other words it's useless.
// instead, compute the period using the elliptic integral from here: https://en.wikipedia.org/wiki/Pendulum_(mathematics)#Arbitrary-amplitude_period
// this is adjusted because here g is not equal to 9.8
const k = sin(this.theta0 / 2);
return 4 * sqrt(this.cordLength / g) * simpsonsRuleApproximation((u) => 1 / sqrt(1 - k * k * pow(sin(u), 2)), 0, HALF_PI);
}
getMass() {
return this.mass;
}
getTheta() {
return this.theta;
}
getRotationalVelocityAboutPivot() {
return (this.theta - this.lastTheta) / timeStep;
}
getTangentialVelocity() {
return this.cordLength * this.getRotationalVelocityAboutPivot();
}
getCordLength() {
return this.cordLength;
}
setCordLength(cordLength) {
this.cordLength = cordLength;
this.setTheta(this.theta+HALF_PI);
}
setMass(mass) {
this.mass = mass;
}
setTheta(theta, reset=false) {
this.theta = theta - HALF_PI;
this.theta0 = this.theta;
this.lastTheta = this.theta;
if (reset) this.vel = 0;
secondarySurf.background(255);
this.lastPos = null;
}
draw() {
let radius = this.massDiameter / 2;
push();
strokeWeight(2);
stroke(this.massColor.x, this.massColor.y, this.massColor.z);
fill(this.massColor.x, this.massColor.y, this.massColor.z);
if (trace && this.lastPos !== null) {
secondarySurf.line(this.lastPos.x, this.lastPos.y, this.massPos.x, this.massPos.y);
}
this.lastPos = this.massPos; // don't put this under the trace condition
if (showGuides) {
dottedLine(this.pivotPos.x, this.pivotPos.y, this.pivotPos.x, this.pivotPos.y + this.cordLength + radius, 20);
dottedLine(this.pivotPos.x - this.cordLength + radius, this.pivotPos.y + this.cordLength + radius,
this.pivotPos.x + this.cordLength + radius, this.pivotPos.y + this.cordLength + radius, 30);
}
stroke(this.cordColor.x, this.cordColor.y, this.cordColor.z);
line(this.pivotPos.x, this.pivotPos.y, this.massPos.x, this.massPos.y);
circle(this.massPos.x, this.massPos.y, this.massDiameter);
if (showGuides) {
fill(this.massColor.x, this.massColor.y, this.massColor.z, 128);
if (this.theta<0) {
arc(this.pivotPos.x, this.pivotPos.y, 2*this.massDiameter, 2*this.massDiameter, HALF_PI, -this.theta+HALF_PI);
} else {
arc(this.pivotPos.x, this.pivotPos.y, 2*this.massDiameter, 2*this.massDiameter, -this.theta+HALF_PI, HALF_PI);
}
}
pop();
}
update() {
this.lastTheta = this.theta;
if (!paused) {
this.acc = this.factor * sin(this.theta);
this.vel += this.acc * timeStep;
this.theta = (this.theta + this.vel * timeStep) % TWO_PI;
}
this.massPos = p5.Vector.add(this.pivotPos, createVector(sin(this.theta), cos(this.theta)).mult(this.cordLength)); // in case the user clicks
this.draw();
}
}
class DoublePendulum {
constructor(topPivotX, topPivotY, mass1Diameter=40, mass2Diameter=40, cordLength1=75, cordLength2=75, mass1=1, mass2=1, cordColor=colors.black, massColor=colors.blue) {
this.theta1 = -HALF_PI; this.theta2 = -HALF_PI;
this.cordLength1 = cordLength1; this.cordLength2 = cordLength2;
this.mass1Diameter = mass1Diameter; this.mass2Diameter = mass2Diameter;
this.mass1 = mass1; this.mass2 = mass2;
this.cordColor = cordColor;
this.massColor = massColor;
this.pivotPos = createVector(topPivotX, topPivotY);
this.mass1Pos = p5.Vector.add(this.pivotPos, createVector(sin(this.theta1), cos(this.theta1)).mult(this.cordLength1));
this.mass2Pos = p5.Vector.add(this.mass1Pos, createVector(sin(this.theta2), cos(this.theta2)).mult(this.cordLength2));
this.lastPos = this.mass2Pos;
this.vel1 = 0, this.vel2 = 0;
this.acc1 = 0, this.acc2 = 0;
this.factor = -g / this.cordLength;
}
calculateAccelerations() {
const partialDen = (2 * this.mass1 + this.mass2 - this.mass2 * cos(2 * this.theta1 - 2 * this.theta2));
this.acc1 = (-g * (2 * this.mass1 + this.mass2) * sin(this.theta1) - this.mass2 * g * sin(this.theta1 - 2 * this.theta2) - 2 * sin(this.theta1 - this.theta2) * this.mass2 * (this.vel2 * this.vel2 * this.cordLength2 + this.vel1 * this.vel1 * this.cordLength1 * cos(this.theta1 - this.theta2))) / (this.cordLength1 * partialDen);
this.acc2 = (2 * sin(this.theta1 - this.theta2) * (this.vel1 * this.vel1 * this.cordLength1 * (this.mass1 + this.mass2) + g * (this.mass1 + this.mass2) * cos(this.theta1) + this.vel2 * this.vel2 * this.cordLength2 * this.mass2 * cos(this.theta1 - this.theta2))) / (this.cordLength2 * partialDen);
}
getKineticEnergy() {
return 0;
}
getPotentialEnergy() {
return 0;
}
getPeriod() {
return 0;
}
getMass1() {
return this.mass1;
}
getMass2() {
return this.mass2;
}
getTheta1() {
return this.theta1;
}
getTheta2() {
return this.theta2;
}
getCordLength1() {
return this.cordLength1;
}
getCordLength2() {
return this.cordLength2;
}
setMass1(mass1) {
this.mass1 = mass1;
}
setMass2(mass2) {
this.mass2 = mass2;
}
setTheta1(theta1, reset=false) {
this.theta1 = theta1 - HALF_PI;
if (reset) this.vel1 = 0;
secondarySurf.background(255);
this.lastPos = null;
}
setTheta2(theta2, reset=false) {
this.theta2 = theta2 - HALF_PI;
if (reset) this.vel2 = 0;
secondarySurf.background(255);
this.lastPos = null;
}
setCordLength1(cordLength1) {
this.cordLength1 = cordLength1;
this.setTheta1(this.theta1+HALF_PI);
}
setCordLength2(cordLength2) {
this.cordLength2 = cordLength2;
this.setTheta1(this.theta1+HALF_PI);
}
draw() {
const radius1 = this.mass1Diameter / 2, radius2 = this.mass2Diameter / 2;
push();
strokeWeight(2);
stroke(this.massColor.x, this.massColor.y, this.massColor.z);
fill(this.massColor.x, this.massColor.y, this.massColor.z);
if (trace && this.lastPos !== null) {
secondarySurf.line(this.lastPos.x, this.lastPos.y, this.mass2Pos.x, this.mass2Pos.y);
}
this.lastPos = this.mass2Pos; // don't put this under the trace condition
if (showGuides) {
dottedLine(this.pivotPos.x, this.pivotPos.y, this.pivotPos.x, this.pivotPos.y + this.cordLength1 + radius1, 20);
dottedLine(this.mass1Pos.x, this.mass1Pos.y, this.mass1Pos.x, this.mass1Pos.y + this.cordLength2 + radius2, 20);
dottedLine(this.pivotPos.x - this.cordLength1 + radius1, this.pivotPos.y + this.cordLength1 + radius1,
this.pivotPos.x + this.cordLength1 + radius1, this.pivotPos.y + this.cordLength1 + radius1, 30);
dottedLine(this.mass1Pos.x - this.cordLength2 + radius2, this.mass1Pos.y + this.cordLength2 + radius2,
this.mass1Pos.x + this.cordLength2 + radius2, this.mass1Pos.y + this.cordLength2 + radius2, 30);
}
stroke(this.cordColor.x, this.cordColor.y, this.cordColor.z);
line(this.pivotPos.x, this.pivotPos.y, this.mass1Pos.x, this.mass1Pos.y);
line(this.mass1Pos.x, this.mass1Pos.y, this.mass2Pos.x, this.mass2Pos.y);
circle(this.mass1Pos.x, this.mass1Pos.y, this.mass1Diameter);
circle(this.mass2Pos.x, this.mass2Pos.y, this.mass2Diameter);
if (showGuides) {
fill(this.massColor.x, this.massColor.y, this.massColor.z, 128);
if (this.theta1 < 0) {
arc(this.pivotPos.x, this.pivotPos.y, 2*this.mass1Diameter, 2*this.mass1Diameter, HALF_PI, -this.theta1+HALF_PI);
} else {
arc(this.pivotPos.x, this.pivotPos.y, 2*this.mass1Diameter, 2*this.mass1Diameter, -this.theta1+HALF_PI, HALF_PI);
}
if (this.theta2 < 0) {
arc(this.mass1Pos.x, this.mass1Pos.y, 2*this.mass2Diameter, 2*this.mass2Diameter, HALF_PI, -this.theta2+HALF_PI);
} else {
arc(this.mass1Pos.x, this.mass1Pos.y, 2*this.mass2Diameter, 2*this.mass2Diameter, -this.theta2+HALF_PI, HALF_PI);
}
}
pop();
}
update() {
if (!paused) {
this.calculateAccelerations();
this.vel1 += this.acc1 * timeStep;
this.vel2 += this.acc2 * timeStep;
this.theta1 = (this.theta1 + this.vel1 * timeStep) % TWO_PI;
this.theta2 = (this.theta2 + this.vel2 * timeStep) % TWO_PI;
}
this.mass1Pos = p5.Vector.add(this.pivotPos, createVector(sin(this.theta1), cos(this.theta1)).mult(this.cordLength1));
this.mass2Pos = p5.Vector.add(this.mass1Pos, createVector(sin(this.theta2), cos(this.theta2)).mult(this.cordLength2)); // in case the user clicks
this.draw();
}
}
const dottedLine = (x1, y1, x2, y2, dashes=10) => {
if (dashes % 2 === 0) dashes++; // make sure it starts and ends with a dash
let dx = (x2-x1)/dashes, dy = (y2-y1)/dashes;
for (let i=0; i<dashes; i++) {
if (i % 2 === 0) {
line(x1, y1, x1+=dx, y1+=dy);
} else {
x1 += dx;
y1 += dy;
}
}
}
const round = (x, decPlaces) => {
const p = pow(10, decPlaces);
return floor(x * p) / p;
}
const decimalString = (x, decPlaces=2) => {
const ending = x<0 ? "" : " ";
if (x === floor(x)) return (x + ".").padEnd((""+floor(x)).length + decPlaces + 1, "0") + ending;
return ("" + round(x, decPlaces)).padEnd((""+floor(x)).length + decPlaces + 1, "0") + ending; // +1 because of the decimal point
}
const drawInfo = (paddingX=20, paddingY=20) => {
let minX = pendulum.pivotPos.x * 2 + paddingX;
let minY = paddingY + textSize();
const showString = (label, units, v, inc=true) => {
const str = label + decimalString(v, 2) + units;
textSize(floor(min(20, 2 * (width-minX) / (str.length + 1))));
text(str, minX, minY+=40*inc);
}
push();
fill(0);
stroke(0);
strokeWeight(1);
line(minX - paddingX, 0, minX - paddingX, height);
showString("Time: ", " seconds", simTime, false);
if (mode === 0) {
showString("Kinetic Energy: ", " joules", pendulum.getKineticEnergy());
showString("Period: ", " seconds", pendulum.getPeriod());
showString("Mass: ", " kg", pendulum.getMass());
showString("Theta: ", " radians", pendulum.getTheta());
showString("Rotational velocity: ", " radians/second", pendulum.getRotationalVelocityAboutPivot());
showString("Tangential velocity: ", " meters/second", pendulum.getTangentialVelocity());
showString("String length: ", " meters", pendulum.getCordLength());
} else {
showString("Mass 1: ", " kg", pendulum.getMass1());
showString("Mass 2: ", " kg", pendulum.getMass2());
showString("Theta 1: ", " radians", pendulum.getTheta1());
showString("Theta 2: ", " radians", pendulum.getTheta2());
showString("String 1 length: ", " meters", pendulum.getCordLength1());
showString("String 2 length: ", " meters", pendulum.getCordLength2());
}
pop();
}
function mousePressed() {
if (0 <= mouseX) {
if (mode === 0) {
const angle = PI-atan2(mouseY - pendulum.pivotPos.y, mouseX - pendulum.pivotPos.x);
pendulum.setTheta(angle, true);
} else {
if (dist(mouseX, mouseY, pendulum.pivotPos.x, pendulum.pivotPos.y) <= pendulum.cordLength1) {
const angle = PI-atan2(mouseY - pendulum.pivotPos.y, mouseX - pendulum.pivotPos.x);
pendulum.setTheta1(angle, true);
} else {
const angle = PI-atan2(mouseY - pendulum.mass1Pos.y, mouseX - pendulum.mass1Pos.x);
pendulum.setTheta2(angle, true);
}
}
}
}
/* UI stuff */
const togglePause = () => {
const btn = document.getElementById("pause-btn");
if (paused) {
btn.innerHTML = "Pause";
} else {
btn.innerHTML = "Resume";
}
paused = !paused;
}
const toggleTrace = () => {
const btn = document.getElementById("trace-btn");
if (trace) {
btn.innerHTML = "Enable trace";
secondarySurf.background(255);
} else {
btn.innerHTML = "Disable trace";
}
trace = !trace;
}
const toggleGuides = () => {
const btn = document.getElementById("guides-btn");
if (showGuides) {
btn.innerHTML = "Enable guides";
} else {
btn.innerHTML = "Disable guides";
}
showGuides = !showGuides;
}
const toggleModes = () => {
const btn = document.getElementById("mode-btn");
if (mode === 0) {
btn.innerHTML = "Switch to single pendulum";
pendulum = new DoublePendulum(width/3, height/5, height/30, height/30, height/6, height/6);
document.getElementById("single-pendulum-widgets").style.display="none";
document.getElementById("double-pendulum-widgets").style.display="block";
} else {
btn.innerHTML = "Switch to double pendulum";
pendulum = new Pendulum(width/3, height/5, height/15, height/3);
document.getElementById("single-pendulum-widgets").style.display="block";
document.getElementById("double-pendulum-widgets").style.display="none";
}
secondarySurf.background(255);
mode = !mode + 0;
}
const resetSimTime = () => {
simTime = 0;
}
/* end */
let pendulum, paused, trace, showGuides, simTime, secondarySurf, mode;
function setup() {
canvas = createCanvas(windowWidth * .75, windowHeight);
canvas.parent("canvas-div");
secondarySurf = createGraphics(width, height);
secondarySurf.background(255);
document.getElementById("gui-div").style.height = windowHeight.toString() + "px";
pendulum = new Pendulum(width/3, height/5, height/15, height/3);
paused = false;
trace = true;
showGuides = true;
mode = 0; // 0: single pendulum. 1: double pendulum
simTime = 0;
}
function draw() {
if (!paused) simTime += timeStep;
image(secondarySurf, 0, 0);
pendulum.update();
drawInfo();
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T00:48:19.073",
"Id": "248014",
"Score": "2",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Simulating arbitrary amplitude pendulums and double pendulums with p5"
}
|
248014
|
<p>I have been reading today about the Abstract Factory Pattern, and tried to make the following implementation.</p>
<p>I have seen a lot of implementations in the internet, where they use <code>switch</code> statements, but I must say that I didn't like that much, since the more factories you make, it seems to me that it makes very difficult to add new products, if needed.</p>
<p>Anyways, I was hoping you to take a look at it and let me know your opinions. Thanks in advance for taking your time to review it.</p>
<p><strong>Factories</strong></p>
<pre><code>from abc import ABC, abstractmethod
class PlayerFactory(ABC):
"""
This class is meant to be an interface
"""
@abstractmethod
def create_goalkeeper(self):
pass
@abstractmethod
def create_defender(self):
pass
class FootballPlayerFactory(PlayerFactory):
def create_goalkeeper(self):
return FootballGoalkeeper()
def create_defender(self):
return FootballDefender()
class HockeyPlayerFactory(PlayerFactory):
def create_goalkeeper(self):
return HockeyGoalkeeper()
def create_defender(self):
return HockeyDefender()
</code></pre>
<p><strong>Football players</strong></p>
<pre><code>class FootballPlayer:
def __init__(self, uses_hands):
self.uses_hands = uses_hands
def play(self):
print("I'm playing football!")
class FootballGoalkeeper(FootballPlayer):
def __init__(self):
super(FootballGoalkeeper, self).__init__(uses_hands=True)
class FootballDefender(FootballPlayer):
def __init__(self):
super(FootballDefender, self).__init__(uses_hands=False)
</code></pre>
<p><strong>Hockey players</strong> (<em>my creativity stopped here, so I didn't include any difference between goalkeepers and defenders</em>)</p>
<pre><code>class HockeyPlayer:
def play(self):
print("I'm playing hockey!")
class HockeyGoalkeeper(HockeyPlayer):
pass
class HockeyDefender(HockeyPlayer):
pass
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T12:26:49.680",
"Id": "485720",
"Score": "2",
"body": "`super(FootballGoalKeeper, self)` can be replaced by `super()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T14:38:52.863",
"Id": "485729",
"Score": "0",
"body": "Thanks! Oh yes, you're right. I'm just too used to that old syntax. Thanks for pointing that out. @hjpotter92"
}
] |
[
{
"body": "<p>As your code presently stands, you don't need the derived Factory classes. They don't do anything different from each other, so they can all be handled by a concrete base class.</p>\n<pre><code>class PlayerFactory:\n\n def __init__(self, goal_keeper_class, defender_class):\n self._goal_keeper_class = goal_keeper_class\n self._defender_class = defender_class\n\n def create_goalkeeper(self):\n return self._goal_keeper_class()\n\n def create_defender(self):\n return self._defender_class()\n\nplayer_factory = {\n "Football": PlayerFactory(FootballGoalkeeper, FootballDefender),\n "Hockey": PlayerFactory(HockeyGoalkeeper, HockeyDefender),\n}\n</code></pre>\n<p>Example Usage:</p>\n<pre><code>>>> player = player_factory["Hockey"].create_defender()\n>>> type(player)\n<class '__main__.HockeyDefender'>\n>>> player.play()\nI'm playing hockey!\n>>>\n</code></pre>\n<p>If there is some aspect of the factories which actually do something different, and thus necessitate separated derived classes, you'll need to include that in your question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T16:12:33.373",
"Id": "485735",
"Score": "0",
"body": "Thank you for this, it's very useful. Hmm yes, your code makes so much more sense, but I was just trying to think in a way to *use* or make an example of Abstract Factory pattern. :-( I guess I'm still confused by the use cases of this pattern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T16:43:31.140",
"Id": "485736",
"Score": "2",
"body": "Well, if you added a \"create_team\" method, your various factories might return different numbers of players for the various positions. You could implement it with code in different derived classes, but it could be simply data-driven without needing derived classes. There is always more than one way to do it. The Abstract Factory pattern is a useful tool for your toolbox, but it isn't necessarily the right tool to use until your problem becomes significantly more complex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T16:53:17.070",
"Id": "485738",
"Score": "0",
"body": "Invaluable information. This is the kind of clarification and inputs I was expecting to have. @AJNeufeld"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T15:24:43.690",
"Id": "248038",
"ParentId": "248015",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248038",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T00:56:38.813",
"Id": "248015",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"abstract-factory"
],
"Title": "Abstract Factory Pattern in Python"
}
|
248015
|
<p>I wrote a library that implements LZW compression and decompression. A goal of this project was to help me acquaint myself with modern C++ development practices (I primarily come from a Java background and have a smattering of C experience).</p>
<p>I want to use this library to compress data and stream it over TCP sockets to be decompressed by the recipient, all without storing a compressed version of the full data on either the sender or the recipient's machine (for hobby/non-production purposes).</p>
<p>lzw.hpp</p>
<pre><code>#pragma once
#include <iostream>
#include <optional>
#include <unordered_map>
#include <vector>
namespace lzw {
class lzw_encoder {
public:
lzw_encoder(std::istream &is, std::ostream &os);
void encode();
private:
uint32_t current_code = 0;
std::string current;
std::unordered_map<std::string, uint32_t> codebook;
std::istream &is;
std::ostream &os;
};
class lzw_decoder {
public:
lzw_decoder(std::istream &is, std::ostream &os);
void decode();
private:
std::vector<std::string> codebook;
std::optional<uint32_t> prev;
std::istream &is;
std::ostream &os;
};
} // namespace lzw
</code></pre>
<p>lzw.cpp</p>
<pre><code>#include "lzw.hpp"
namespace lzw {
static constexpr size_t ENCODER_BUFFER_SIZE = 256;
static constexpr size_t DECODER_BUFFER_SIZE = 64;
lzw_encoder::lzw_encoder(std::istream &is, std::ostream &os)
: is(is), os(os), current_code(0) {
for (current_code = 0; current_code < 256; ++current_code) {
codebook[std::string(1, static_cast<char>(current_code))] = current_code;
}
}
void lzw_encoder::encode() {
char buffer[ENCODER_BUFFER_SIZE];
while (true) {
is.read(buffer, ENCODER_BUFFER_SIZE);
auto read_length = is.gcount();
if (read_length == 0)
break;
for (size_t i = 0; i < read_length; ++i) {
current.push_back(buffer[i]);
auto iter = codebook.find(current);
if (iter == codebook.end()) {
codebook[current] = current_code++;
current.pop_back();
auto code_val = codebook[current];
os.write(reinterpret_cast<char *>(&code_val), sizeof(code_val));
current.clear();
current.push_back(buffer[i]);
}
}
}
if (current.size()) {
auto code_val = codebook[current];
os.write(reinterpret_cast<char *>(&code_val), sizeof(code_val));
}
}
lzw_decoder::lzw_decoder(std::istream &is, std::ostream &os)
: is(is), os(os), prev{} {
for (int i = 0; i < 256; ++i) {
codebook.emplace_back(1, static_cast<char>(i));
}
}
void lzw_decoder::decode() {
uint32_t buffer[DECODER_BUFFER_SIZE];
while (true) {
is.read(reinterpret_cast<char *>(buffer),
DECODER_BUFFER_SIZE * sizeof(uint32_t));
auto read_length = is.gcount() / sizeof(uint32_t);
if (read_length == 0)
break;
for (size_t i = 0; i < read_length; ++i) {
if (buffer[i] < codebook.size()) {
os << codebook[buffer[i]];
if (prev) {
codebook.push_back(codebook[*prev] + codebook[buffer[i]].front());
}
} else {
codebook.push_back(codebook[*prev] + codebook[*prev].front());
os << codebook.back();
}
prev = buffer[i];
}
}
}
} // namespace lzw
</code></pre>
<p>I plan on replacing the unordered_map in the lzw_encoder with a dictionary trie in a future edit.</p>
<p>Does my code exhibit a reasonable way to use io streams?</p>
<p>I feel that my usage of read and write did not have a feeling of modern C++, and I'm wondering if I am unaware of some standard library tools to help me with binary io. In particular, I don't like that I used
<code>while(true)</code> instead of some condition related to the input streams. Also, I was wondering if there was a way to do binary io without using <code>reinterpret_cast</code> to cast numeric/binary data pointers to <code>char *</code>.</p>
|
[] |
[
{
"body": "<p>Here are some things I see that may help you improve your code.</p>\n<h2>Shouldn't a compressed file be smaller?</h2>\n<p>Imagine my surprise when I discovered that a 2037-byte file (the lzw.cpp source code itself) became 3524 bytes when "compressed!" The original LZW algorithm encoded 8-bit values into 12-bit codes. This appears to be encoding 8-bit values as 32-bit codes which is unlikely to offer much compression for short files like this. I did, however, try it on the plain text version of <a href=\"http://www.gutenberg.org/ebooks/345\" rel=\"nofollow noreferrer\">Bram Stoker's <em>Dracula</em></a> and, as expected, the resulting file was about 75% of the size of the original. Because it's a stream and you don't have access to the length of the source, there may not be much you can do about it, but it's probably a good thing to warn potential users about.</p>\n<h2>Rethink the interface</h2>\n<p>In order to use the compression, one must first create an object and <em>then</em> use it, perhaps like this:</p>\n<pre><code>lzw::lzw_encoder lzw(in, out);\nlzw.encode();\n</code></pre>\n<p>Wouldn't it be nicer to just be able to do this?</p>\n<pre><code>lzw::encode(in, out);\n</code></pre>\n<h2>Write member initializers in declaration order</h2>\n<p>The <code>lzw_encoder</code> class has this constructor</p>\n<pre><code>lzw_encoder::lzw_encoder(std::istream &is, std::ostream &os)\n : is(is), os(os), current_code(0) {\n for (current_code = 0; current_code < 256; ++current_code) {\n codebook[std::string(1, static_cast<char>(current_code))] = current_code;\n }\n}\n</code></pre>\n<p>That looks fine, but in fact, <code>current_code</code> will be initialized <em>before</em> <code>is</code> and <code>os</code> because members are always initialized in <em>declaration</em> order and <code>current_code</code> is declared before <code>is</code> in this class. To avoid misleading another programmer, you could simply omit <code>current_code</code> since it is already initialized by the declaration:</p>\n<pre><code>uint32_t current_code = 0;\n</code></pre>\n<h2>Use standard algorithms where appropriate</h2>\n<p>Initializing the codebook uses this:</p>\n<pre><code>for (current_code = 0; current_code < 256; ++current_code) {\n codebook[std::string(1, static_cast<char>(current_code))] = current_code;\n}\n</code></pre>\n<p>This can be improved in a number of ways. First, we already know how large the codebook will be so we can reduce the number of memory reallocations by telling the compiler that information:</p>\n<pre><code>codebook.reserve(256);\n</code></pre>\n<p>Next, we can avoid the cast and gain a bit of efficiency by using <code>emplace</code>:</p>\n<pre><code>for (current_code = 0; current_code < 256; ++current_code) {\n codebook.emplace(std::string(1, current_code), current_code);\n}\n</code></pre>\n<p>I'd also recommend replacing <code>256</code> here with a <code>static constexpr initial_codebook_size</code>.</p>\n<h2>Beware of endian-ness differences</h2>\n<p>The code currently contains these lines:</p>\n<pre><code>auto code_val = codebook[current];\nos.write(reinterpret_cast<char *>(&code_val), sizeof(code_val));\n</code></pre>\n<p>There problem is that depending on whether this is a big-endian or little-endian machine, the encoding will be different. If the compressed stream is intended to be sent to a different machine, this needs to be consistent. Consider using something like the POSIX <code>htonl</code> function here.</p>\n<h2>Consider restructuring loops</h2>\n<p>The problem with <code>while(true)</code> is that it hides the loop exit condition. Instead of this:</p>\n<pre><code>while (true) {\n is.read(buffer, ENCODER_BUFFER_SIZE);\n auto read_length = is.gcount();\n if (read_length == 0)\n break;\n // etc\n}\n</code></pre>\n<p>Consider something like this:</p>\n<pre><code>while (is.read(buffer, ENCODER_BUFFER_SIZE)) {\n // handle full block\n}\nif (is.gcount()) {\n // handle final partial block\n}\n</code></pre>\n<h2>Understand the use of streams</h2>\n<p>It's possible that the caller has set one or both streams to throw an <a href=\"https://en.cppreference.com/w/cpp/io/basic_ios/exceptions\" rel=\"nofollow noreferrer\">exception</a> on encountering a failure such as end of file on read. Either override this or handle it appropriately.</p>\n<h2>Consider adding convenience functions</h2>\n<p>The handling of blocks for encode and for decode could both be made into functions within the namespace. This would make the restructuring of loops as mentioned above a bit easier and cleaner and would isolate the handling of the data structures from basic stream I/O. That may make things a bit easier when you convert to a trie. Here's my rewrite of the loop:</p>\n<pre><code>while (is.read(buffer, ENCODER_BUFFER_SIZE)) {\n encode_buffer(buffer, ENCODER_BUFFER_SIZE);\n}\nencode_buffer(buffer, is.gcount());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:56:52.423",
"Id": "485841",
"Score": "0",
"body": "Thanks for all of the tips! I added the trie on a recent edit, and got rid of the ```while(true)``` reading loop in the encoder by using std::streambuf_iterator. For the decoder, instead of maintaining a buffer, I directly use std::istream::read to read a single uint32_t - I'm not sure what the performance difference would be in having my program maintain the read buffers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T16:02:42.670",
"Id": "485842",
"Score": "0",
"body": "I think removing the ```encode``` and ```decode``` methods makes sense. In your comment about removing the ```while(true)``` loops by handling the final partial block separately, I think because I am using ```std::istream``` instead of ```std::ifstream```, there is no guarantee that an incompletely filled block would be the last block, e.g. when ```is``` is ```std::cin```, the block would be written up to the next newline if I am not mistaken"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T16:35:51.653",
"Id": "485843",
"Score": "1",
"body": "For using `std::istream::read` for a single `uint32_t` at a time, because most implementations I've seen are buffered, I doubt there would be a performance hit (but measure to be sure). For reading from `std::in`, you may be right. As you correctly guessed, I was thinking in terms of `std::ifstream`s."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T14:35:39.560",
"Id": "248090",
"ParentId": "248018",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T03:15:10.177",
"Id": "248018",
"Score": "3",
"Tags": [
"c++",
"c++17",
"stream",
"compression"
],
"Title": "LZW Compression Library"
}
|
248018
|
<p>I'm implementing the logic of a board game in Java to practice my coding skills. I chose <a href="https://boardgamegeek.com/boardgame/175914/food-chain-magnate" rel="nofollow noreferrer">Food Chain Magnate</a> because is a fairly complex game that requires different data structures. One of my first tasks is to generate the data structure for the game board. In the game, the board is built using some (of all, depending of the # of players) of the 20 available tiles. Each tile is a grid of 5 x 5 squares. The identity of each tile is not important during the game, only if some square is in a different tile than another.</p>
<p>I created a <code>Board</code> class that is basically a wrapper over a 2D Object array with additional methods for calculation, and a <code>BoardGenerator</code> that create <code>Board</code>s and initializes it with the contents of the different tiles.</p>
<p><strong>Board.java</strong></p>
<pre><code>package com.lartkma.fcm.model.board;
public class Board {
public static final int TILE_SIZE = 5;
public static final Object OFF_LIMIT = new Object();
private Object[][] boardSquares;
public Board(int widthTiles, int heightTiles) {
this.boardSquares = new Object[widthTiles * TILE_SIZE][heightTiles * TILE_SIZE];
}
public Object get(int x, int y) {
if (x >= 0 && x < this.boardSquares.length && y >= 0 && y < this.boardSquares[0].length) {
return this.boardSquares[x][y];
} else {
return OFF_LIMIT;
}
}
public Object get(Point p) {
return get(p.x(), p.y());
}
public void set(int x, int y, Object obj) {
if (x >= 0 && x < this.boardSquares.length && y >= 0 && y < this.boardSquares[0].length) {
this.boardSquares[x][y] = obj;
} else {
throw new IndexOutOfBoundsException("Point " + new Point(x, y) + " is out of the board");
}
}
public void set(Point p, Object obj) {
set(p.x(), p.y(), obj);
}
public int getWidth() {
return this.boardSquares.length;
}
public int getHeight() {
return this.boardSquares[0].length;
}
/**
* Returns the tile where the square belongs, relative to this board. The value
* is not related to the original tile used to build the board, only allows to
* differentiate one tile from another.
* @param p
* @return
*/
public int getTileNumber(Point p) {
return (p.y() / TILE_SIZE) * (this.boardSquares.length / TILE_SIZE) + (p.x() / TILE_SIZE);
}
}
</code></pre>
<p>The <code>Point</code> class is a simple, immutable 2D point class with a constructor <code>Point(int x, int y)</code>, methods <code>x()</code>, <code>y()</code> for retrieval and a <code>add(int dx, int dy)</code> method that returns the point (x + dx, y + dy). I'm not writing it here to focus in the other classes.</p>
<p><strong>BoardGenerator.java</strong></p>
<pre><code>package com.lartkma.fcm.model.board;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Stream;
public class BoardGenerator {
public static Board fromRandom(int widthTiles, int heightTiles) {
Random rnd = new Random();
Map<Character, Object[][]> tileList = getTileList();
List<Character> randomTiles = new LinkedList<>(tileList.keySet());
Collections.shuffle(randomTiles);
Board board = new Board(widthTiles, heightTiles);
for (int i = 0; i < widthTiles; i++) {
for (int j = 0; j < heightTiles; j++) {
fillWithTile(board, tileList.get(randomTiles.get(i * heightTiles + j)), i * Board.TILE_SIZE,
j * Board.TILE_SIZE, rnd.nextInt(4));
}
}
return board;
}
/**
* Generates a board using the tiles and rotations indicated in the expression.
*
* The expression is composed of (# tiles tall) subexpressions separated by
* newlines or spaces, each subexpression made of (# tiles wide x 2) characters.
*
* Each 2 characters of a subexpression describe a tile and the rotation of such
* tile. The tile is indicated with one of the upper-case characters used in
* <a href="https://boardgamehelpers.com/FoodChainMagnate/MapTileKey.aspx">this page</a>.
* The rotation is described as a digit from 1 to 4, where 1 is the orientation shown in
* the page mentioned above (with the identified in the bottom left), 2 rotates the
* reference orientation rotated 90 degrees clockwise, and so on.
*
* @param expression
* @return
*/
public static Board fromExpression(String expression) {
String[] rows = expression.split("\n|\r\n| ");
int heightTiles = rows.length;
int widthTiles = Stream.of(rows).mapToInt(s -> s.length() / 2).max().orElse(0);
Board board = new Board(widthTiles, heightTiles);
Map<Character, Object[][]> tileList = getTileList();
for (int i = 0; i < widthTiles; i++) {
for (int j = 0; j < heightTiles; j++) {
if (2 * i + 1 < rows[rows.length - 1 - j].length()) {
char tileId = rows[rows.length - 1 - j].charAt(2 * i);
char tileRotationFactor = rows[rows.length - 1 - j].charAt(2 * i + 1);
if (tileList.containsKey(tileId) && tileRotationFactor >= '1' && tileRotationFactor <= '4') {
// Number of rotations goes from 0 to 3
fillWithTile(board, tileList.get(tileId), i * Board.TILE_SIZE, j * Board.TILE_SIZE,
tileRotationFactor - '1');
} else {
throw new IllegalArgumentException(
"Board tile expression \"" + tileId + tileRotationFactor + "\" cannot be read");
}
}
}
}
return board;
}
private static Map<Character, Object[][]> getTileList() {
Map<Character, Object[][]> outputMap = new HashMap<>();
try (BufferedReader stream = new BufferedReader(
new InputStreamReader(BoardGenerator.class.getResourceAsStream("tiles.txt")))) {
int lineCount = 1;
Object[][] currentTileContent = new Object[Board.TILE_SIZE][Board.TILE_SIZE];
char currentTileIdentifier = 'A';
String currentLine;
while ((currentLine = stream.readLine()) != null) {
for (int i = 0; i < Board.TILE_SIZE; i++) {
char lineChar = currentLine.charAt(i);
if (lineChar == 'O') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = null;
} else if (lineChar == '-') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(false, true, false, true);
} else if (lineChar == '|') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, false, true, false);
} else if (lineChar == '/') {
// check the previous and next squares in the same line to check if this is
// a up-to-right turn or a right-to-up turn
char previous = (i == 0 ? 'O' : currentLine.charAt(i - 1));
char next = (i == Board.TILE_SIZE - 1 ? 'O' : currentLine.charAt(i + 1));
if ((isHorizontalRoad(previous) || i == 0) && !isHorizontalRoad(next)) {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, false, false,
true);
} else if (!isHorizontalRoad(previous)
&& (isHorizontalRoad(next) || i == Board.TILE_SIZE - 1)) {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(false, true, true,
false);
} else {
throw new IllegalStateException("Unknown combination on ( " + currentLine + ")");
}
} else if (lineChar == '\\') {
// check the previous and next squares in the same line to check if this is
// a up-to-left turn or a left-to-up turn
char previous = (i == 0 ? 'O' : currentLine.charAt(i - 1));
char next = (i == Board.TILE_SIZE - 1 ? 'O' : currentLine.charAt(i + 1));
if ((isHorizontalRoad(previous) || i == 0) && !isHorizontalRoad(next)) {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(false, false, true,
true);
} else if (!isHorizontalRoad(previous)
&& (isHorizontalRoad(next) || i == Board.TILE_SIZE - 1)) {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, true, false,
false);
} else {
throw new IllegalStateException("Unknown combination on ( " + currentLine + ")");
}
} else if (lineChar == '^') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, true, false, true);
} else if (lineChar == '>') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, true, true, false);
} else if (lineChar == 'V') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(false, true, true, true);
} else if (lineChar == '<') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, false, true, true);
} else if (lineChar == '+') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, true, true, true);
} else if (lineChar == 'S') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = GoodsSource.SODA;
} else if (lineChar == 'B') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = GoodsSource.BEER;
} else if (lineChar == 'L') {
currentTileContent[i][Board.TILE_SIZE - lineCount] = GoodsSource.LEMONADE;
} else if (lineChar >= '0' && lineChar <= '9') {
Object previous = (i == 0 ? null : currentTileContent[i - 1][Board.TILE_SIZE - lineCount]);
if (previous instanceof House) {
// part of a two-digit house, same entity as left
currentTileContent[i][Board.TILE_SIZE
- lineCount] = currentTileContent[i - 1][Board.TILE_SIZE - lineCount];
} else {
int houseOrder = (lineChar - '0'); // classic
char next = (i == Board.TILE_SIZE - 1 ? 'O' : currentLine.charAt(i + 1));
if (next >= '0' && next <= '9') { // two digit id
houseOrder = houseOrder * 10 + (next - '0');
}
currentTileContent[i][Board.TILE_SIZE - lineCount] = new House(houseOrder);
}
} else if (lineChar == 'H') {
Object previous = (i == 0 ? null : currentTileContent[i - 1][Board.TILE_SIZE - lineCount]);
if (previous instanceof House) {
// same entity as left
currentTileContent[i][Board.TILE_SIZE - lineCount] = previous;
} else {
previous = (lineCount == 1 ? null
: currentTileContent[i][Board.TILE_SIZE - lineCount + 1]);
if (previous instanceof House) {
// same entity as up
currentTileContent[i][Board.TILE_SIZE - lineCount] = previous;
} else {
throw new IllegalStateException(
"Unknown combination on ( " + currentLine + "): no house defined near H");
}
}
} else {
throw new IllegalStateException("Unknown symbol: " + lineChar);
}
}
lineCount += 1;
if (lineCount > Board.TILE_SIZE) {
outputMap.put(currentTileIdentifier, currentTileContent);
lineCount = 1;
currentTileContent = new Object[Board.TILE_SIZE][Board.TILE_SIZE];
currentTileIdentifier += 1;
}
}
return outputMap;
} catch (IOException e) {
throw new Error("tiles.txt not available", e);
}
}
private static boolean isHorizontalRoad(char c) {
return c == '-' || c == '/' || c == '\\' || c == '^' || c == 'V' || c == '+';
}
private static void fillWithTile(Board board, Object[][] tileArray, int xStart, int yStart, int numRotations) {
for (int i = 0; i < Board.TILE_SIZE; i++) {
for (int j = 0; j < Board.TILE_SIZE; j++) {
Point boardPoint = new Point(xStart + i, yStart + j);
Point tileCoords = toTileCoords(i, j, numRotations);
Object inTile = tileArray[tileCoords.x()][tileCoords.y()];
if (inTile instanceof House) {
Object prevHouse;
if ((prevHouse = board.get(boardPoint.add(-1, 0))) instanceof House
&& ((House) prevHouse).getOrder() == ((House) inTile).getOrder()) {
// check house at the left
board.set(boardPoint, prevHouse);
} else if ((prevHouse = board.get(boardPoint.add(0, -1))) instanceof House
&& ((House) prevHouse).getOrder() == ((House) inTile).getOrder()) {
// check house below
board.set(boardPoint, prevHouse);
} else {
board.set(boardPoint, new House(((House) inTile).getOrder()));
}
} else if (inTile instanceof Road) {
board.set(boardPoint, ((Road) inTile).rotate(numRotations));
} else if (inTile instanceof GoodsSource || inTile == null) {
board.set(boardPoint, inTile);
} else {
throw new IllegalStateException("Unknown object: " + inTile.getClass());
}
}
}
}
private static Point toTileCoords(int x, int y, int rotations) {
switch (rotations) {
case 0:
return new Point(x, y);
case 1:
return new Point(Board.TILE_SIZE - 1 - y, x);
case 2:
return new Point(Board.TILE_SIZE - 1 - x, Board.TILE_SIZE - 1 - y);
case 3:
return new Point(y, Board.TILE_SIZE - 1 - x);
default:
throw new IllegalArgumentException("Should not happen");
}
}
}
</code></pre>
<p>The <code>tiles.txt</code> file contains the description of the 20 tiles. The contents of each tile can be seen here: <a href="https://boardgamehelpers.com/FoodChainMagnate/MapTileKey.aspx" rel="nofollow noreferrer">https://boardgamehelpers.com/FoodChainMagnate/MapTileKey.aspx</a> (doesn't include the expansion tiles). It's a plain text file formed with lines of 5 characters each. Each 5 lines describes a tile (5 x 5). Each tile is assigned a character as is shown in the reference link, being the first 5 lines tile A, the next 5 tile B and so on. Each character (or group of characters) represents an object. For example, tile E is described as</p>
<pre><code>/-/OO
|BOOO
/O8H/
OOHH|
OO/-/
</code></pre>
<p>(characters <code>/</code> and <code>\</code> can represent either one of two possible types of turns, depending of context)</p>
<p><strong>Road.java</strong></p>
<pre><code>package com.lartkma.fcm.model.board;
import java.util.Arrays;
import java.util.StringJoiner;
public class Road {
private boolean[] canMove;
public Road(boolean canGoUp, boolean canGoRight, boolean canGoDown, boolean canGoLeft) {
this.canMove = new boolean[] { canGoUp, canGoRight, canGoDown, canGoLeft };
}
public boolean canMove(Direction inDirection) {
return this.canMove[inDirection.ordinal()];
}
public Road rotate(int amountRotations) {
Road rotated = new Road(this.canMove[0], this.canMove[1], this.canMove[2], this.canMove[3]);
if (amountRotations < 0) {
// Java operator % returns a remainder, that is different from a mathematical
// modulus
// https://stackoverflow.com/questions/5385024/mod-in-java-produces-negative-numbers
// https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3
amountRotations = amountRotations % rotated.canMove.length + rotated.canMove.length;
} else {
amountRotations = amountRotations % rotated.canMove.length;
}
boolean swapTemp;
for (int k = 0; k < amountRotations; k++) {
for (int i = 1; i < rotated.canMove.length; i++) { // it makes no sense for the first element
swapTemp = rotated.canMove[0];
rotated.canMove[0] = rotated.canMove[i];
rotated.canMove[i] = swapTemp;
}
}
return rotated;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Road) {
return Arrays.equals(this.canMove, ((Road) obj).canMove);
} else {
return false;
}
}
@Override
public String toString() {
StringJoiner name = new StringJoiner("-", "Road[", "]");
for (Direction d : Direction.values()) {
if (canMove(d)) {
name.add(d.name());
}
}
return name.toString();
}
}
</code></pre>
<p><code>Direction</code> is an enum with values <code>UP, RIGHT, DOWN, LEFT</code> (in that order). <code>House</code> is a simple data class with a <code>order</code> property, but it will mutate other properties during the game. <code>GoodsSource</code> is a simple, immutable class that can only have 3 possible instances.</p>
<p><strong>BoardGeneratorTest.java</strong> (for a sample of how it's used)</p>
<pre><code>package com.lartkma.fcm.model.board;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.CoreMatchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.lartkma.fcm.model.board.Board;
import com.lartkma.fcm.model.board.GoodsSource;
import com.lartkma.fcm.model.board.House;
import com.lartkma.fcm.model.board.BoardGenerator;
import com.lartkma.fcm.model.board.Road;
public class BoardGeneratorTest {
@Test
@DisplayName("The board generator can receive specific tiles as parameters and should generate the correct amount of squares")
public void testBoardGeneratorSizeFromExpression() {
Board board = BoardGenerator.fromExpression("G1E2\nI3M4");
assertAll("The board should be of 2 x 2 tiles (10 x 10 squares)",
() -> assertEquals(10, board.getWidth(), "Board width"),
() -> assertEquals(10, board.getHeight(), "Board height"));
}
@Test
@DisplayName("The board generator can generate a random board and should generate the correct amount of squares")
public void testBoardGeneratorSizeFromRandom() {
Board board = BoardGenerator.fromRandom(3, 2);
assertAll("The board should be of 3 x 2 tiles (15 x 10 squares)",
() -> assertEquals(15, board.getWidth(), "Board width"),
() -> assertEquals(10, board.getHeight(), "Board height"));
}
@Test
@DisplayName("The board generator can create a 1-tile board with the correct contents")
public void testBoardGeneratorContent() {
Board board = BoardGenerator.fromExpression("E1");
assertAll("The board should have the following contents",
() -> assertThat("In 0, 0", board.get(0, 0), is(nullValue())),
() -> assertThat("In 1, 0", board.get(1, 0), is(nullValue())),
() -> assertThat("In 2, 0", board.get(2, 0), is(equalTo(new Road(false, true, true, false)))),
() -> assertThat("In 3, 0", board.get(3, 0), is(equalTo(new Road(false, true, false, true)))),
() -> assertThat("In 4, 0", board.get(4, 0), is(equalTo(new Road(true, false, false, true)))),
() -> assertThat("In 0, 1", board.get(0, 1), is(nullValue())),
() -> assertThat("In 1, 1", board.get(1, 1), is(nullValue())),
() -> assertThat("In 2, 1", board.get(2, 1), is(equalTo(new House(8)))),
() -> assertThat("In 3, 1", board.get(3, 1), is(sameInstance(board.get(2, 1)))),
() -> assertThat("In 4, 1", board.get(4, 1), is(equalTo(new Road(true, false, true, false)))),
() -> assertThat("In 0, 2", board.get(0, 2), is(equalTo(new Road(true, false, false, true)))),
() -> assertThat("In 1, 2", board.get(1, 2), is(nullValue())),
() -> assertThat("In 2, 2", board.get(2, 2), is(sameInstance(board.get(2, 1)))),
() -> assertThat("In 3, 2", board.get(3, 2), is(sameInstance(board.get(2, 1)))),
() -> assertThat("In 4, 2", board.get(4, 2), is(equalTo(new Road(false, true, true, false)))),
() -> assertThat("In 0, 3", board.get(0, 3), is(equalTo(new Road(true, false, true, false)))),
() -> assertThat("In 1, 3", board.get(1, 3), is(equalTo(GoodsSource.BEER))),
() -> assertThat("In 2, 3", board.get(2, 3), is(nullValue())),
() -> assertThat("In 3, 3", board.get(3, 3), is(nullValue())),
() -> assertThat("In 4, 3", board.get(4, 3), is(nullValue())),
() -> assertThat("In 0, 4", board.get(0, 4), is(equalTo(new Road(false, true, true, false)))),
() -> assertThat("In 1, 4", board.get(1, 4), is(equalTo(new Road(false, true, false, true)))),
() -> assertThat("In 2, 4", board.get(2, 4), is(equalTo(new Road(true, false, false, true)))),
() -> assertThat("In 3, 4", board.get(3, 4), is(nullValue())),
() -> assertThat("In 4, 4", board.get(4, 4), is(nullValue())));
}
@Test
@DisplayName("The board generator can create a rotated 1-tile board with the correct contents")
public void testBoardGeneratorContentRotated() {
Board board = BoardGenerator.fromExpression("E2");
assertAll("The board should have the following contents",
() -> assertThat("In 0, 0", board.get(0, 0), is(equalTo(new Road(true, true, false, false)))),
() -> assertThat("In 1, 0", board.get(1, 0), is(equalTo(new Road(false, true, false, true)))),
() -> assertThat("In 2, 0", board.get(2, 0), is(equalTo(new Road(false, false, true, true)))),
() -> assertThat("In 3, 0", board.get(3, 0), is(nullValue())),
() -> assertThat("In 4, 0", board.get(4, 0), is(nullValue())),
() -> assertThat("In 0, 1", board.get(0, 1), is(equalTo(new Road(true, false, true, false)))),
() -> assertThat("In 1, 1", board.get(1, 1), is(equalTo(new House(8)))),
() -> assertThat("In 2, 1", board.get(2, 1), is(sameInstance(board.get(1, 1)))),
() -> assertThat("In 3, 1", board.get(3, 1), is(nullValue())),
() -> assertThat("In 4, 1", board.get(4, 1), is(nullValue())),
() -> assertThat("In 0, 2", board.get(0, 2), is(equalTo(new Road(false, false, true, true)))),
() -> assertThat("In 1, 2", board.get(1, 2), is(sameInstance(board.get(1, 1)))),
() -> assertThat("In 2, 2", board.get(2, 2), is(sameInstance(board.get(1, 1)))),
() -> assertThat("In 3, 2", board.get(3, 2), is(nullValue())),
() -> assertThat("In 4, 2", board.get(4, 2), is(equalTo(new Road(true, true, false, false)))),
() -> assertThat("In 0, 3", board.get(0, 3), is(nullValue())),
() -> assertThat("In 1, 3", board.get(1, 3), is(nullValue())),
() -> assertThat("In 2, 3", board.get(2, 3), is(nullValue())),
() -> assertThat("In 3, 3", board.get(3, 3), is(equalTo(GoodsSource.BEER))),
() -> assertThat("In 4, 3", board.get(4, 3), is(equalTo(new Road(true, false, true, false)))),
() -> assertThat("In 0, 4", board.get(0, 4), is(nullValue())),
() -> assertThat("In 1, 4", board.get(1, 4), is(nullValue())),
() -> assertThat("In 2, 4", board.get(2, 4), is(equalTo(new Road(true, true, false, false)))),
() -> assertThat("In 3, 4", board.get(3, 4), is(equalTo(new Road(false, true, false, true)))),
() -> assertThat("In 4, 4", board.get(4, 4), is(equalTo(new Road(false, false, true, true)))));
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>public static final int TILE_SIZE = 5;\n</code></pre>\n<p>Maybe call this <code>TILE_EDGE_SIZE</code> or something similar, as a tile doesn't contain 5 squares.</p>\n<pre><code>public Object get(int x, int y) {\n</code></pre>\n<p>Remove this, just use <code>get(Point p)</code>, it's not that more work.</p>\n<pre><code>return OFF_LIMIT;\n</code></pre>\n<p>This single <em>magic value</em> is keeping you from using the correct class for the Array. Magic values are something you might want to avoid. If you really want to avoid an exception, use <code>Optional<Square></code>. But personally I would throw an exception and use <code>Optional</code> instead of returning <code>null</code>.</p>\n<pre><code>throw new IndexOutOfBoundsException("Point " + new Point(x, y) + " is out of the board");\n</code></pre>\n<p>I knew you could do it, now make the methods <em>symmetric</em> on how they handle out of bounds.</p>\n<pre><code>public int getWidth() {\n...\npublic int getHeight() {\n</code></pre>\n<p>Perfect, no reason why the application would ever return <code>OFF_LIMIT</code> then.</p>\n<hr />\n<pre><code>Map<Character, Object[][]> tileList = getTileList();\n</code></pre>\n<p>Mixing collections and arrays is not a good idea; just use collections.</p>\n<pre><code>List<Character> randomTiles = new LinkedList<>(tileList.keySet());\n</code></pre>\n<p>To be precise, you'd use <code>ArrayList</code> here, not a linked list.</p>\n<pre><code>Collections.shuffle(randomTiles);\n</code></pre>\n<p>Because looking up random indexes and then moving them around in a linked list is just not a good idea.</p>\n<pre><code>fillWithTile(board, tileList.get(randomTiles.get(i * heightTiles + j)), i * Board.TILE_SIZE, j * Board.TILE_SIZE, rnd.nextInt(4));\n</code></pre>\n<p>Way too much is going on in this method, split it out. Why is this happening and what is it doing? Why is there a magic <code>4</code> in there, 4 of what?</p>\n<pre><code>if (2 * i + 1 < rows[rows.length - 1 - j].length()) {\n</code></pre>\n<p>Again, from here we can see how things are being done, but not what or why. The helpful (if incomplete) JavaDoc does help somewhat, but a comment would be appreciated.</p>\n<pre><code>private static Map<Character, Object[][]> getTileList() {\n</code></pre>\n<p>Way too much is being done in this method, the amount of complexity is astounding.</p>\n<pre><code>if (lineChar == 'O') { // ... endless else if's\n</code></pre>\n<p>Here a switch would do wonders, but don't forget the <code>break;</code> statements.</p>\n<pre><code>currentTileContent[i][Board.TILE_SIZE - lineCount] = null;\n</code></pre>\n<p>What about <code>Object tileContent;</code> declaration, then set it in the <code>switch</code>, and in the end assign it to <code>currentTileContent[i][Board.TILE_SIZE - lineCount]</code>. Too much copy / paste if you ask me.</p>\n<pre><code> currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(false, true, false, true);\n</code></pre>\n<p>Ah, a road that goes <code>false, true, false, true</code>. That's not a <code>true</code> road, use <code>enum</code> instead of boolean parameters. It's in Effective Java, which you should read.</p>\n<pre><code> EnumSet<Direction> possibleDirections = EnumSet.of(Direction.RIGHT, Direction.LEFT);\n</code></pre>\n<p>is just soooo much nicer, don't you agree?</p>\n<pre><code>char previous = (i == 0 ? 'O' : currentLine.charAt(i - 1));\nchar next = (i == Board.TILE_SIZE - 1 ? 'O' : currentLine.charAt(i + 1));\nif ((isHorizontalRoad(previous) || i == 0) && !isHorizontalRoad(next)) {\n currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(true, false, false,\n true);\n} else if (!isHorizontalRoad(previous)\n && (isHorizontalRoad(next) || i == Board.TILE_SIZE - 1)) {\n currentTileContent[i][Board.TILE_SIZE - lineCount] = new Road(false, true, true,\n false);\n} else {\n throw new IllegalStateException("Unknown combination on ( " + currentLine + ")");\n}\n</code></pre>\n<p>One value is returned: a <code>Road</code>. Method maybe? So easy to distinguish.</p>\n<pre><code>currentTileContent[i][Board.TILE_SIZE - lineCount] = GoodsSource.SODA;\n</code></pre>\n<p>Ah, now I get it. A <code>Road</code>, <code>GoodsSource</code> a <code>House</code> or nothing is expected. Still, create a marker interface such as <code>TileContent</code> at the very least, and have <code>Road</code> and <code>GoodsSource</code> implement it so you don't need <code>Object</code>, because that's too ugly.</p>\n<pre><code>throw new Error("tiles.txt not available", e);\n</code></pre>\n<p>Not fully readable is maybe a better exception. <code>RuntimeException</code>should be preferred over <code>Error</code> which is commonly not recoverable <em>system wide</em>.</p>\n<pre><code>} else if ((prevHouse = board.get(boardPoint.add(0, -1))) instanceof House\n && ((House) prevHouse).getOrder() == ((House) inTile).getOrder()) {\n // check house below\n board.set(boardPoint, prevHouse);\n</code></pre>\n<p>OK, so you are creating larger houses. I think I can be mean and create a house that's made up of separate parts. I hope that your houses are square :) But really, again, provide methods.</p>\n<p>Enum values can be directly compared, no need to compare <code>order</code> for equality.</p>\n<pre><code>throw new IllegalArgumentException("Should not happen");\n</code></pre>\n<p>I agree there, such an exception is not acceptable.</p>\n<pre><code> return this.canMove[inDirection.ordinal()];\n</code></pre>\n<p>Or <code>possibleDirections.contains(inDirection)</code> (see above?)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T16:57:24.540",
"Id": "248201",
"ParentId": "248019",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T03:37:49.927",
"Id": "248019",
"Score": "3",
"Tags": [
"java"
],
"Title": "Board generator for a Food Chain Magnate implementation"
}
|
248019
|
<p>This project was highly inspired by the popular drawille project, that lets one draw to the terminal using the braille unicode characters.</p>
<p>The advantage of drawing with braille characters compared to normal ASCII characters is simple: Because every "braille-character" is made up of <code>2 x 4 = 8</code> possible spots, we have <code>256</code> possible variants we can draw per character. These <a href="https://en.wikipedia.org/wiki/Braille_Patterns" rel="noreferrer">braille-patterns</a> allow for much "finer/smoother" drawing.</p>
<p>My implementation also comes with a rendering engine that allows for animating whatever is drawn to the screen by using the ncurses library.
My implementation aims to by very performant by:</p>
<ol>
<li>Using minimal amount of memory.</li>
<li>Having very good runtime.</li>
</ol>
<p>while still being easy to use.</p>
<p>Here some examples that demonstrate what can be done with this library. These examples can also be found in <code>examples.c</code>:</p>
<p><a href="https://i.stack.imgur.com/AYcbG.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/AYcbG.gif" alt="Sine-Curve tracking" /></a>
<a href="https://i.stack.imgur.com/HpNCA.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/HpNCA.gif" alt="Spiral" /></a></p>
<p>I am already fairly happy with the implementation of my grid structure, that stores and accesses data in a very compact manner.
I am curious if the performance of the rendering structure can be improved any further? I am already trying to only render what has changed from the previous frame, but maybe I can optimize it even more?</p>
<p>Furthermore, I am unsure if my implementation makes good use of the C-style coding guidelines.
Additionally, I want to make sure the library is user friendly. So, let me know what functionality you (as a user) would expect from this library's API, and if there is anything you miss when using it in the current state.</p>
<p><strong>grid.c</strong></p>
<pre><code>#define _POSIX_C_SOURCE 199309L
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <time.h>
#include "grid.h"
#include "unicode.h"
#include "constants.h"
grid *grid_new(int grid_width, int grid_height)
{
if ((grid_width % 2 != 0) || (grid_height % 4 != 0))
return NULL;
grid *p_grid = calloc(1, sizeof(*p_grid));
p_grid->width = grid_width;
p_grid->height = grid_height;
p_grid->buffer_size = grid_width / group_width * grid_height / group_height;
p_grid->buffer = calloc(p_grid->buffer_size, sizeof(int));
return p_grid;
}
void grid_free(grid *p_grid)
{
free(p_grid->buffer);
free(p_grid);
}
void grid_clear(grid *g)
{
for (int i = 0; i < g->buffer_size; ++i)
{
g->buffer[i] = 0x00;
}
}
void grid_fill(grid *g)
{
for (int i = 0; i < g->buffer_size; ++i)
{
g->buffer[i] = 0xFF;
}
}
void grid_print_buffer(grid *g, char* tag) {
printf(tag);
for (int i = 0; i < g->buffer_size; i++)
{
printf("0x%02x%s", g->buffer[i], i == g->buffer_size - 1 ? "\n" : ",");
}
}
void grid_modify_pixel(grid *g, int x, int y, int value)
{
// ToDo validate coords
int bytes_per_line = g->width / group_width;
int byte_idx = (x / group_width) + (y / group_height) * bytes_per_line;
int bit_idx = (x % group_width) * group_height + (y % group_height);
g->buffer[byte_idx] = (g->buffer[byte_idx] & ~(1 << bit_idx)) | (value << bit_idx);
}
void grid_set_pixel(grid *g, int x, int y)
{
grid_modify_pixel(g, x, y, 1);
}
void grid_unset_pixel(grid *g, int x, int y)
{
grid_modify_pixel(g, x, y, 0);
}
void grid_draw_line(grid *g, int x1, int y1, int x2, int y2)
{
// Bresenham's line algorithm
int x_diff = x1 > x2 ? x1 - x2 : x2 - x1;
int y_diff = y1 > y2 ? y1 - y2 : y2 - y1;
int x_direction = x1 <= x2 ? 1 : -1;
int y_direction = y1 <= y2 ? 1 : -1;
int err = (x_diff > y_diff ? x_diff : -y_diff) / 2;
while (1)
{
grid_set_pixel(g, x1, y1);
if (x1 == x2 && y1 == y2)
{
break;
}
int err2 = err;
if (err2 > -x_diff)
{
err -= y_diff;
x1 += x_direction;
}
if (err2 < y_diff)
{
err += x_diff;
y1 += y_direction;
}
}
}
void grid_draw_triangle(grid *g, int x1, int y1, int x2, int y2, int x3, int y3)
{
// ToDo: Add filling algorithm
grid_draw_line(g, x1, y1, x2, y2);
grid_draw_line(g, x2, y2, x3, y3);
grid_draw_line(g, x3, y3, x1, y1);
}
</code></pre>
<p><strong>grid.h</strong></p>
<pre><code>#ifndef GRID_H
#define GRID_H
typedef struct
{
int width;
int height;
int buffer_size;
int *buffer;
} grid;
grid *grid_new(int grid_width, int grid_height);
void grid_free(grid *p_grid);
void grid_clear(grid *g);
void grid_fill(grid *g);
void grid_print_buffer(grid *g, char* tag);
void grid_modify_pixel(grid *g, int x, int y, int value);
void grid_set_pixel(grid *g, int x, int y);
void grid_unset_pixel(grid *g, int x, int y);
void grid_draw_line(grid *g, int x1, int y1, int x2, int y2);
void grid_draw_triangle(grid *g, int x1, int y1, int x2, int y2, int x3, int y3);
#endif
</code></pre>
<p><strong>renderer.c</strong></p>
<pre><code>#include "grid.h"
#include "unicode.h"
#include "renderer.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "constants.h"
#include <ncurses.h>
#include <unistd.h>
#include <locale.h>
render_context* p_render_context;
const int braille_offset = 0x2800;
const int TRANSFORMATION_MATRIX[8] ={ 0x01, 0x02, 0x04, 0x40, 0x08, 0x10, 0x20, 0x80 };
wchar_t lookup_table[256] ={};
void renderer_new(grid *p_grid) {
// Set locale for ncurses to process unicode correctly
setlocale(LC_ALL, "");
// Generate braille lookup table
grid_generate_lookup_table();
// Create copy of initial grid for caching, but zero out buffer
grid *p_cached_grid = calloc(1, sizeof(*p_grid));
p_cached_grid->width = p_grid->width;
p_cached_grid->height = p_grid->height;
p_cached_grid->buffer_size = p_grid->buffer_size;
p_cached_grid->buffer = calloc(p_grid->buffer_size, sizeof(int));
// Store cached grid in render_context
p_render_context = calloc(1, sizeof(*p_render_context));
p_render_context->p_cached_grid = p_cached_grid;
p_render_context->frames_rendered = 0;
// Initialize ncurses
initscr();
noecho();
curs_set(0);
}
void renderer_update(grid* p_grid)
{
// Notes:
// Should only render the characters that changed from current grid buffer to the cached one
// Iterate over grid and look for differences to cached_grid
for (int i = 0; i < p_grid->buffer_size; i++)
{
// Difference was found, note that this character must be re-rendered
if (p_grid->buffer[i] != p_render_context->p_cached_grid->buffer[i]) {
// Compute row and column index of the character we need to re-render
int pos_x = i % (p_render_context->p_cached_grid->width / group_width);
int pos_y = i / (p_render_context->p_cached_grid->width / group_width);
// Obtain correct braille character
char uc[5];
int braille = lookup_table[p_grid->buffer[i]];
int_to_unicode_char(braille, uc);
// Linebreak if we reached the right end of the grid
if (i % (p_grid->width / group_width) == 0 && i != 0)
{
printw("\n");
}
// Render the braille character at the position that changed
mvprintw(pos_y, pos_x, uc);
//printw("Change index %i [%i->%i] Rerendering coordinate (%i, %i).\n", i, p_render_context->p_cached_grid->buffer[i], p_grid->buffer[i], pos_x, pos_y);
}
}
// ToDo: Update p_cached_grid
p_render_context->frames_rendered++;
//grid_print_buffer(p_render_context->p_cached_grid, "cached: ");
//grid_print_buffer(p_grid, "current: ");
// Update cached buffer with current one
memcpy(p_render_context->p_cached_grid->buffer, p_grid->buffer, sizeof(int) * p_grid->buffer_size);
// Sleep some milliseconds so that changes are visible to the human eye
napms(render_delay_ms);
// Refresh terminal to render changes
refresh();
}
void renderer_free()
{
// Wait before all allocations are free'd
napms(2000);
// Free all allocations and end ncurses window
free(p_render_context->p_cached_grid->buffer);
free(p_render_context->p_cached_grid);
free(p_render_context);
endwin();
}
void grid_generate_lookup_table()
{
for (int i = 0; i < 256; ++i)
{
int unicode = braille_offset;
for (int j = 0; j < 8; ++j)
{
if (((i & (1 << j)) != 0))
{
unicode += TRANSFORMATION_MATRIX[j];
}
}
lookup_table[i] = unicode;
}
}
</code></pre>
<p><strong>renderer.h</strong></p>
<pre><code>#ifndef RENDERER_H
#define RENDERER_H
#include "grid.h"
typedef struct {
grid* p_cached_grid;
int frames_rendered;
} render_context;
void renderer_new(grid* p_grid);
void renderer_update(grid* p_grid);
void renderer_free();
void grid_generate_lookup_table();
#endif
</code></pre>
<p><strong>unicode.c</strong></p>
<pre><code>void int_to_unicode_char(unsigned int code, char *chars)
{
if (code <= 0x7F)
{
chars[0] = (code & 0x7F);
chars[1] = '\0';
}
else if (code <= 0x7FF)
{
// one continuation byte
chars[1] = 0x80 | (code & 0x3F);
code = (code >> 6);
chars[0] = 0xC0 | (code & 0x1F);
chars[2] = '\0';
}
else if (code <= 0xFFFF)
{
// two continuation bytes
chars[2] = 0x80 | (code & 0x3F);
code = (code >> 6);
chars[1] = 0x80 | (code & 0x3F);
code = (code >> 6);
chars[0] = 0xE0 | (code & 0xF);
chars[3] = '\0';
}
else if (code <= 0x10FFFF)
{
// three continuation bytes
chars[3] = 0x80 | (code & 0x3F);
code = (code >> 6);
chars[2] = 0x80 | (code & 0x3F);
code = (code >> 6);
chars[1] = 0x80 | (code & 0x3F);
code = (code >> 6);
chars[0] = 0xF0 | (code & 0x7);
chars[4] = '\0';
}
else
{
// unicode replacement character
chars[2] = 0xEF;
chars[1] = 0xBF;
chars[0] = 0xBD;
chars[3] = '\0';
}
}
</code></pre>
<p><strong>unicode.h</strong></p>
<pre><code>#ifndef UNICODE_H
#define UNICODE_H
void int_to_unicode_char(unsigned int code, char *chars);
#endif
</code></pre>
<p><strong>constants.c</strong></p>
<pre><code>const int group_height = 4;
const int group_width = 2;
const int render_delay_ms = 10;
</code></pre>
<p><strong>constants.h</strong></p>
<pre><code>#ifndef CONSTANTS_H
#define CONSTANTS_H
extern const int group_height;
extern const int group_width;
extern const int render_delay_ms;
#endif
</code></pre>
<p><strong>examples.c</strong></p>
<pre><code>#include <math.h>
#include "grid.h"
#include "renderer.h"
#include <stdio.h>
void example_filling_bar()
{
int width = 100;
int height = 24;
grid *g = grid_new(width, height);
renderer_new(g);
// Fill grid from left to right (simple animation)
renderer_update(g);
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
grid_set_pixel(g, i, j);
}
renderer_update(g);
}
// Free allocations
renderer_free();
grid_free(g);
}
void example_build_block()
{
int width = 100;
int height = 40;
grid *g = grid_new(width, height);
renderer_new(g);
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
grid_set_pixel(g, x, y);
renderer_update(g);
}
}
// Free allocations
renderer_free();
grid_free(g);
}
void example_sine_tracking()
{
int width = 124;
int height = 40;
grid *g = grid_new(width, height);
renderer_new(g);
double shift = 0;
while (1)
{
grid_clear(g);
// Draw line
grid_draw_line(g, 0, height / 2, width - 1, (height + sin(shift) * height) / 2);
// Draw curve
for (int j = 0; j < width; j++)
{
grid_set_pixel(g, j, (height / 2 * sin(0.05 * j + shift) + height / 2));
}
// Move curve
shift += 0.05;
renderer_update(g);
}
// Free allocations
renderer_free();
grid_free(g);
}
void example_spiral_effect()
{
int width = 60;
int height = 32;
grid *g = grid_new(width, height);
renderer_new(g);
// Start with an empty grid
grid_clear(g);
int m = width, n = height;
int sr = 0, sc = 0, er = m - 1, ec = n - 1;
while (sr <= er && sc <= ec)
{
for (int i = sc; i <= ec; ++i)
{
grid_set_pixel(g, sr, i);
renderer_update(g);
}
for (int i = sr + 1; i <= er; ++i)
{
grid_set_pixel(g, i, ec);
renderer_update(g);
}
for (int i = ec - 1; sr != er && i >= sc; --i)
{
grid_set_pixel(g, er, i);
renderer_update(g);
}
for (int i = er - 1; sc != ec && i > sr; --i)
{
grid_set_pixel(g, i, sc);
renderer_update(g);
}
sr++, sc++;
er--, ec--;
}
// Free allocations
renderer_free();
grid_free(g);
}
</code></pre>
<p><strong>examples.h</strong></p>
<pre><code>#ifndef EXAMPLES_H
#define EXAMPLES_H
#include "grid.h"
void example_filling_bar();
void example_build_block();
void example_sine_tracking();
void example_spiral_effect();
#endif
</code></pre>
<p><strong>main.c</strong></p>
<pre><code>#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include "examples.h"
int main()
{
//example_sine_tracking();
//example_build_block();
example_spiral_effect();
return 0;
}
</code></pre>
<p>And finally, the Makefile to compile everything:</p>
<pre><code>prog:
gcc -g -o dots examples.c constants.c grid.c unicode.c renderer.c main.c -Wall -Werror -lncursesw -lm
clean:
rm dots
</code></pre>
<p>I appreciate every feedback! The project is also available on GitHub: <a href="https://github.com/766F6964/DotDotDot" rel="noreferrer">https://github.com/766F6964/DotDotDot</a></p>
<p><strong>Note</strong>: When testing this, make sure you have a terminal font installed that can display braille characters properly, otherwise it will look messed up.</p>
|
[] |
[
{
"body": "<h1>Use named constants consistently</h1>\n<p>You defined <code>grid_width</code> and <code>grid_height</code>, very good, but unfortunately you are not using it consistently. In <code>grid_new()</code> for example, the first line can be replaced with:</p>\n<pre><code>if ((grid_width % group_width != 0) || (grid_height % group_height != 0))\n</code></pre>\n<p>Also, it is customary to have global constants such as these written in ALL CAPS, so it is easier to distinguish from variables.</p>\n<h1>Make use of <code>memset()</code></h1>\n<p>You have written loops in <code>grid_clear()</code> and <code>grid_fill()</code>, but you can easily do this task with <a href=\"https://en.cppreference.com/w/c/string/byte/memset\" rel=\"nofollow noreferrer\"><code>memset()</code></a>, which is more likely to be optimized. For sure, <code>grid_clear()</code> can be rewritten to do <code>memset(g->buffer, 0, g->buffer_size * sizeof(*g->buffer))</code>. If <code>g->buffer</code> was a <code>uint8_t *</code>, then you can also use <code>memset()</code> inside <code>grid_fill()</code>.</p>\n<h1>Use <code>uint8_t</code> for the grid</h1>\n<p>You are only using 8 bits for each character in the grid, so you can store it in an <code>uint8_t</code> instead of an <code>int</code>. This reduces memory usage of the grid by a factor 4, and also allows <code>memset()</code> to be used in <code>grid_fill()</code>.</p>\n<h1>Consider hardcoding the lookup table</h1>\n<p>You might think, what blasfemy is this?! Everyone knows you should avoid hardcoding things! But in this case, the Unicode Braille characters are set in stone, and you are wasting a lot of code to generate the characters, and some CPU cycles everytime you start your program, when you can just write:</p>\n<pre><code>wchar_t lookup_table[256] = L"⠁⠂⠃⠄⠅⠆⠇⡀⡁⡂⡃⡄⡅⡆⡇"\n L"⠈⠉⠊⠋⠌⠍⠎⠏... "\n ...\n L" ...⣿";\n</code></pre>\n<h1>Consider using ncursesw</h1>\n<p>Instead of having to convert from <code>wchar_t</code> to a UTF-8 string yourself, you can use the wide version of ncurses that allows you to print <code>wchar_t</code> strings directly. Since ncurses version 6, this is included by default, and you to print wide strings you can use <a href=\"https://linux.die.net/man/3/mvaddwstr\" rel=\"nofollow noreferrer\"><code>mvaddwstr()</code></a> instead of <code>mvprintw()</code>.</p>\n<h1>Consider not caching the grid yourself</h1>\n<p>A big feature of ncurses is that it caches what is on screen, and will only send the necessary characters and control codes to the terminal to update what has really been changed. You are doing the same yourself, thus duplicating what ncurses is doing.</p>\n<p>I see two ways to get rid of this inefficiency. First, you can do away with your own buffers altogether, and just write directly to the screen with curses functions. Of course, if you need to update a single dot in a Braille character, you need to know what Braille pattern is already on screen. You can read the contents of the screen back with commands like <a href=\"https://linux.die.net/man/3/mvin_wch\" rel=\"nofollow noreferrer\"><code>mvin_wch()</code></a>. The drawback is that reading back individual characters might result in lots of function calls, and you have to decode the Braille character back into a bitmask.</p>\n<p>Another option is to keep a single buffer, and just give the whole buffer to ncurses every refresh. If you think that is inefficient, consider that you yourself were copying the whole buffer to the cached buffer every refresh. If you go this way though, you probably want to have the original buffer for easy manipulation of individual dots, and a second buffer of type <code>wchar_t *</code> that you update in parallel, and that you can send off to ncurses to print in one go. Note, there is also a <a href=\"https://en.cppreference.com/w/c/string/wide/wmemset\" rel=\"nofollow noreferrer\"><code>wmemset()</code></a> which might be helpful here.</p>\n<p>I would suggest going for the second option. You should start benchmarking your code so you will be able to measure its performance objectively.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T13:28:31.177",
"Id": "486042",
"Score": "0",
"body": "Thanks for all the points you mentioned. Definitely very helpful. Not to much f a fan of the hard-coding - but apart from that I agree with almost everything. What are your thoughts on the function naming conventions? For example - I saw some people tend to prefix \"private\" functions with a double underscore? In my case the `grid_modify_pixel()` function would be such a case. Maybe I should do that? And yeah, I think I should try let ncurses do the caching - probably a good idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T21:10:45.730",
"Id": "486080",
"Score": "1",
"body": "Be careful with [underscores at the start of names](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). In my personal projects, I don't use any prefix or postfix for private functions. But if you pick a different convention, make sure you follow it consistently, otherwise it is of no use at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T03:23:56.490",
"Id": "486768",
"Score": "0",
"body": "Fair point. I'll think about it. As for the caching: I think it would be great if ncurses could do most of this. If I got your point correctly, the entire caching structure I currently have is obsolete. I would just pass the entire buffer to ncurses and then it will automatically draw what changed? Maybe you can elaborate a bit on that, as I am a bit unsure what's the best way to implement this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T15:09:12.630",
"Id": "248037",
"ParentId": "248021",
"Score": "3"
}
},
{
"body": "<p>Pretty cool code.</p>\n<p>Little review of some side issues.</p>\n<p><strong><code>sizeof *ptr</code> vs. <code>sizeof type</code></strong></p>\n<p>Code nicely used <code>sizeof *ptr</code> in 2 of 3 cases.</p>\n<pre><code>grid *p_cached_grid = calloc(1, sizeof(*p_grid));\np_cached_grid->buffer = calloc(p_grid->buffer_size, sizeof(int)); // why sizeof(int)\np_render_context = calloc(1, sizeof(*p_render_context));\n</code></pre>\n<p>Recommend to continue that</p>\n<pre><code>// p_cached_grid->buffer = calloc(p_grid->buffer_size, sizeof(int));\np_cached_grid->buffer = calloc(p_grid->buffer_size, sizeof *(p_cached_grid->buffer));\n// or\np_cached_grid->buffer = calloc(p_grid->buffer_size, sizeof p_cached_grid->buffer[0]);\n// or other variations.\n</code></pre>\n<hr />\n<p><strong>Improper handling of <a href=\"https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates\" rel=\"nofollow noreferrer\">Surrogates</a></strong></p>\n<p>Although not important to <em>this</em> code, better to detect surrogates and maybe handle as an error (form Unicode replacement character).</p>\n<hr />\n<p><strong>Bresenham's line algorithm</strong></p>\n<p>A better than usual implementation.</p>\n<p>For <em>this</em> code, no issue seen.</p>\n<p>In <em>general</em> code fails when <code>x1 - x2</code> or <code>y1 - y2</code> overflows. There are ways to handle this using <code>unsigned</code> to handle the difference without resorting to wider math.</p>\n<p>I'd post some sample code, but my ref code is not up to date.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T13:25:54.593",
"Id": "486041",
"Score": "0",
"body": "Thanks for the feedback. Not entirely sure how to realize the surrogate checks in my case? Maybe you can clarify that a bit? Also, looking forward to your Bresenham optimization - I already tried to be as efficient as possible with my implementation, but seems like it can be improved even more :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-27T03:26:15.850",
"Id": "486769",
"Score": "0",
"body": "Can you link your ref code? Curious how exactly this edge case should be handled correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T19:12:21.873",
"Id": "487575",
"Score": "0",
"body": "@766F6964 Still looking to post some ref code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-02T19:20:14.080",
"Id": "487576",
"Score": "0",
"body": "Sure, let me know in case you find it :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T06:08:49.453",
"Id": "248124",
"ParentId": "248021",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T06:06:49.787",
"Id": "248021",
"Score": "10",
"Tags": [
"c",
"console",
"formatting",
"animation",
"unicode"
],
"Title": "Text based rendering/animation engine for the terminal"
}
|
248021
|
<p>Here is my revised code from my other review question <a href="https://codereview.stackexchange.com/questions/247577/node-js-delete-multiple-mysql-linked-records-and-delete-physical-file?noredirect=1#comment485660_247577">Node JS delete multiple MySQL linked records and delete physical file</a></p>
<p>Just would like to hear some reviews if I have the right logic.</p>
<pre><code>router.delete('/:id', (req, res)=>{
function deleteCommentRecords(){
db.beginTransaction(function(err) {
if(err) return res.status(500).end(err.message);
//Delete comment section records
db.query("DELETE FROM commentSchema WHERE PostID = ?", req.params.id, (err, result)=>{
if(err){
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
db.commit((err)=>{
if(err){
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
console.log('Transaction Completed Successfully.');
});
});
});
}
function deletePostSchemaReords(){
// Delete PostSchema records
db.query("delete from postschema where id = ?", req.params.id, (err, result)=>{
if(err) {
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
db.commit((err)=>{
if(err){
db.rollback(()=>{
return res.status(500).end(err.message);
});
}
console.log('Transaction Completed Successfully.');
});
});
}
function loadData(){
// Get filenames from Comments
db.query("SELECT image FROM commentschema WHERE postID = ?", req.params.id, (error, comments_image_output)=>{
if(error) return res.status(500).end(err.message);
// If there is an image
if(comments_image_output.length > 0){
// Foreach image, delete one by one
comments_image_output.forEach(function(row){
try {
console.log(row.image);
fs.unlinkSync(uploadDir + row.image);
console.log('Successfully deleted');
// Query to remove commentSchema records
deleteCommentRecords();
} catch (err) {
// handle the error
}
});
// Redirect back to posts
res.redirect(303, '/admin/posts');
}
deleteCommentRecords();
})
// Get filename from PostSchema
db.query("SELECT filename FROM PostSchema WHERE id = ?", req.params.id, (err,post_image_output)=>{
if(err) return res.status(500).end(err.message);
if(post_image_output.length > 0){
// Foreach image, delete one by one
post_image_output.forEach(function(row){
try {
console.log(row.filename);
fs.unlinkSync(uploadDir + row.filename);
console.log('Successfully deleted files');
deletePostSchemaReords();
} catch (err) {
// handle the error
}
});
}
deletePostSchemaReords();
});
}
loadData();
});
</code></pre>
|
[] |
[
{
"body": "<p>There are some problems with this implementation:</p>\n<ul>\n<li>if both the query in <code>loadData</code> fail, <code>res.status(500).end(err.message)</code> is run twice so you will get an error <code>RESPONSE ALREADY CLOSED</code> that could lead to server crash, and this must be avoided</li>\n<li>you are not using a linter on your code. I can say that because you have the <code>error</code> parameter in the callback, but in the code, you wrote <code>..end(err.message)</code>, so adopt a linter to see these error before they happen in production that would cause a crash of your application since <code>err</code> would be <code>undefined</code></li>\n<li>every request adds in the memory heap the functions <code>loadData</code>, <code>deletePostSchemaReords</code> and <code>deleteCommentRecords</code> causing pressure on the garbage collector and slowing down your endpoints and this can be voided</li>\n<li>a lot of code replicated that must be avoided to have a nice and maintainable endpoint</li>\n<li><code>fs.unlinkSync</code> kills the performance in an API endpoint</li>\n<li><code>deleteCommentRecords()</code> is called for every <code>comments_image_output</code> but this would execute <code>comments_image_output.length</code> times the same query, this is a functional error</li>\n<li>in <code>deleteCommentRecords()</code> a transaction begins and the immediately committed so it is not adding any performance gain: a transaction works best when there are multiple <code>query</code> to execute across multiple tables</li>\n<li>the <code>loadData</code> function is deleting rows from DB, so the name is misbehaviour</li>\n<li>in <code>deletePostSchemaReords</code> there is only a query without the <code>transaction</code> so the rollback is ineffective</li>\n<li>the <code>response</code> object should be managed by one entity otherwise there is too much coupling between general functions (like delete an array of files) and the HTTP protocol</li>\n</ul>\n<p>Here how I would proceed with the refactor.</p>\n<ul>\n<li>I used the callback style (instead of <code>async/await</code>) since you are not using promises</li>\n<li>I assume there is a <code>db</code> and a <code>uploadDir</code> global objects - since are not in the code example</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>router.delete('/:id', (req, res) => {\n loadData(req.params.id, (err, files) => {\n if (err) { return res.status(500).end(err.message) }\n\n // if both query are successful delete from the database\n deleteAll(req.params.id, (err) => {\n if (err) { return res.status(500).end(err.message) }\n\n res.redirect(303, '/admin/posts') // response to the client first\n\n // the database deletion is OK, now delete the files quitely\n const deleteFileArray = files.comment.concat(files.post)\n deleteFiles(deleteFileArray, (err) => {\n if (err) {\n console.log('ops failed to delete files, but who cares?')\n }\n })\n })\n })\n})\n\nfunction loadData (postId, callback) {\n let runs = 0\n const output = { comment: null, post: null, error: null }\n\n db.query('SELECT image FROM commentschema WHERE postID = ?', postId, processQueryResult.bind(null, 'comment', 'image'))\n db.query('SELECT filename FROM PostSchema WHERE id = ?', postId, processQueryResult.bind(null, 'post', 'filename'))\n\n // this function will be executed twice an manage only one callback call\n function processQueryResult (responseType, columnName, error, images) {\n if (error) {\n output.error = error\n } else {\n output[responseType] = images.map(row => uploadDir + row[columnName])\n }\n\n if (++runs === 2) { // call the callback with the sum of the files to delete\n callback(output.error, output)\n }\n }\n}\n\nfunction deleteAll (postId, callback) {\n // Delete PostSchema records\n db.beginTransaction(function (err) {\n if (err) return callback(err)\n\n // Delete comment section records\n db.query('DELETE FROM commentSchema WHERE PostID = ?', postId, (err) => {\n if (err) { return db.rollback(callback.bind(null, err)) }\n\n db.query('DELETE FROM postschema where id = ?', postId, (err) => {\n if (err) { return db.rollback(callback.bind(null, err)) }\n\n db.commit((err) => {\n if (err) { return db.rollback(callback.bind(null, err)) }\n console.log('Transaction Completed Successfully.')\n callback()\n })\n })\n })\n })\n}\n\nfunction deleteFiles (files, callback) {\n let i = files.length\n files.map(function (filepath) {\n fs.unlink(filepath, function (err) {\n if (err) {\n callback(err)\n } else if (--i <= 0) {\n callback(null)\n }\n })\n })\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T18:32:09.510",
"Id": "486173",
"Score": "0",
"body": "Just realized - If there is a comment without an image (Because people can comment without attaching an image). It throws `console.log('ops failed to delete files, but who cares?')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T19:14:17.087",
"Id": "486179",
"Score": "0",
"body": "You need only to change the query to avoid selection of the post without images, you will reduce the payload of the query and all will works as expected"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T14:51:36.407",
"Id": "248244",
"ParentId": "248022",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T07:02:28.487",
"Id": "248022",
"Score": "2",
"Tags": [
"javascript",
"mysql",
"node.js"
],
"Title": "NODE JS Unlink and delete MySQL data"
}
|
248022
|
<p>I am new to async methods and am kinda confused how async is working so what i want for you to do is review this code and tell me does implementing async like this is meaningless</p>
<pre><code>[Route("/Dev/ForceBufferUpdate")]
public async Task<IActionResult> BufferUpdate()
{
bool isAdministrator = await Task.Run(() => {
return Security.IsAdministrator(Request);
});
if(!isAdministrator)
return View("Error", "You don't have permission!");
await Task.Run(() => {
LimitlessSoft.Buffer.Refresh();
});
return Redirect("/Dev");
}
</code></pre>
|
[] |
[
{
"body": "<p>This code is pointless since it creates <a href=\"https://www.codeproject.com/Articles/535635/Async-Await-and-the-Generated-StateMachine\" rel=\"nofollow noreferrer\">async state machine</a> while the code you execute is actually synchronous code.\nSo eventually you get a performance penalty for the creation of a state machine but no reward of asynchronous execution.</p>\n<p>Consider using <code>async</code> and <code>await</code> when you're dealing with IO operations. Usually, such methods already provide asynchronous API. You can spot this as such methods return <code>Task</code> or <code>Task<T></code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T07:24:50.287",
"Id": "485783",
"Score": "0",
"body": "What if `Security.IsAdministrator()` takes 3 second to run. Is then using async useful?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T09:44:08.743",
"Id": "485796",
"Score": "0",
"body": "In case you're operating with I/O that would make sense. Otherwise you might consider offloading this operation into `System.Threading.Thread`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T14:49:36.917",
"Id": "248035",
"ParentId": "248033",
"Score": "2"
}
},
{
"body": "<p>The async/await method isn't really about running parallel code; it is about releasing the current thread instead of having it wait for i/o bound processing.</p>\n<p>Imagine 20 people call that end point; on the first call there is a thread of execution create. If Security.IsAdministrator hits a database then this is IO and that calling thread would block until the IO was complete.</p>\n<p>Using Task.Run and async/await will not cause the thread to block, the thread gets released to can process the next 19 calls. Once IO is complete another thread, or the same one, picks up the processing.</p>\n<p>So I would say it is not meaningless, if the tasks involve IO.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T18:40:26.807",
"Id": "248332",
"ParentId": "248033",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T13:03:57.830",
"Id": "248033",
"Score": "1",
"Tags": [
"c#",
"performance",
"asp.net"
],
"Title": "ASP.NET Core async iactionresult"
}
|
248033
|
<p>I am creating a social network that let's users upload a profile picture. I just want to know if this is a secure way of doing it. Thanks.</p>
<pre><code><?php
include 'includes/header.php';
include 'includes/form_handlers/settings_handler.php';
//$userPic = '';
$date_time = date('Y-m-d_H-i-s');
if(!empty($userLoggedIn)) {
if (isset($_FILES['fileToUpload'])) {
$errors= array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size = $_FILES['fileToUpload']['size'];
$width = 1500;
$height = 1500;
$file_tmp = $_FILES['fileToUpload']['tmp_name'];
$file_type = $_FILES['fileToUpload']['type'];
$tmp = explode('.',$_FILES['fileToUpload']['name']);
$file_ext=strtolower (end ($tmp));
$extensions = array( "jpeg", "jpg", "png", "gif");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if ($file_size > 8097152) {
$errors[] = 'File size must be 2 MB';
}
if ($width > 1500 || $height > 1500) {
echo"File is to large";
}
if(!$errors) {
$userPic = md5($_FILES["fileToUpload"]["name"]) . $date_time . " " . $file_name;
$profilePic = move_uploaded_file($file_tmp,"assets/images/profile_pics/" . $userPic);
$file_path = "assets/images/profile_pics/" . $userPic;
$stmt = $con->prepare("UPDATE users SET profile_pic = ? WHERE username = ?");
$stmt->bind_param('ss', $file_path, $username);
$stmt->execute();
$stmt->close();
header('Location: settings.php');
exit();
}
}
} else {
echo "Invalid Username";
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:25:27.440",
"Id": "485984",
"Score": "3",
"body": "Rather than add all that code to the question after an answer has already been posted, please post a follow up question with the added code. By updating the code you have invalidated the answer. Please see the [help center](https://codereview.stackexchange.com/help/someone-answers)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:44:21.923",
"Id": "485988",
"Score": "0",
"body": "@pacmaninbw I just wanted to know if that's how my profile picture code should be"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:50:56.760",
"Id": "485989",
"Score": "4",
"body": "That;s a valid question, but I and 2 other more experienced members of the community were notified about the update that invalidated the answer. The community as a whole prefers that follow up questions be separate questions. You might notice that it was another user that rolled back the question to its original state. The 2nd Monitor chat room has a bot that identifies edits that invalidate answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T22:56:15.507",
"Id": "486091",
"Score": "0",
"body": "fyi: `File is to large` should be `File is **too** large` @user13477176"
}
] |
[
{
"body": "<p>This is my personal opinion, but I'd say the following:</p>\n<ol>\n<li>The code should be formatted, I'd personally look at <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"noreferrer\">PSR-12</a> as this standard should be followed when possible.</li>\n<li>move_uploaded_file doesn't protect against directory traversal. You should use basename on <code>$_FILES['fileToUpload']['tmp_name']</code> and some other forms of validation</li>\n<li>Checking the file extension with <code>if(in_array($file_ext,$extensions)=== false)</code> doesn't prevent a user from uploading a malicious file they could for instance use a magic byte to trick the server into thinking it's a certain type of file. You should take a look at <a href=\"https://www.php.net/manual/en/class.finfo.php\" rel=\"noreferrer\">finfo</a> and the first example on <a href=\"https://www.php.net/manual/en/features.file-upload.php\" rel=\"noreferrer\">file upload</a></li>\n<li>You're create an array of errors, currently that's being checked in an if statement and is then thrown away. If you aren't planning on using it you might be better just returning out of the function early rather than continuing execution.</li>\n<li>Depending on how unique the filename should be you might want to use something like <code>uniqid(mt_rand(), true)</code></li>\n<li>move_uploaded_file will replace a file if it already exists, you might want to check that this exists before you overwrite an existing file. Depending on your naming solution it's very unlikely to occur but under high load for long periods of time this could happen more often than you think.</li>\n<li>You're using <code>UPDATE users SET profile_pic = ? WHERE username = ?</code> I'd assume that this value exists in the database as the user needs to be logged in. However, if you aren't sure if the field exists or not (I haven't seen the database) I'd personally use: <code>INSERT INTO users (profile_pic, username) VALUES (?,?) ON DUPLICATE KEY UPDATE profile_pic=?, username=?</code> this will insert into the table if the row doesn't exist but will update it if it does.</li>\n<li>You've set a local variable called width and height and are comparing them to the same value. I assume this was meant to check the actual file dimensions?</li>\n</ol>\n<p>I hope this helps in some way :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:18:47.620",
"Id": "485983",
"Score": "0",
"body": "Is the second part of my code secure ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T22:34:20.097",
"Id": "485985",
"Score": "2",
"body": "Because [the original post was rolled back](https://codereview.stackexchange.com/questions/248036/secure-upload-script#comment485984_248036) the \"second part of the code\" isn't visible anymore. Per the help center page [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) an option is to post a follow-up question with the second part of the code."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T21:13:02.227",
"Id": "248107",
"ParentId": "248036",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T15:04:34.810",
"Id": "248036",
"Score": "3",
"Tags": [
"php",
"mysql",
"mysqli"
],
"Title": "Secure upload script"
}
|
248036
|
<p>I adding some pathfinding to a game I'm working on. It primarily used A* with as suggested in the pathfinding articles at <a href="https://www.redblobgames.com/pathfinding" rel="nofollow noreferrer">reb blob games</a>.<br />
It works, but isn't very fast.<br />
It is a square grid map that (at the moment) has uniform movement cost, but in the future I will to add weights that make paths avoid enemy units etc.<br />
Here is some code:</p>
<p>Here is my FIFO-queue header, heavily influenced by the <a href="https://github.com/nothings/stb/blob/master/stretchy_buffer.h" rel="nofollow noreferrer">stb stretchy_buffer.h</a>:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef QUEUE_H
#define QUEUE_H
#include <stdlib.h>
#include <string.h>
#include <assert.h>
// Entire data block
#define queue_raw(a) ((int*) (a)-3)
// Number of elements queue can hold
#define queue__s(a) (queue_raw(a)[0])
// Index of the first element
#define queue__f(a) (queue_raw(a)[1])
// Number of queued elements
#define queue__c(a) (queue_raw(a)[2])
#define queue_count(a) ((a) ? queue__c(a) : 0)
#define queue_empty(a) (queue_count(a)==0)
#define queue_push(a,v) (queue__maybegrow(a,1), (a)[queue__norm(a, (queue__f(a)+(queue__c(a)++)))]=v)
#define queue_append(a,n) (queue__maybegrow(a,n), queue__c(a)+=(n), &(a)[queue__c(a)-n])
#define queue_peek(a) ((a) ? (a)[queue__f(a)] : 0)
#define queue_pop(a) (queue_empty(a) ? 0 : (queue__c(a)--, queue__f(a)=queue__norm(a,queue__f(a)+1), ((a)[queue__f(a) ? queue__f(a)-1 : queue__s(a)-1])))
#define queue_last(a) (queue_empty(a) ? 0 : (a)[queue__norm(queue__f(a)+queue__c(a))])
#define queue_poplast(a) (queue_empty(a) ? 0 : (queue__c(a)--, (a)[queue__norm(queue__f(a)+queue__c(a))]))
#define queue_free(a) ((a) ? free(queue_raw(a)),0 : 0)
#define queue__norm(a,i) (((i)%queue__s(a)+queue__s(a))%queue__s(a))
#define queue__grow(a,n) queue__growf((void*) &(a), (n), sizeof(*(a)))
#define queue__needgrow(a,n) ((a)==0 || queue_count(a)+n > queue__s(a))
#define queue_resize(a,n) (queue__maybegrow((a),(n)))
#define queue__maybegrow(a,n) (queue__needgrow((a),(n)) ? queue__grow((a),(n)) : (void)0)
static void queue__growf(void** arr, int increment, size_t itemsize) {
// Grow the size of *arr by increments*itemsize bytes.
// Does not change queue__c(*arr)
int c = queue_count(*arr);
if (*arr && !c) queue__f(*arr) = 0;
int s = *arr ? queue__s(*arr) : 0;
int f = *arr ? queue__f(*arr) : 0;
int m = c + increment;
assert(m > s);
if (f) {
// Reallocate the queue with the first element at index 0
void* buf = malloc(itemsize*m + sizeof(int)*3);
assert(buf);
if (buf) {
void* arr_buf = (void*) ((int*) buf + 3);
if (f + c <= s) {
memcpy(arr_buf, (unsigned char*)(*arr) + f*itemsize, itemsize * c);
} else {
memcpy(arr_buf, (unsigned char*)(*arr) + f*itemsize, itemsize * (s-f));
memcpy((unsigned char*) arr_buf + itemsize*(s-f), *arr, itemsize * (f+c-s));
}
queue__s(arr_buf) = m;
queue__f(arr_buf) = 0;
queue__c(arr_buf) = c;
queue_free(*arr);
*arr = arr_buf;
}
} else {
void* buf = realloc(*arr ? queue_raw(*arr) : 0, itemsize*m + sizeof(int)*3);
assert(buf);
if (buf) {
*arr = (void*) ((int*) buf + 3);
queue__s(*arr) = m;
queue__f(*arr) = 0;
queue__c(*arr) = c;
}
}
}
#endif
</code></pre>
<p>And my priority queue:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef PRIORITY_QUEUE_H
#define PRIORITY_QUEUE_H
typedef struct {
int v;
int p;
} pqueue_pair;
struct pqueue {
int size;
int count;
pqueue_pair* data;
};
void pqueue_push(struct pqueue* h, int v, int p);
int pqueue_pop(struct pqueue* h);
#endif
#ifdef PRIORITY_QUEUE_IMPLEMENTATION
static inline void swap(pqueue_pair* a, pqueue_pair* b) {
pqueue_pair tmp;
memcpy(&tmp, a, sizeof(pqueue_pair));
memcpy(a, b, sizeof(pqueue_pair));
memcpy(b, &tmp, sizeof(pqueue_pair));
}
static void heapify(struct pqueue* h, int i) {
int largest = i;
while (true) {
int l = 2*i + 1;
int r = l + 1;
if (l < h->count && h->data[l].p < h->data[largest].p) largest = l;
if (r < h->count && h->data[r].p < h->data[largest].p) largest = r;
if (largest != i) {
swap(h->data+largest, h->data+i);
i = largest;
} else {
break;
}
}
}
void pqueue_push(struct pqueue* h, int v, int p) {
if (h->count >= h->size) {
h->count --;
printf("Overflowing pqueue of with %d elements! Last element as priority of %d\n", h->size, h->data[h->count].p);
}
h->data[h->count].v = v;
h->data[h->count].p = p;
h->count ++;
if (h->count > 1) {
for (int i=h->count/2-1; i>=0; i--) {
heapify(h, i);
}
}
}
int pqueue_pop(struct pqueue* h) {
assert(h->count);
int v = h->data[0].v;
h->count --;
memcpy(h->data, h->data+h->count, sizeof(pqueue_pair));
if (h->count > 1) {
heapify(h, 0);
}
return v;
}
#endif
#endif
</code></pre>
<p>And finally, the code itself (at least most of it; I cut the game-specific stuff):</p>
<pre class="lang-c prettyprint-override"><code>uint8_t* obstacles = 0;
unsigned int obstacles_size = 0;
#define MAX_LANDMARK_DISTANCE 0xff
uint8_t* landmarks = 0;
int* landmark_positions = 0;
int num_landmarks = 0;
int landmark_size = 0;
// Functions for but shifting into an array of single-bit bools.
// I don't know if the speed difference compared to normal
// indexing, but I assume the size difference is worth it?
static inline uint8_t get_obstacle(int i) {
assert(i/8 < obstacles_size);
return obstacles[i/8] & (1 << i%8);
}
static inline void set_obstacle(int i) {
assert(i/8 < obstacles_size);
obstacles[i/8] |= 1 << i % 8;
}
static inline void unset_obstacle(int i) {
assert(i/8 < obstacles_size);
obstacles[i/8] = ~((~obstacles[i/8]) | 1 << i%8);
}
static int get_neighbors(int* neighbors, int i, int s) {
// Fill neighbors with flattened coords of tiles adjacent to i and return the count
assert(i >= 0 && i < s*s && s >= 0);
int x = i % s;
int y = i / s;
int count = 0;
if (x > 0) neighbors[count++] = i-1; // East
if (x < s-1) neighbors[count++] = i+1; // West
if (y > 0) neighbors[count++] = i-s; // North
if (y < s-1) neighbors[count++] = i+s; // South
return count;
}
void update_map(/* Game-specific arguments */) {
// This function is called every time the map
// changes, (i.e., wall is remove, building added/destroyed)
// It happens fairly often.
// Update obstacles here, and allocates them if need be
// Update the landmarks
#define L(i) (landmarks + (i)*landmark_size)
// This part here is rather slow
memset(landmarks, 0xff, num_landmarks*landmark_size*sizeof(*landmarks));
for (int l=0; l<num_landmarks; l++) {
assert(landmark_positions[l] >= 0 && landmark_positions[l] < size);
L(l)[landmark_positions[l]] = 0;
int* queue = 0;
queue_resize(queue, map->size * 3);
queue_push(queue, landmark_positions[l]);
while (queue_count(queue)) {
int current = queue_pop(queue);
assert(L(l)[current] < MAX_LANDMARK_DISTANCE);
int neighbors[4];
int neighbors_count = get_neighbors(neighbors, current, map->size);
for (int n=0; n<neighbors_count; n++) {
int next = neighbors[n];
if (get_obstacle(next)) continue;
int new_cost = L(l)[current] + 1;
if (new_cost < L(l)[next]) {
L(l)[next] = new_cost;
if (new_cost < MAX_LANDMARK_DISTANCE) queue_push(queue, next);
}
}
}
queue_free(queue);
}
#undef L
}
static inline int distance_heuristic(int a, int b, int w) {
return abs(a%w - b%w) + abs(a/w - b/w);
}
static inline int heuristic(int a, int b, int w) {
int d = distance_heuristic(a, b, w);
for (int i=0; i<num_landmarks; i++) {
int da = landmarks[i*landmark_size + a];
int db = landmarks[i*landmark_size + b];
int dd = abs(da - db);
if (dd > d) {
d = dd;
}
}
return d;
}
void nav_path_find(int map_size, int sx, int sy, int gx, int gy, uint16_t* path_out, uint8_t* path_length, uint8_t max_path) {
int start = sy*map->size + sx;
int goal = gy*map->size + gx;
// The maps are always square
int size = map_size * map_size;
const int pq_size = map->size*3;
pqueue_pair pq_data[pq_size];
for (int i=0; i<pq_size; i++) pq_data[i].p = -1;
struct pqueue pq = {.size=pq_size, .count=0, .data=pq_data};
pqueue_push(&pq, start, 1);
// Create the closed list the size of the entire map which stores
// the flattened Cartesian coordinates of the previous tile such that
// y * map_width + x = i
// and
// x == i % map_size && y == (int) i / map_size
int came_from[size];
for (int i=0; i<size; i++) came_from[i] = -1;
came_from[start] = 0;
uint16_t cost[size];
memset(cost, 0xff, sizeof(*cost) * size);
bool found_path = false;
while (pq.count > 0 && !found_path) {
int current = pqueue_pop(&pq);
assert(came_from[current] >= 0);
if (current == goal) {
found_path = true;
}
int neighbors[4];
int neighbors_count = get_neighbors(neighbors, current, map->size);
for (int n=0; n<neighbors_count; n++) {
int next = neighbors[n];
if (get_obstacle(next)) continue;
int new_cost = cost[current] + 1;
if (came_from[next] < 0 || new_cost < cost[next]) {
cost[next] = new_cost;
pqueue_push(&pq, next, new_cost + heuristic(next, goal, map_width));
came_from[next] = current;
}
}
}
// Here we trace the path back and return the first `max_path` steps
}
</code></pre>
<p>The map obstacles will be fairly dynamic and change over the course of the game, thus landmarks that were placed in the map editor will possibly become less useful or entirely surrounded with weeds.<br />
Suggestions/methods/resources for dynamically placing landmarks and making my code faster/prettier in general would be appreciated.</p>
<p>One idea I had is to had an array the size of the map that holds the index to the respective tiles' heap location, which so you could change the priority of an item kinda like this:</p>
<pre class="lang-c prettyprint-override"><code>int pq_indices[size];
for (int i=0; i<size; i++) pq_indices[i] = -1;
// Then later when looping through neighbors
if (pq_indices[next] != -1) {
// Push it
} else {
pq_data[next].priority = new_priority;
pqueue_update();
}
</code></pre>
<p>And I would add that array the <code>pqueue</code> so it would somehow get updated when pushing/popping/heapifying.</p>
<p>It also might be worth noting that maps are probably between 64x64 tiels (tiny map) to 512x512 tiles (enormous map).</p>
|
[] |
[
{
"body": "<p>So one thing I thought of is basing the priority queue's size on the heuristic rather than the map size:</p>\n<pre class=\"lang-c prettyprint-override\"><code>const int pq_size = heuristic(start, goal, map_size) * 3;\n</code></pre>\n<p>Also when the priority queue overflows only rewrite the last element if the new one is better:</p>\n<pre class=\"lang-c prettyprint-override\"><code>if (h->count >= h->size) {\n printf("Overflowing pqueue of with %d elements! Last element as priority of %d\\n", h->size, h->data[h->count-1].p);\n if (h->data[h->count-1] <= p) {\n return;\n }\n h->count --;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:53:01.597",
"Id": "248049",
"ParentId": "248040",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T16:24:00.010",
"Id": "248040",
"Score": "5",
"Tags": [
"performance",
"c",
"game",
"pathfinding",
"a-star"
],
"Title": "A* and ALT pathfinding in C tips"
}
|
248040
|
<p>It's my first time here, so please accept my apologies in advance if something is wrong with my approach to asking.</p>
<p>I've been learning Python for a couple of months and I decided to have a go at a small project that I felt able to complete on my own: a version of the card game UNO, using PyGame for the graphical interface. I've settled with a version that mostly works, I've had a great time building it and certainly my child of 4 has a great time playing it :) It's nothing fancy, a two player game against a dumb AI, but I guess it's nice for a start.</p>
<p>Now, the code is over 600 lines long and as I was adding features I knew there were far better ways to write it, some of which I won't have even heard of, but I wanted to get as far as possible. So I would be pleased to get some code reviews, the harsher the better.</p>
<p>Below I've left the full code, there are a number of comments in Spanish but that's mostly for my own consumption. If anyone does take the time to review and destroy it I will be eternally thankful :)</p>
<pre><code>import pygame
import random
import os
import sys
main_dir = os.path.split(os.path.abspath(__file__))[0]
os.environ['SDL_VIDEO_CENTERED'] = '1'
class Button: # Con esta clase crearemos una colección de botones con el color, coordenadas y texto que definamos
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.w = w
self.h = h
self.rect = (self.x, self.y, self.w, self.h)
self.color = []
self.text = []
def contains_point(self, point):
"""Return True if my sprite rectangle contains point pt """
(my_x, my_y) = self.x, self.y
my_width = self.w
my_height = self.h
(x, y) = point
return my_x <= x < my_x + my_width and my_y <= y < my_y + my_height
class Text:
def __init__(self, x, y, text):
self.font = pygame.font.SysFont("Fixedsys Excelsior", 48)
self.x = x
self.y = y
self.position = (self.x, self.y)
self.text = self.font.render(text.format(), True, (255, 255, 255))
class CardSprite: # Vamos a cargar una imagen que contiene todas las cartas.
# Esta imagen es un objeto diferente a la carta, por tanto tendrá su propia clase
def __init__(self): # Cargamos una lista de coordenadas donde están las cartas
self.sheet = pygame.image.load(os.path.join(main_dir, 'UNO', "Copia UNO.jpg"))
self.x = self.sheet.get_width() # 800
self.y = self.sheet.get_height() # 882
def load_grid_images(self):
sheet_rect = self.sheet.get_rect()
sheet_width, sheet_height = sheet_rect.size
sprite_rects = []
cardheighty = 0
cardwidthx = 0
cardsizex = self.x // 10
cardsizey = 125
for card in range(56): # El rango sería mejor definirlo en función del número de cartas del mazo, revisar
card_coordinates = [cardwidthx, cardheighty, cardsizex, cardsizey]
sprite_rects.append(card_coordinates)
cardwidthx += cardsizex
if cardwidthx >= self.x:
cardwidthx = 0
cardheighty += cardsizey
return self.images_at(sprite_rects)
def image_at(self, rectangle, colorkey=None):
"""Load a specific image from a specific rectangle."""
# Loads image from x, y, x+offset, y+offset.
rect = pygame.Rect(rectangle)
image = pygame.Surface(rect.size)
image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0, 0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image
def images_at(self, rects, colorkey=None):
"""Load a whole bunch of images and return them as a list."""
return [self.image_at(rect, colorkey) for rect in rects]
class Card:
suits = ["Rojo", "Amarillo", "Verde", "Azul", "Comodín"] # suit es un atributo de clase
ranks = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
"pierdeturno", "cambiasentido", "robados", "eligecolor", "robacuatro"] # rank es otro atributo de clase
def __init__(self, suit=0,
rank=0): # __init__ crea una instancia de la clase Card; cada carta tiene un suit y un rank
self.suit = suit
self.rank = rank
self.position = []
self.image = None
def contains_point(self, point):
""" Return True if my sprite rectangle contains point pt """
(my_x, my_y) = self.position
my_width = self.image.get_width()
my_height = self.image.get_height()
(x, y) = point
return my_x <= x < my_x + my_width and my_y <= y < my_y + my_height
class Deck:
def __init__(self):
self.cards = [] # Creamos el atributo cards. Recordar que los atributos en __init__, aparte de self, son opcionales
for suit in range(4):
for rank in range(0, 10):
self.cards.append(Card(suit, rank))
for suit in range(4):
for rank in range(10, 13):
self.cards.append(Card(suit, rank))
for suit in range(4, 5):
for rank in range(13, 15):
self.cards.append(Card(suit, rank))
self.cards.append(Card(suit, rank))
sprite = CardSprite()
images = sprite.load_grid_images()
i = 0
for image in images:
self.cards[i].image = image
i += 1
questionmark = sprite.image_at([720, 750, 80, 125])
self.image = questionmark
self.position = (650, 256)
def shuffle(self):
rng = random.Random()
rng.shuffle(self.cards)
def remove(self, card):
if card in self.cards:
self.cards.remove(card) # Usamos el método remove
return True
return False
def pop(self):
return self.cards.pop() # Pop toma la última carta y la reparte
def is_empty(self):
return self.cards == [] # True si no quedan cartas en el mazo
def deal(self, hands, num_cards=999):
num_hands = len(hands)
for i in range(num_cards):
if self.is_empty():
break
card = self.pop()
hand = hands[i % num_hands]
hand.add(card)
def contains_point(self, point):
""" Return True if my sprite rectangle contains point pt """
(my_x, my_y) = self.position
my_width = self.image.get_width()
my_height = self.image.get_height()
(x, y) = point
return my_x <= x < my_x + my_width and my_y <= y < my_y + my_height
class Hand(Deck):
pass
def __init__(self, name=""):
super().__init__()
self.cards = []
self.name = name
if name == "AI":
self.status = 1 # jugador controlado por el ordenador
else:
self.status = 0 # jugador humano
def add(self, card):
self.cards.append(card)
class UNOGame:
def __init__(self):
self.all_buttons = []
self.hands = []
self.colors = ([234, 26, 39], [248, 224, 0], [0, 164, 78], [2, 149, 216], [255, 165, 0],
[0, 0, 0]) # Rojo, amarillo, verde, azul, naranja, negro
surface_sizex = 1280 # Ancho del tablero, en píxeles
surface_sizey = 640 # Alto del tablero, en píxeles
self.main_surface = pygame.display.set_mode((surface_sizex, surface_sizey)) # Creamos el tablero
self.play_area = (320, 264)
self.surface_color = (19, 136, 8) # Red/Green/Blue; la superficie del tablero será de color verde oscuro
self.deck = Deck()
self.deck.shuffle()
def place_cards(self):
# Definimos un patrón para pegar las cartas una junto a otra
[paste_x, paste_y] = [64, 480]
[paste_xAI, paste_yAI] = [64, 32]
# Definimos la posición que ocuparán las cartas sobre el tablero al empezar la partida
for hand in self.hands:
for card in hand.cards:
card.hidden = self.deck.image # Para el atributo hidden usamos la carta con el signo de interrogación,
# que anteriormente asignamos al atributo image del mazo
if hand.name == "AI":
card.position = [paste_xAI, paste_yAI]
paste_xAI += 85
else:
card.position = [paste_x, paste_y]
paste_x += 85
def place_buttons(self):
size = 45
x = self.play_area[0]
y = self.play_area[1]
# Definimos los botones para elegir entre los cuatro colores, así como el botón de pasar turno y el del color en juego
for n in range(4):
a_button = Button(x - 55, y + 145, size, size)
x += 50
self.all_buttons.append(a_button)
coordinates = [850, 275, 125, 25], [750, 325, 330, 25], [225, 400, 175, 30], [575, 400, 175, 30]
for c in coordinates:
a_button = Button(c[0], c[1], c[2], c[3])
self.all_buttons.append(a_button)
c = 0
for button in self.all_buttons:
button.color = self.colors[c]
c += 1
if c == 6:
break
self.all_buttons[4].text = self.font.render("Pasar turno".format(), True, (0, 0, 0))
self.all_buttons[5].text = self.font.render("El color en juego es el {0}".format(self.color_in_play), True,
(255, 255, 255))
self.all_buttons[6].text = self.font.render("Volver a jugar".format(), True, (0, 0, 0))
self.all_buttons[6].color = self.colors[0]
self.all_buttons[7].text = self.font.render("Salir del juego".format(), True, (0, 0, 0))
self.all_buttons[7].color = self.colors[3]
def blit_buttons(self, i=0, j=6):
for n in range(i, j):
button_color = self.all_buttons[n].color
button_rect = (self.all_buttons[n].x, self.all_buttons[n].y, self.all_buttons[n].w, self.all_buttons[n].h)
if n == 5:
self.all_buttons[n].text = self.font.render("El color en juego es el {0}".format(self.color_in_play),
True, (255, 255, 255))
button_text = self.all_buttons[n].text
self.main_surface.fill(button_color, button_rect)
try:
self.main_surface.blit(button_text, button_rect)
except:
TypeError
def update_cards(self):
# Ponemos las cartas sobre el tablero
for hand in self.hands:
for card in hand.cards:
if hand.name == "AI":
self.main_surface.blit(card.hidden,
card.position) # Si es una carta de la IA, elegimos la imagen del signo de interrogación
else:
self.main_surface.blit(card.image, card.position)
self.main_surface.blit(self.deck.image, self.deck.position)
self.main_surface.blit(self.card_in_play.image, self.play_area)
def update_surface(self):
# last_play = Text(600, 200, "La carta en juego es " + self.card_in_play.suits[self.color] + self.card_in_play.ranks[self.number])
# Pintamos la superficie
self.main_surface.fill(self.surface_color)
self.update_cards()
self.blit_buttons(4, 6)
pygame.display.flip()
def play_discard(self):
self.deck.cards = self.discard_deck.cards # Asignamos al mazo las cartas del mazo de descartes
self.deck.shuffle() # Barajamos el nuevo mazo
self.discard_deck.cards = [] # Vaciamos el mazo de descartes para reiniciar el ciclo
def start_UNO(self): # Creamos la partida del juego de cartas UNO, que es un tipo de juego de cartas
# Iniciamos el módulo pygame
pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(os.path.join(main_dir, 'UNO', "lobby.mp3"))
pygame.mixer.music.play(-1)
# Creamos una superficie de juego, donde colocar las cartas
pygame.display.set_caption('UNO')
self.main_surface.fill(self.surface_color)
self.font = pygame.font.SysFont("Fixedsys Excelsior", 32)
# Cargamos el logo del juego para la carga inicial
logo = pygame.image.load(os.path.join(main_dir, 'UNO', "UNO_logo_small.png"))
h = logo.get_height()
w = logo.get_width()
welcome = Text(345, 580, "Pulsa cualquier tecla para continuar")
surface_sizex = 1280 # Ancho del tablero, en píxeles
surface_sizey = 640 # Alto del tablero, en píxeles
self.main_surface.blit(logo, (surface_sizex // 2 - w // 2, surface_sizey // 2 - h // 2))
self.main_surface.blit(welcome.text, welcome.position)
pygame.display.flip()
while True:
event = pygame.event.poll()
if event.type == pygame.KEYDOWN: # Hemos pulsado una tecla
break
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Permitimos al jugador introducir su nombre
name = Text(100, 100, "Introduce tu nombre (pulsa enter cuando hayas terminado):")
self.main_surface.fill(self.surface_color)
self.main_surface.blit(name.text, name.position)
pygame.display.flip()
self.player_name = ''
font = pygame.font.SysFont("Fixedsys Excelsior", 48)
enter = 0
while enter == 0:
event = pygame.event.poll() # Buscar eventos y asignárselos a la variable event
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
self.player_name = self.player_name[:-1]
elif event.key == pygame.K_RETURN:
enter = 1
else:
self.player_name += event.unicode
self.main_surface.fill(self.surface_color)
txt_surface = font.render(self.player_name, True, pygame.Color('dodgerblue2'))
self.main_surface.blit(txt_surface, (100, 200))
self.main_surface.blit(name.text, name.position)
pygame.display.flip()
self.main_surface.fill(self.surface_color)
tachan = Text(100, 300, "¡Bienvenido, " + self.player_name + "! La partida comenzará en unos segundos")
self.main_surface.blit(tachan.text, tachan.position)
pygame.display.flip()
self.names = [self.player_name, "AI"]
self.main_surface.fill(self.surface_color)
def play_UNO(self): # Iniciamos la partida de UNO
# Creamos las manos del juego
pygame.mixer.music.load(os.path.join(main_dir, 'UNO', "lobby.mp3"))
pygame.mixer.music.play(-1)
for name in self.names:
self.hands.append(Hand(name))
# Repartimos las cartas
self.deck.deal(self.hands, 7 * len(self.names)) # Tomamos el objeto mazo que pertenece al objeto juego (self),
# y repartimos siete cartas a cada jugador
# Colocamos las cartas sobre el tablero
self.place_cards()
# Sacamos una carta para empezar a jugar
self.card_in_play = self.deck.pop()
self.card_in_play.position = self.play_area
self.color = self.card_in_play.suit # Me interesa separar el color de la carta, para poder implementar el comodín eligecolor
self.number = self.card_in_play.rank
# Creamos algunas cositas más parabotones extra
self.color_in_play = self.card_in_play.suits[self.color]
turn = 0
pierdeturno = 0
self.has_drawn = 2 # Para cubrir el caso en que la carta inicial sea una carta de efectos
i = 0
self.place_buttons()
self.update_surface()
self.discard_deck = Deck() # Creamos un mazo de descartes
self.discard_deck.cards = [] # Vaciamos el mazo de descartes
while True:
# Comenzamos el bucle estableciendo los efectos en función de la carta en juego (self.card_in_play):
if self.card_in_play.rank == 10: # "pierdeturno": # El turno pasará al otro jugador
if self.has_drawn == 0:
pierdeturno += 1
self.has_drawn = 1
elif self.card_in_play.rank == 11: # "cambiasentido":
self.has_drawn = 1 # Esto es simplemente para poder simplificar la fórmula de efectos y expresarla como 10 <= rank <= 14
elif self.card_in_play.rank == 12: # "robados":
if self.has_drawn != 1: # No queremos que al comenzar el siguiente turno se vuelvan a robar dos cartas
for n in range(2):
if self.deck.is_empty(): # Si no quedan cartas en el mazo
self.play_discard()
self.hands[(i + 1) % len(self.hands)].cards.append(
self.deck.pop()) # Robo dos cartas y las añado a mi mano
self.has_drawn = 1
elif self.card_in_play.rank == 13: # "eligecolor":
if self.has_drawn != 1: # No queremos que al final de este turno se vuelvan a robar cuatro cartas
# Aquí hay que añadir un árbol de decisión según sea jugador IA o jugador humano, para elegir el color
if self.hands[i].status == 1: # si el jugador es IA
rng = random.Random()
self.color = rng.randrange(0, 4)
else: # si el jugador es humano
self.blit_buttons(0, 4)
pygame.display.flip()
has_picked_color = 0
while has_picked_color == 0:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN: # Hemos hecho click
place_of_click = event.dict["pos"]
b = 0
for button in self.all_buttons[0:4]:
if button.contains_point(place_of_click):
has_picked_color = 1
self.color = b
b += 1
self.card_in_play.suit = self.color
self.color_in_play = self.card_in_play.suits[self.color]
self.has_drawn = 1
elif self.card_in_play.rank == 14: # "robacuatro":
if self.has_drawn != 1: # No queremos que al final de este turno se vuelvan a robar cuatro cartas
for n in range(4):
if self.deck.is_empty(): # Si no quedan cartas en el mazo
self.play_discard()
self.hands[(i + 1) % len(self.hands)].cards.append(
self.deck.pop()) # Robo cuatro cartas y las añado a mi mano
# Aquí hay que añadir un árbol de decisión según sea jugador IA o jugador humano, para elegir el color
if self.hands[i].status == 1: # si el jugador es IA
rng = random.Random()
self.color = rng.randrange(0, 4)
else: # si el jugador es humano
self.blit_buttons(0, 4)
pygame.display.flip()
has_picked_color = 0
while has_picked_color == 0:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN: # Hemos hecho click
place_of_click = event.dict["pos"]
b = 0
for button in self.all_buttons[0:4]:
if button.contains_point(place_of_click):
has_picked_color = 1
self.color = b
b += 1
self.card_in_play.suit = self.color
self.color_in_play = self.card_in_play.suits[self.color]
self.has_drawn = 1
# Actualizamos las cartas
self.place_cards()
self.update_surface()
# Los efectos ya están consolidados (esperemos). Ahora hay que definir el cambio de turno
turn += 1
i = (turn + pierdeturno) % len(
self.hands) # 0 en el primer turno, salvo que la primera carta en juego sea pierdeturno
self.playable_cards = []
suits_in_hand = []
hand = self.hands[i].cards # Llamamos hand a la mano que está jugando, para que el código sea más legible
# Comienza el siguiente turno, propiamente dicho
# Determinamos si tenemos cartas en la mano que podamos jugar:
for card in hand:
suits_in_hand.append(
card.suit) # Anotamos el color de cada carta, para comprobar después si podemos usar el comodín robacuatro
if card.suit == self.color or card.rank == self.card_in_play.rank or card.rank == 13: # "eligecolor":
# Si la carta comparte color o número con la que está en juego, o si es el comodín de elegir color
self.playable_cards.append(card)
if self.color not in suits_in_hand: # Si no tenemos ninguna carta del mismo color que la que está en el área de juego
for card in hand:
if card.rank == 14: # "robacuatro":
self.playable_cards.append(card) # Lo añadimos a las cartas que podemos jugar
if self.hands[i].status == 1: # si el jugador es IA
self.AI_plays(hand)
else: # si el jugador es humano
self.human_plays(hand)
# Consideraciones de final de turno, a continuación
self.color = self.card_in_play.suit
self.color_in_play = self.card_in_play.suits[self.color]
if self.deck.is_empty(): # Si no quedan cartas en el mazo
self.play_discard()
self.place_cards()
self.update_surface()
if self.hands[i].is_empty(): # Si no quedan cartas en la mano
end_game = 0
self.main_surface.fill(self.surface_color)
if self.hands[i].name == self.player_name: # Ha ganado el jugador humano
pygame.mixer.music.load(os.path.join(main_dir, 'UNO', "win.mp3"))
pygame.mixer.music.play(-1)
win = Text(100, 300, "¡Enhorabuena, " + self.player_name + "! Has ganado la partida")
self.main_surface.blit(win.text, win.position)
else: # Ha ganado la IA
pygame.mixer.music.load(os.path.join(main_dir, 'UNO', "loss.mp3"))
pygame.mixer.music.play(-1)
loss = Text(100, 300, "¡Lo sentimos, " + self.player_name + "! El ordenador ha ganado la partida")
self.main_surface.blit(loss.text, loss.position)
self.blit_buttons(6, 8)
pygame.display.flip()
while end_game == 0:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN: # Hemos hecho click
place_of_click = event.dict["pos"]
for button in self.all_buttons[6:8]:
if button.contains_point(place_of_click):
if button == self.all_buttons[6]:
end_game = 1
self.deck = Deck()
self.deck.shuffle()
self.play_UNO()
else:
pygame.quit()
sys.exit()
pygame.display.flip()
def AI_plays(self, hand):
if not self.playable_cards: # No podemos jugar ninguna carta, tenemos que robar
drawn_card = self.deck.pop()
if drawn_card.suit == self.color or drawn_card.rank == self.card_in_play.rank or drawn_card.suit == 4: # "Comodín":
# Si la carta robada comparte color o número con la que está en juego, o si es un comodín
self.card_in_play = drawn_card # Jugamos la carta robada
self.has_drawn = 0
# hand.remove(drawn_card) ¡No es necesario, porque no llega a añadir la carta a la mano! Dará error
self.discard_deck.cards.append(drawn_card)
else:
hand.append(drawn_card) # Añadimos la carta robada a nuestra mano
else: # No nos hace falta robar, porque tenemos en la mano cartas que podemos jugar
rng = random.Random()
selected_card = self.playable_cards[
rng.randrange(0, len(self.playable_cards))] # La IA elige la carta que jugar
self.card_in_play = selected_card # La carta elegida será la próxima carta en juego
self.has_drawn = 0
self.card_in_play.position = self.play_area # Adjudicamos a la carta elegida la zona de juego
hand.remove(selected_card)
self.discard_deck.cards.append(selected_card)
def human_plays(self, hand):
self.has_drawn = 0
has_played = 0
has_playable_cards = 0
while self.has_drawn == 0:
if not self.playable_cards: # No podemos jugar ninguna carta, tenemos que robar
for event in pygame.event.get(): #event = pygame.event.poll() # Buscar eventos y asignárselos a la variable event
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN: # Hemos hecho click
place_of_click = event.dict["pos"]
if self.deck.contains_point(place_of_click):
drawn_card = self.deck.pop()
if drawn_card.suit == self.color or drawn_card.rank == self.card_in_play.rank or drawn_card.suit == 4: # "Comodín":
self.playable_cards.append(drawn_card)
has_playable_cards = 1
else:
pygame.display.flip()
self.has_drawn = 1
hand.append(drawn_card)
# Actualizamos las cartas
self.place_cards()
self.update_surface()
else:
has_playable_cards = 1
self.has_drawn = 1
while has_played == 0:
if has_playable_cards == 1: # Podemos jugar
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN: # Hemos hecho click
place_of_click = event.dict["pos"]
for card in self.playable_cards:
if card.contains_point(place_of_click):
self.card_in_play = card
hand.remove(card)
self.discard_deck.cards.append(card)
has_played = 1
self.has_drawn = 0
else: # Tenemos que pasar turno
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN: # Hemos hecho click
place_of_click = event.dict["pos"]
if self.all_buttons[4].contains_point(place_of_click):
has_played = 1
def main():
game = UNOGame()
game.start_UNO()
game.play_UNO()
# call the "main" function if running this script
if __name__ == '__main__': main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:13:10.347",
"Id": "485743",
"Score": "3",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T08:09:52.470",
"Id": "485791",
"Score": "0",
"body": "Hi! Sorry for any inconvenience. Anyway, I've managed to fix it in a very unelegant way, I think. I will edit the post and update the code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:07:22.420",
"Id": "248042",
"Score": "2",
"Tags": [
"python",
"beginner",
"object-oriented",
"game",
"pygame"
],
"Title": "Python code for UNO Game"
}
|
248042
|
<p>Since I had to almost start all of the code again with first refactor and an eye opening advice on a random Overflow question, here it is again:</p>
<p>This is a code that selects the right sheet according to the day of the week(date) and time(Now).</p>
<p>The code finds the day of the week (in French), determines if we are in night or day shift depending on time limits also depending of the days: it then concatenates the 2 ex: "Thursday" + "night" and finds the sheets name accordingly.</p>
<p>If it does not find a match (Friday night or weekend) it selects Friday sheet</p>
<p><a href="https://i.stack.imgur.com/FdAVc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FdAVc.png" alt="feuille" /></a></p>
<p>The code is runned by workbook_open and beforeSave, so it need to be optimized as much as possible.</p>
<p>Here the whole code:</p>
<pre><code> Public Sub SelectionDeQuartAuto()
Dim wsactivate As Boolean ' Boolean turns true if ws is activated
Dim joursemaine As String ' Day of the week
joursemaine = Application.WorksheetFunction.Text(Date, "[$-40c]DDDD")
Dim shift As String
shift = Shiftselect(IsDayShift(Now)) ' Returns "Day" or "Night" shifts
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets ' Loops trough all .visible ws to find a match w day+shift
If ws.Visible Then
If InStr(1, ws.Name, joursemaine & " " & shift, vbTextCompare) > 0 Then 'If ws.name contain day of the week + day or night shift
ws.Activate
wsactivate = True
Exit For
End If
End If
Next
If wsactivate = False Then ' If no match
Sheets("Vendredi jour").Activate ' Activate friday
End If
End Sub
Public Function Shiftselect(Isday As Boolean) As String
' Returns "Day" or "Night" string depending on IsDay boolean
If Isday Then
Shiftselect = "jour"
Else
Shiftselect = "soir"
End If
End Function
Public Function IsDayShift(ByVal DateTime As Date) As Boolean
' Return a true boolean if we are outside night shift boundaries, return false elseways
If weekday(DateTime, vbSunday) = vbThursday Then ' If we are thursday night shift boundaries are different
IsDayShift = TimeValue(DateTime) > TimeValue("03:00:00") And TimeValue(DateTime) < TimeValue("15:15:00") ' If Time is outside night shift limit assume its day shift
Else ' Monday to wednesday + friday (no night shift on friday) use normal boundaries
IsDayShift = TimeValue(DateTime) > TimeValue("03:00:00") And TimeValue(DateTime) < TimeValue("16:15:00")
End If
End Function
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:10:56.800",
"Id": "248043",
"Score": "4",
"Tags": [
"vba",
"excel",
"automation"
],
"Title": "Sheet display in function of date and time on open and save (2)"
}
|
248043
|
<p>I was hoping to get some input on a class module I'm designing to abstract away the boilerplate of utilizing asynchronous queries in VBA. cQueryable supports both synchronous and asynchronous queries. So you could do something like call a package to populate temp tables. This would be done synchronously because you'd want this to be completed before you executed your select queries. After, you would then execute select queries on each of the temp tables asynchronously.</p>
<p>This code really just abstracts away a lot of the functionality in the ADODB library. I tried to name my properties and methods similarly to what the objects in that library use where possible. My connectionString property is named similarly to the same one in the ADODB.Connection object. And my CreateParam method is named similarly to the createParameter method of the ADODB.Command object.</p>
<p>A few of the new procedures I've introduced are the sql property. This holds the sql query to be executed (this maps to commandtext in the command object). Another is ProcedureAfterQuery. This is to hold the name procedure to be called by the connection object after it raises an event when the query completes. Others are SyncExecute and AsyncExecute which should describe what they do in their names.</p>
<p>One thing to note about these two is that SyncExecute is a function whereas AsyncExecute is a subroutine. I wanted SyncExecute to return a recordset when it completes. But for AsyncExecute, I wanted it to be a sub I didn't want to imply that it returned anything. I use similar (but different) code to do this. So I think I violate the DRY principle. I could consolidate these two to call one shared subroutine procedure. That shared procedure would then be more complicated, but the code would at least be shared. I don't have a preference one way or another.</p>
<p>Although CreateParam is similar to the CreateParameter method of the command object, there's two differences. One is that the order of the arguments is different. This is mainly because the size and direction parameters are listed as optional parameters with default values. Their default values can just be used when the value is numeric, but size must be specified if the value is a string. So in certain situations, size is optional, whereas in others it's required. And the query will fail if it isn't provided.</p>
<p>Other things I didn't consider (or test) is that I've read that ADODB can be used essentially anywhere a driver can be provided. So this could be used on Excel workbooks, perhaps text files, and other sources rather than just databases. So perhaps the synchronous and asynchronous queries would work there as well. But that's not what I set out to design or test.</p>
<p>I'd appreciate constructive criticism.</p>
<pre class="lang-vb prettyprint-override"><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "cQueryable"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit
'Requires a refernce to the Microsoft ActiveX Data Objects 6.1 Library (or equivalent)
Private WithEvents mASyncConn As ADODB.Connection
Attribute mASyncConn.VB_VarHelpID = -1
Private mSyncConn As ADODB.Connection
Private mConn As ADODB.Connection
Private mComm As ADODB.Command
Private mSql As String
Private mProcedureAfterQuery As String
Private mAsync As Boolean
Private mConnectionString As String
Private Const mSyncExecute As Long = -1
Private Sub Class_Initialize()
Set mComm = New ADODB.Command
Set mConn = New ADODB.Connection
End Sub
Public Property Let Sql(value As String)
mSql = value
End Property
Public Property Get Sql() As String
Sql = mSql
End Property
Public Property Let ConnectionString(value As String)
mConnectionString = value
End Property
Public Property Get ConnectionString() As String
ConnectionString = mConnectionString
End Property
Public Property Let procedureAfterQuery(value As String)
mProcedureAfterQuery = value
End Property
Public Property Get procedureAfterQuery() As String
procedureAfterQuery = mProcedureAfterQuery
End Property
Public Sub createParam(pName As String, pType As DataTypeEnum, pValue As Variant, Optional pDirection As ParameterDirectionEnum = adParamInput, Optional pSize As Long = 0)
Dim pm As ADODB.Parameter
With mComm
Set pm = .CreateParameter(name:=pName, Type:=pType, direction:=pDirection, value:=pValue, size:=pSize)
.Parameters.Append pm
End With
End Sub
Public Function SyncExecute()
Set mSyncConn = mConn
If connectionSuccessful Then
With mComm
.CommandText = mSql
Set .ActiveConnection = mSyncConn
Set SyncExecute = .execute(Options:=mSyncExecute)
End With
End If
End Function
Public Sub AsyncExecute()
Set mASyncConn = mConn
If connectionSuccessful Then
With mComm
.CommandText = mSql
Set .ActiveConnection = mASyncConn
.execute Options:=adAsyncExecute
End With
End If
End Sub
Private Function connectionSuccessful() As Boolean
If mConn.State = adStateClosed Then
mConn.ConnectionString = mConnectionString
End If
On Error GoTo errHandler
If mConn.State = adStateClosed Then
mConn.Open
End If
connectionSuccessful = (mConn.State = adStateOpen)
On Error GoTo 0
Exit Function
errHandler:
Debug.Print "Error: Connection unsuccessful"
connectionSuccessful = False
End Function
Private Sub mASyncConn_ExecuteComplete(ByVal RecordsAffected As Long, ByVal pError As ADODB.Error, adStatus As ADODB.EventStatusEnum, ByVal pCommand As ADODB.Command, ByVal pRecordset As ADODB.Recordset, ByVal pConnection As ADODB.Connection)
If mProcedureAfterQuery <> "" Then
Call Application.Run(mProcedureAfterQuery, pRecordset)
End If
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T18:47:29.933",
"Id": "485748",
"Score": "0",
"body": "In order to respond to events of an object in a scripting text file you will need to declare the library and type of object. The only way this can be done is using `CreateObject`. For example `Set Connection = WScript.CreateObject(\"ADODB.Connection\", \"Connection_\")`. With this setup `Sub Connection_ExecuteComplete(RecordsAffected, pError, adStatus, pCommand, pRecordset, pConnection)` will fire correctly. But I'm not sure that this will work in a scripting class. Hopefully, with a little duck, one of the real Gurus can elaborate on this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T22:13:46.880",
"Id": "485760",
"Score": "0",
"body": "Ah I have no idea. Thanks for the heads up though. My code wasn't really meant to handle a scripting text file. So if it doesn't work I'll just put it as a caveat on my github."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T02:28:24.867",
"Id": "485774",
"Score": "0",
"body": "@beyphy I have had to use the ADODB library so extensively that I have created several of my own wrapper classes. Overtime I have improved them, from an architectural standpoint and by documenting and addressing the various bugs in the library. It took many man hours to get to the point I have it at now, so I figure it is worth sharing with others so they don't have to do the same. Saying that, here is the github link to the code: https://github.com/rickmanalexander/ADODBDataAccessAPI."
}
] |
[
{
"body": "<h2>Private Function connectionSuccessful() As Boolean</h2>\n<p>The name suggest that you are testing to see if the Connection has already been opened when in fact it is used to opening the Connection and test if it was successful.</p>\n<blockquote>\n<pre><code>Private Function OpenConnection() As Boolean \n</code></pre>\n</blockquote>\n<p>This name tells you that you are opening a Connection. Since the return type is Boolean, it is natural to assume that the function will return True only if the Connection was successful.</p>\n<p>Having the error handler escape errors and print a message to the Immediate Window is counter productive. As a developer I don't instinctively look to the Immediate Window for error messages. As a user I will notify the developer of the error message that was raised down the line and not at the point of impact. Considering that your code uses callback procedures, there is no guarantee that an error will ever be raised. The only thing that is certain is that there are going to be problems somewhere down the line.</p>\n<p>You should definitely raise a custom error it the <code>mConnectionString</code> is not set. A custom error message for the failed connection is not necessary (if you remove the error handler) because an ADODB error will be thrown at the point where this procedure was called.</p>\n<h2>Public Sub AsyncExecute()</h2>\n<p>Consider raising an error if the callback procedure is not set.</p>\n<h2>Private Sub Class_Terminate()</h2>\n<p>This method should be used to close the connection.</p>\n<h2>mConn, mASyncConn, and mSyncConn</h2>\n<p>There is no need to use three different Connection variable. You are doing more work and obfuscating the code. Using a variable such as <code>AsyncMode As Boolean</code> will give you the same feedback and simplify the code making it easier to read.</p>\n<h2>Naming Conventions</h2>\n<p>Having <code>value</code> and <code>execute</code> lower case changes the case for all other variables and properties with the same names. For this reason, I use Pascal Case for all my variables that do not have some sort of prefix.</p>\n<p>Mathieu Guindon's <a href=\"https://rubberduckvba.wordpress.com/2018/04/24/factories-parameterized-object-initialization/\" rel=\"nofollow noreferrer\">Factories: Parameterized Object Initialization</a></p>\n<h2>Other possible improvements</h2>\n<p>A public event would allow you to use <code>cQueryable</code> in other custom classes.</p>\n<blockquote>\n<pre><code>Public Event AsyncExecuteComplete(pRecordset As Recordset)\n</code></pre>\n</blockquote>\n<p>The ability to chain queries together seems like a natural fit.</p>\n<blockquote>\n<pre><code>Public Function NextQuery(Queryable AS cQueryable) AS cQueryable\n Set NextQuery = Queryable \n Set mQueryable = Queryable \nEnd Function\n</code></pre>\n</blockquote>\n<p>This will allow you to run multiple queries in order without the need of multiple callback.</p>\n<blockquote>\n<pre><code>CreateTempQuery.NextQuery(FillTempTableQuery).NextQuery(UpdateEmployeesTableQuery)\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T14:47:27.000",
"Id": "485828",
"Score": "0",
"body": "Thanks! For the note on the connection variables, I need at least two (the async and the non-async one) to prevent the event from firing each time an execution happens. So I thought to use three to keep things consistent. I thought about potentially creating a method with a paramArray() that accepted multiple SQL queries. I believe the connection is closed when the object gets dereferenced. One issue I think happens is that, if there's an exception, the connection stays open. This makes sense because the object is still referenced. So perhaps I should add error handling to address that case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:31:16.753",
"Id": "485835",
"Score": "0",
"body": "@beyphy I would still prefer to let the event fire and do nothing if `AsyncMode = False`. You should rename `procedureAfterQuery` to `procedureAfterAsyncQuery` if you don't want it to run after execution has completed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T23:27:44.233",
"Id": "248064",
"ParentId": "248045",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:14:59.943",
"Id": "248045",
"Score": "7",
"Tags": [
"sql",
"vba",
"asynchronous",
"adodb"
],
"Title": "VBA-Sync code feedback"
}
|
248045
|
<p>I have a working code as below. Is there any better way to return <code>nil</code> after the <code>each</code> loop and <code>unless else</code> in the below example?</p>
<pre><code>def find_member(member_name)
unless members.empty?
members.each do |member|
if member.name == member_name
return member
end
end
nil
else
nil
end
end
</code></pre>
<p>I should pass <code>nil</code> in each case because there are different conditions in other methods where this method is called. That is the reason why I have written the code as above.</p>
|
[] |
[
{
"body": "<p>Ruby has a <code>detect</code> method, so your entire method can be replaced with</p>\n<pre><code>members.detect { |member| member.name == member_name }\n</code></pre>\n<p>As an aside, <code>each</code> works fine for empty arrays, hence the <code>empty?</code> check you have is completely unnecessary even if you keep the explicit loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-04T18:51:33.687",
"Id": "504394",
"Score": "0",
"body": "Are you the lifter or the liftee?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T20:05:40.397",
"Id": "248052",
"ParentId": "248046",
"Score": "5"
}
},
{
"body": "<p>It's a method on <code>Enumerable</code>. It is also aliased to <code>find</code> which may be a more descriptive verb depending on the context. Using the built-in functions will always be faster because they are implemented in <code>c</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-29T22:21:46.167",
"Id": "248638",
"ParentId": "248046",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "248052",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:28:55.260",
"Id": "248046",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Return nil after loop and also in unless block in Ruby"
}
|
248046
|
<p>I tried to do a tic tac toe game, so, to base myself in something, I searched through multiple tic tac toe codes and took some ideas from them to implement on my code. Here's the result and I would like anyone to make an analisys of it and tell me your opinion about it!</p>
<p>It's almost completely funcional, the only thing that needs to be fixed is the A.I. because there isn't any of it there, it just chooses a random number to place X or O. Later I'll try to build it by myself.</p>
<pre><code># Simple TIC TAC TOE game
import random
import time
board = {1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '}
winning_combinations = ((1, 2, 3), (4, 5, 6), (7, 8, 9), # Horizontals
(1, 4, 7), (2, 5, 8), (3, 6, 9), # Verticals
(1, 5, 9), (3, 5, 7)) # Diagonals
# Displays the visual output in the terminal
def print_board():
print(board[1] + '|' + board[2] + '|' + board[3])
print('-+-+-')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-+-+-')
print(board[7] + '|' + board[8] + '|' + board[9])
print('\n')
# Defines who starts the game by chance
def who_starts():
sides = ['X', 'O']
print('The game is starting.')
print('Flipping coin...')
time.sleep(1)
if random.random() > 0.5:
print('The computer won.\n')
computer_side = random.choice(sides)
sides.remove(computer_side)
player_side = sides[0]
print(f"The computer has chosen to be {computer_side}.")
print(f"You will be {player_side[0]}.")
return player_side, computer_side, False # This boolean will be used later on play()
else:
print('You won.\n')
while True:
player_side = input('Choose your side: ').upper()
if player_side not in sides:
print('You can only choose X or O\n')
else:
sides.remove(player_side)
computer_side = sides[0]
print(f'You have chosen to be {player_side}.')
print(f'The computer will be {computer_side}.')
return player_side, computer_side, True # This boolean will be used later on play()
# Allows the player place X or O in the board. The 'side' means whether X or O
def player_place(side):
check_if_full()
occupied = False
while not occupied:
try:
local = int(input('Choose somewhere to place it (1-9): '))
if local not in range(1, 10):
print('Invalid number. ')
else:
if board[local] != ' ':
print('This place is already occupied. \n')
else:
board[local] = side
print_board()
time.sleep(0.5)
check_win(side, 'O') if side == 'X' else check_win(side, 'X')
occupied = True
except ValueError:
print('Enter a number! ')
# Allows the (dumb!) A.I. to place X or O in the board. The 'side' means whether X or O
def ai_place(side):
check_if_full()
local = random.randint(1, 9)
while board[local] != ' ':
local = random.randint(1, 9)
board[local] = side
time.sleep(1)
print_board()
time.sleep(0.5)
check_win('O', side) if side == 'X' else check_win('X', side)
# Analyses winning patters in the board, if it detects it, it will end the game
def check_win(player_side, computer_side):
for combination in winning_combinations:
player_index = 0
computer_index = 0
for integer in combination:
if board[integer] == player_side:
player_index += 1
if player_index == 3:
print('You won!. GAME OVER')
exit()
elif board[integer] == computer_side:
computer_index += 1
if computer_index == 3:
print('You lost!, the AI defeated you. GAME OVER')
exit()
# Checks if the board is full
def check_if_full():
count = 0
for i in range(1, 10):
if board[i] != ' ':
count += 1
if count == 9:
print('GAME OVER')
exit()
# Executes the game with a loop based on the boolean value of the variable 'value'
def play():
player, computer, value = who_starts()
while True:
if value is True:
player_place(player), ai_place(computer) # The player won, so will start first
else:
ai_place(computer), player_place(player) # The computer won, starting first
# Driver code
if __name__ == '__main__':
play()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>Variables and logic 1</strong></p>\n<p>I think it would be more standard to call the sides 0 and 1 and use those numbers to represent them.</p>\n<p>If you do, you can simplify the side choosing code a bit, for example if the computer chooses <code>computer_side = 1</code> then you do <code>player_side = 1 - computer_side</code> and vice versa. If the computer was 1 then player becomes 0 and it works both ways.</p>\n<p><strong>Logic 2</strong></p>\n<p><code>check_win('O', side) if side == 'X' else check_win('X', side)</code></p>\n<p>This is unnecessarily complex and you don't need two different cases for it.\nAfter each move, you just need to check if anybody wins, since only one player can win after any move (by the game rules).</p>\n<p>All you need to keep track of is which side the player is, and in the <code>check_win</code> function you check both sides if either wins, then act accordingly.</p>\n<p><strong>Logic 3</strong></p>\n<pre><code>def ai_place(side):\n check_if_full()\n</code></pre>\n<p>It seems very unintuitive for me to check if the board is full before placing and then ending the game. I would check if the board is full <strong>after</strong> each move, not <strong>before</strong>.</p>\n<p>It's also related so the <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> . A function called <code>ai_place</code> should only handle ai_placing, and it should already be taken care of that the board is not full (by checking that somewhere else, before calling this function).</p>\n<p><strong>Naming</strong></p>\n<pre><code>def play():\n player, computer, value = who_starts()\n</code></pre>\n<p>Since <code>value</code> represents "should the player start?" then it should be named something that indicates that too, for example <code>player_starts</code> is a fine name.</p>\n<p>That also makes the next line\n<code>if player_starts:</code> which is <strong>very</strong> readable, rather than <code>if value is True:</code></p>\n<p><strong>Other</strong></p>\n<pre><code>if value is True:\n player_place(player), ai_place(computer) # The player won, so will start first\nelse:\n ai_place(computer), player_place(player) # The computer won, starting first\n</code></pre>\n<p>You are "abusing" <a href=\"https://realpython.com/python-lists-tuples/\" rel=\"nofollow noreferrer\">tuple notation</a> here for no reason. A comma between two expressions creates a tuple.\nJust put these on one line each since you're not actually using the tuple for anything.</p>\n<pre><code>if value is True:\n player_place(player)\n ai_place(computer) # The player won, so will start first\nelse:\n ai_place(computer)\n player_place(player) # The computer won, starting first\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T22:56:17.997",
"Id": "486385",
"Score": "0",
"body": "thank you for fixing the readability! It's cleaner now"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T15:32:12.073",
"Id": "248195",
"ParentId": "248047",
"Score": "3"
}
},
{
"body": "<p>The final edited code is posted at the bottom.</p>\n<ol>\n<li>You should just use a Python list to represent the board, as it looks like you are using the dictionary as a list anyway. Dictionaries are useful when you need to have a unique value map to another value. In this situation, you can just use the user's input to access a value in a list. Since lists start at index 0, we also need to update the winning combinations list as well:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>board = [' '] * 9 # Creates a list with 9 items, where each item is ' '.\nwinning_combinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), # Horizontals\n (0, 3, 6), (1, 4, 7), (2, 5, 8), # Verticals\n (0, 4, 8), (2, 4, 6)) # Diagonals\n</code></pre>\n<p>We can then update the <code>check_if_full</code> to be the following:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def check_if_full():\n if ' ' not in board:\n print('GAME OVER')\n exit()\n</code></pre>\n<ol start=\"2\">\n<li>You're <code>print_board</code> function is fine, but it can written in a more concise way. Consider:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def print_board():\n # We store each row string here. Usually if you are joining many strings\n # together, it's more efficient to append them to a list then join them.\n # Here it doesn't matter, but keeps things short and concise.\n output = []\n # Because the length of each row is constant, we can just step by the length of each row in our loop.\n for row_start in range(0, len(board), 3):\n # Nicer way to creating the row string, without string concatenation\n output.append("{}|{}|{}\\n".format(board[row_start], board[row_start + 1], board[row_start + 2]))\n output.append("-+-+-\\n")\n # Joins the strings in the list.\n print("".join(output))\n</code></pre>\n<p>If you don't like this way, your original function is fine. Here it is, but with updated accesses to the <code>board</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def print_board():\n print(board[0] + '|' + board[1] + '|' + board[2])\n print('-+-+-')\n print(board[3] + '|' + board[4] + '|' + board[5])\n print('-+-+-')\n print(board[6] + '|' + board[7] + '|' + board[8])\n print('\\n')\n</code></pre>\n<ol start=\"3\">\n<li>It is best practice to make sure your functions only do one thing when possible. This makes it easier to reason what a function does because it keeps your functions shorter and you know exactly what it should be doing. So your <code>who_starts</code> function should only decide who starts the game, it shouldn't choose who is assigned to what side and also ask for user input. You should separate it into two functions <code>who_starts</code> and <code>assign_sides</code>. I will rename <code>who_starts</code> to <code>starts_first</code>:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def assign_sides():\n sides = ['X', 'O']\n player_side = None\n comp_side = None\n\n if random.random() > 0.5:\n # Computer wins\n print('The computer won.\\n')\n comp_side = random.choice(sides)\n sides.remove(comp_side)\n player_side = sides[0]\n print(f"The computer has chosen to be {comp_side}.")\n print(f"You will be {player_side[0]}.")\n else:\n print('You won.\\n')\n while True:\n player_side = input('Choose your side: ').upper()\n if player_side not in sides:\n print('You can only choose X or O\\n')\n else:\n sides.remove(player_side)\n comp_side = sides[0]\n print(f'You have chosen to be {player_side}.')\n print(f'The computer will be {comp_side}.')\n break\n\n return player_side, comp_side\n\n\n# Chooses who goes first. If True, the player goes first. Otherwise the computer\n# goes first.\ndef starts_first():\n # You can actually just have this in the play function, but to be explicit\n #we'll make it its own function.\n return random.random() > 0.5\n\n# This is what play will look like after our changes\ndef play():\n player, computer = assign_sides()\n user_goes_first = starts_first()\n while True:\n if user_goes_first is True:\n # The player won, so will start first\n player_place(player), ai_place(computer)\n else:\n # The computer won, starting first\n ai_place(computer), player_place(player)\n</code></pre>\n<ol start=\"4\">\n<li>You can simplify your <code>check_win</code> function. Instead of checking if either the user or AI wins after a move has been made, you just have to check if the current player has one after their move has been made. So if the user makes their move, then we only check if they have won. This same logic applies to the AI. We then get the following adjustments:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def player_place(side):\n check_if_full()\n while True:\n try:\n local = int(input('Choose somewhere to place it (1-9): ')) - 1\n if local not in range(0, 9):\n print('Invalid number. ')\n else:\n if board[local] != ' ':\n print('This place is already occupied. \\n')\n else:\n board[local] = side\n print_board()\n time.sleep(0.5)\n if did_win(side):\n print("You won!")\n exit()\n break\n except ValueError:\n print('Enter a number! ')\n\n\ndef ai_place(side):\n check_if_full()\n local = random.randint(0, len(board) - 1)\n while board[local] != ' ':\n local = random.randint(0, len(board) - 1)\n board[local] = side\n time.sleep(1)\n print_board()\n time.sleep(0.5)\n\n if did_win(side):\n print("Computer won! Game over")\n exit()\n\n\ndef did_win(side):\n # The following is called tuple unpacking. Because each item in\n # winning_combinations is a tuple, we can simply `unpack` it by\n # writing (square1, square2, square3), where each variable\n # represents the value in the tuple. We can then use these directly\n # without having to go tuple[index]. This makes for digestible code.\n for (square1, square2, square3) in winning_combinations:\n row = [board[square1], board[square2], board[square3]]\n # all checks whether all items in an iterable are the same. The argument\n # given is a list comprehension (which just returns a list). Thus we are\n # checking if every item in the row is equal to the current player's side.\n if all(item == side for item in row):\n return True\n return False\n</code></pre>\n<p>If anything is unclear, feel free to comment.</p>\n<p>Final Code:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Simple TIC TAC TOE game\nimport random\nimport time\n\nboard = [' '] * 9\nwinning_combinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), # Horizontals\n (0, 3, 6), (1, 4, 7), (2, 5, 8), # Verticals\n (0, 4, 8), (2, 4, 6)) # Diagonals\n\n\n# Displays the visual output in the terminal\ndef print_board():\n output = []\n for row_end in range(0, len(board), 3):\n output.append("{}|{}|{}\\n".format(\n board[row_end], board[row_end + 1], board[row_end + 2])\n )\n output.append("-+-+-\\n")\n print("".join(output))\n\n\n# Assigns each player to either 'X' or 'O'\ndef assign_sides():\n sides = ['X', 'O']\n player_side = None\n comp_side = None\n\n if random.random() > 0.5:\n # Computer wins\n print('The computer won.\\n')\n comp_side = random.choice(sides)\n sides.remove(comp_side)\n player_side = sides[0]\n print(f"The computer has chosen to be {comp_side}.")\n print(f"You will be {player_side[0]}.")\n else:\n print('You won.\\n')\n while True:\n player_side = input('Choose your side: ').upper()\n if player_side not in sides:\n print('You can only choose X or O\\n')\n else:\n sides.remove(player_side)\n comp_side = sides[0]\n print(f'You have chosen to be {player_side}.')\n print(f'The computer will be {comp_side}.')\n break\n\n return player_side, comp_side\n\n\n# Chooses who goes first. If True, the player goes first. Otherwise the computer goes first.\ndef starts_first():\n # You can actually just have this in the play function, but to be explicit we'll make it its own function.\n return random.random() > 0.5\n\n\n# Allows the player place X or O in the board. The 'side' means whether X or O\ndef player_place(side):\n check_if_full()\n while True:\n try:\n local = int(input('Choose somewhere to place it (1-9): ')) - 1\n if local not in range(0, 9):\n print('Invalid number. ')\n else:\n if board[local] != ' ':\n print('This place is already occupied. \\n')\n else:\n board[local] = side\n print_board()\n time.sleep(0.5)\n if did_win(side):\n print("You won!")\n exit()\n break\n except ValueError:\n print('Enter a number! ')\n\n\ndef ai_place(side):\n check_if_full()\n local = random.randint(0, len(board) - 1)\n while board[local] != ' ':\n local = random.randint(0, len(board) - 1)\n board[local] = side\n time.sleep(1)\n print_board()\n time.sleep(0.5)\n\n if did_win(side):\n print("Computer won! Game over")\n exit()\n\n\ndef did_win(side):\n # The following is called tuple unpacking. Because each item in\n # winning_combinations is a tuple, we can simply `unpack` it by\n # writing (square1, square2, square3), where each variable\n # represents the value in the tuple. We can then use these directly\n # without having to go tuple[index]. This makes for digestible code.\n for (square1, square2, square3) in winning_combinations:\n row = [board[square1], board[square2], board[square3]]\n # all checks whether all items in an iterable are the same. The argument\n # given is a list comprehension (which just returns a list). Thus we are\n # checking if every item in the row is equal to the current player's side.\n if all(item == side for item in row):\n return True\n return False\n\n\ndef check_if_full():\n if ' ' not in board:\n print('GAME OVER')\n exit()\n\n\ndef play():\n player, computer = assign_sides()\n user_goes_first = starts_first()\n while True:\n if user_goes_first is True:\n player_place(player), ai_place(computer)\n else:\n ai_place(computer), player_place(player)\n\n\n# Driver code\nif __name__ == '__main__':\n play()\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T22:54:23.123",
"Id": "486384",
"Score": "0",
"body": "thank you for fixing my code, now it looks much more professional. I hadn't understood some parts of the it, but thankfully you put some comments on it, which helped a lot the understanding."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T23:06:20.680",
"Id": "486386",
"Score": "0",
"body": "About the `print_board()` func. I'd say it looks a bit confusing for me, because it uses many functions such as `append()`, `join()` and `format()`. But as I become better at coding I should use more of them to make it smaller rather than using only one, like `print()`, and repeating it many times, right?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T16:32:56.463",
"Id": "248199",
"ParentId": "248047",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248199",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:38:39.053",
"Id": "248047",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Tic Tac Toe implemented in Python"
}
|
248047
|
<p>I have coded more in Python but I am learning Ruby now. So I am trying to write a solution to create a <code>family_tree</code> and add and get relationships. The code below is of the file that contains the main function which is called from the command line. The below code works and solves the problem but I have written methods without classes. In python it is acceptable. Is is acceptable in ruby? Even though the code works is this how it is written in Ruby? Or does this need refactoring? If yes then please tell how?</p>
<p>#main_file.rb</p>
<pre><code>require_relative 'family'
require_relative 'family_tree'
include FamilyTree
require_relative 'constants'
require_relative 'errors'
def is_valid_input(command)
#User input Validation
commands = command.split(' ')
return false unless (commands && INPUT_FUNCTION_MAPPER.key?(commands[0]))
return false if (commands[0] == "ADD_CHILD" && commands.length != 4)
return true
end
def create_family_tree(family_tree)
#Initializing the family
family_name = family_tree[:name]
members = family_tree[:members]
family = Family.new(family_name)
members.each do |name, gender, mother_name|
family.add_member(name, gender, mother_name)
end
family
end
def execute_command(command, family)
result = nil
unless is_valid_input(command)
raise InvalidParametersError, "Command is not valid"
end
command = command.split(" ")
if command[0] == "ADD_CHILD"
mother, name, gender = command[1..]
result = family.add_member(name, gender, mother)
end
result
end
def main_method
if ARGV.length != 1
raise InvalidParametersError, "Please provide an input file"
end
input_file = ARGV[0]
unless File.file?(input_file)
raise InvalidParametersError, "Input file does not exist"
end
family = create_family_tree(FAMILYTREE)
File.readlines(input_file).each do |line|
line = line.strip
puts execute_command(line, family)
end
end
main_method()
</code></pre>
<p>This is executed as below:</p>
<pre><code>ruby main_file.rb input.txt
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-01T08:27:47.620",
"Id": "504048",
"Score": "0",
"body": "A small thing caught my eye: the last three lines of the body of `is_valid_input?` would normally be written `commands && INPUT_FUNCTION_MAPPER.key?(commands[0])) && (commands[0] != \"ADD_CHILD\" || commands.length == 4)` (or the logical equivalent)."
}
] |
[
{
"body": "<p>This "global function" style works for small scripts but isn't reusable.</p>\n<p>A more practical problem with it is if you want to have state that is shared between functions, you don't have anywhere to store it (well, you could use global variables (<code>$var</code>), but that's prone to conflicts).</p>\n<p>For a more encapsulated design, create a class that does the work and move the methods into the class. See for example <a href=\"https://github.com/mongodb/mongo-ruby-driver/blob/master/.evergreen/tools.rb\" rel=\"nofollow noreferrer\">definition</a> and <a href=\"https://github.com/mongodb/mongo-ruby-driver/blob/master/.evergreen/get-mongodb-download-url\" rel=\"nofollow noreferrer\">usage</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T20:02:31.960",
"Id": "248051",
"ParentId": "248048",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T17:44:13.270",
"Id": "248048",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Should methods be inside classes? in Ruby"
}
|
248048
|
<p>A similar question was asked <a href="https://codereview.stackexchange.com/questions/161050/opengl-4-5-core-buffer-wrapper">here</a>, and I'm trying to do the same thing. But</p>
<ol>
<li>I'm trying a different approach by deriving from <code>std::array</code>, and</li>
<li>This is a very focused question about constructors only.</li>
</ol>
<p>Here is my <code>gl_wrap.h</code>:</p>
<pre><code>// header guards snipped
#include <array>
#include <algorithm>
#include <cstring>
#include <GL/gl.h>
namespace gl_wrap {
// aliases for style consistency and to mark as parts of gl_wrap
using gl_name = GLuint;
using gl_enum = GLenum;
template<size_t N>
class buffer_objects : public std::array<gl_name, N> {
public:
buffer_objects() noexcept;
~buffer_objects();
buffer_objects(const buffer_objects&) = delete;
buffer_objects operator=(const buffer_objects&) = delete;
buffer_objects(buffer_objects&& from) noexcept;
buffer_objects& operator=(buffer_objects&& from) noexcept;
};
template<size_t N>
buffer_objects<N>::buffer_objects() noexcept
{
glGenBuffers(N, this->data());
}
template<size_t N>
buffer_objects<N>::~buffer_objects()
{
glDeleteBuffers(N, this->data());
}
template<size_t N>
buffer_objects<N>::buffer_objects(buffer_objects<N>&& from) noexcept
: std::array<gl_name, N>(std::move(from))
{
memset(from.data(), 0, N * sizeof(gl_name));
}
template<size_t N>
buffer_objects<N>& buffer_objects<N>::operator=(buffer_objects<N>&& from)
noexcept
{
std::array<gl_name, N>::operator=(std::move(from));
memset(from.data(), 0, N * sizeof(gl_name));
return *this;
}
}
// namespace gl_wrap
</code></pre>
<p>Some specific questions I have about this code/approach are, if applicable,</p>
<ol>
<li>Error handling design decision: should the constructors throw, or should I leave error checking, if desired, to the caller?</li>
<li>Design decision: is it a good idea to use templates here? Will this lead to problematic code bloat if I'm using a lot of different-sized <code>buffer_objects</code>, or is it efficient? Can I evaluate this through profiling?</li>
<li>Are the <code>memcpy</code>s worth it to put the rvalues in a valid non-owning state, or can I treat the rvalues as non-owning leftovers?</li>
<li>Am I properly using the base class's move constructor?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T20:30:29.570",
"Id": "485756",
"Score": "3",
"body": "Note that c++ standard library classes usually aren't mean for inheritance. Better use a `std::array` class member variable instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T21:29:33.767",
"Id": "485757",
"Score": "2",
"body": "Looks like your move semantics are doing as much work as a copy."
}
] |
[
{
"body": "<blockquote>\n<p>Some specific questions I have about this code/approach are, if applicable,</p>\n</blockquote>\n<p>OK.</p>\n<blockquote>\n<p>Error handling design decision: should the constructors throw, or should I leave error checking, if desired, to the caller?</p>\n</blockquote>\n<p>Either the object is correctly initialized and ready to use or it should throw. Two stage initialization (construct then check) is a bad idea as it leaves it open to the user to do the correct thing. You should make sure your object can not be abused not relie on the user to not abuse you.</p>\n<blockquote>\n<p>Design decision: is it a good idea to use templates here?</p>\n</blockquote>\n<p>If you are going to use <code>std::array</code> you don't really have a choice.</p>\n<blockquote>\n<p>Will this lead to problematic code bloat if I'm using a lot of different-sized buffer_objects, or is it efficient? Can I evaluate this through profiling?</p>\n</blockquote>\n<p>Potentially this will lead to methods be compiled for different types. But this is compiler dependent and some modern compiler can optimize this out. But what are you comparing it too?</p>\n<blockquote>\n<p>Are the memcpys worth it to put the rvalues in a valid non-owning state, or can I treat the rvalues as non-owning leftovers?</p>\n</blockquote>\n<p>I think you need to null out the <code>src</code> values. Otherwise the destructor is going to release the names. Alternatively you can store more state about if the object is valid and make the call to <code>glDeleteBuffers()</code> conditional on the object being in a valid state.</p>\n<p>But I also think there is a bug here. You have just copied over the values. But you did not release the values on the <code>dst</code> side before the copy so you have lost the names stored there.</p>\n<p>Remember that a std::array does not have its own move (as the data is local to the object not dynamically allocated). It moves the underlying objects between containers.</p>\n<blockquote>\n<p>Am I properly using the base class's move constructor?</p>\n</blockquote>\n<p>Yes it seems ligit.</p>\n<h2>Suggestions.</h2>\n<p>I would make the <code>std::array</code> a member rather inherit from it.</p>\n<h2>I would do:</h2>\n<pre><code>#ifndef THORSANVIL_GL_WRAPPER_H\n#define THORSANVIL_GL_WRAPPER_H\n\n#include <GL/gl.h>\n#include <array>\n#include <algorithm>\n#include <cstring>\n\nnamespace ThorsAnvil::GL {\n\ntemplate<size_t N>\nclass BufferObjects\n{\n std::array<GLuint, N> buffer;\n bool valid;\n public:\n BufferObjects() noexcept;\n ~BufferObjects();\n\n // Note: These are non copyable objects.\n // Deleting the copy operations.\n BufferObjects(BufferObjects const&) = delete;\n BufferObjects operator=(BufferObjects const&) = delete;\n\n // Note: The move is as expensive as a copy operation.\n // But we are doing a logical move as you \n // can not have two objects with the same resource.\n BufferObjects(BufferObjects&& from) noexcept;\n BufferObjects& operator=(BufferObjects&& from) noexcept;\n\n // Reset an invalid object.\n // Note: If object is valid no action.\n void reset();\n\n};\n\ntemplate<size_t N>\nBufferObjects<N>::BufferObjects() noexcept\n : valid(false)\n{\n reset();\n}\n\ntemplate<size_t N>\nBufferObjects<N>::~BufferObjects()\n{\n if (valid) {\n glDeleteBuffers(N, buffer.data());\n }\n}\n\ntemplate<size_t N>\nBufferObjects<N>::BufferObjects(BufferObjects<N>&& from) noexcept\n{\n // Move the resources from the other object.\n std::move(std::begin(from.buffer), std::end(from.buffer), std::begin(buffer));\n\n // Maintain the correct valid states\n // The rhs is no longer in a valid state and has no resources.\n valid = from.valid;\n from.valid = false;\n}\n\ntemplate<size_t N>\nBufferObjects<N>& BufferObjects<N>::operator=(BufferObjects<N>&& from)\n noexcept\n{\n // The standard copy and swap not efficient.\n // So we should do a test for self assignment\n if (this != &from)\n {\n // Destroy then re-create this object.\n // Call destructor and then placement new to use\n // the move copy constructor code to set this value.\n ~BufferObjects();\n new (this) BufferObjects(std::move(from));\n }\n return *this;\n}\n\ntemplate<size_t N>\nvoid BufferObjects::reset()\n{\n if (!valid) {\n glGenBuffers(N, buffer.data());\n valid = true;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T21:43:21.503",
"Id": "248060",
"ParentId": "248054",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "248060",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T20:20:27.423",
"Id": "248054",
"Score": "4",
"Tags": [
"c++",
"constructor",
"wrapper",
"opengl"
],
"Title": "C++ wrapper class for array of OpenGL buffer objects -- just the constructors"
}
|
248054
|
<p>I have a form on a page to add a Post (parent), before submitting the form, a user should be able to add 1 or more Sections (children) to the Post.</p>
<p>The form:</p>
<pre><code> <form asp-action="AddSection">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-controller="Post" asp-action="AddPost" type="submit" class="btn btn-primary" value="Add Post" />
</div>
<div class="form-group">
<label asp-for="SectionTitle" class="control-label"></label>
<input asp-for="SectionTitle" class="form-control" />
<span asp-validation-for="SectionTitle" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="SectionDescription" class="control-label"></label>
<input asp-for="SectionDescription" class="form-control" />
<span asp-validation-for="SectionDescription" class="text-danger"></span>
</div>
<div class="form-group">
<button id="add-section-button" type="button" class="btn btn-primary">Add Section</button>
</div>
</form>
</code></pre>
<p>AddPostViewModel</p>
<pre><code>public class AddPostViewModel
{
public string Title { get; set; }
public string Description { get; set; }
public string SectionTitle { get; set; }
public string SectionDescription { get; set; }
public static List<Section> Sections { get; set; } = new List<Section>();
}
</code></pre>
<p>AddPost (GET)</p>
<pre><code> public IActionResult AddPost()
{
var viewModel = new AddPostViewModel();
return View(viewModel);
}
</code></pre>
<p>AddSection(POST via Ajax)</p>
<pre><code>public IActionResult AddSection(AddPostViewModel viewModel)
{
var section = new Section()
{
Title = viewModel.SectionTitle,
Description = viewModel.SectionDescription
};
AddPostViewModel.Sections.Add(section);
var pendingSection = new PendingSectionViewModel()
{
Title = viewModel.SectionTitle,
Description = viewModel.SectionDescription,
};
return ViewComponent("PendingSections", new { section = pendingSection });
}
</code></pre>
<p>AddPost (POST)</p>
<pre><code> [HttpPost]
public IActionResult AddPost(AddPostViewModel viewModel)
{
var post = new Post()
{
Title = viewModel.Title,
Description = viewModel.Description,
Sections = AddPostViewModel.Sections
};
_db.Add(post);
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
</code></pre>
<p>This code works and writes to database as intended, a parent is written with it's associated children. However the code is messy and I plan to refactor anyway but what would be a better way of approaching this?</p>
<p>Quick note on AddSection too. The reason it returns a ViewComponent is it's used to feedback to the user what sections they have added to their post and will have the ability to edit/delete them later down the line. The added sections are added to the top of the page in a list.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T20:32:49.953",
"Id": "248056",
"Score": "1",
"Tags": [
"c#",
"asp.net",
"entity-framework"
],
"Title": "Adding multiple child entities to a parent entity when creating the parent entity"
}
|
248056
|
<p>I am having a bit of difficulty in designing my Go code.</p>
<p>I'll try to demonstrate things with a very simple example of adding a new user to the database.</p>
<p>My Handler is only doing one thing: Calling a service.
The service is managing all the business logic and then calling the DAO to interact with the database.
The DAO also has only responsibility: Storing in the database.</p>
<p>Also, just for context I am making GraphQL requests to interact with my ElasticSearch database, but the design shouldn't be affected by this too much.</p>
<p>I have read a lot of posts about using structs/interfaces to handle the service layer and DAO layer, but I am unable to implement the same in my usecase.</p>
<p><code>File: handlers/user.go</code></p>
<pre><code>type Resolver struct {
client *elastic.Client
index string
}
func (r *Resolver) CreateUser(ctx context.Context, userID string, name string, token *string) (*model.User, error) {
u, err := CreateUserService(ctx, r.client, r.index, userID, name, token)
if err != nil {
fmt.Println("Could not add User to db")
return nil, err
}
return u, nil
}
</code></pre>
<p><code>File: services/user.go</code></p>
<pre><code>func CreateUserService(ctx context.Context, client *elastic.Client, index string, userID string, name string, token *string) (*model.User, error) {
u := &model.User{
UserID: userID,
Name: name,
Token: token
}
s, err := utils.ParseToString(u)
if err != nil {
return nil, err
}
err := CreateUserDAO(ctx, client, index, s)
if err != nil {
return nil, err
}
return u, nil
}
</code></pre>
<p><code>File: dao/user.go</code></p>
<pre><code>func CreateUserDAO(ctx context.Context, client *elastic.Client, index string, user string) error {
_, err = client.Index().
Index(index).
BodyString(s).
Do(ctx)
if err != nil {
return err
}
return nil
}
</code></pre>
<p>I don't have a background in Java/C# so I'm not well versed with OOP Principles but I did read a lot on MVC based on other answers. My code works for now, but is it bad code?
What are the things I can smooth out?</p>
<p>I don't want to be passing parameters from one function to another. Is there a way to that with receivers on methods?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T22:55:33.833",
"Id": "485767",
"Score": "1",
"body": "Welcome to code review. Asking `How to` questions is generally off-topic on code review because it indicates the code isn't working as expected, it is especially bad in a title. Since the code works it is important to change the title. A better title for this might be `Adding a new user through a service in Go`. The title should be about what the code does, any specific questions should be asked within the body of the question. Please review how to ask a good question in our [help center](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T07:04:51.877",
"Id": "485901",
"Score": "0",
"body": "you should not be using functions everywhere. They do not offer any surface to build interchangeable api. They should be struct and methods. You should not pass around the clients etc. As you will have struct, you will be able to declare fields to attach those instances of clients to their respective service implementations and use them within the new methods. Those services are initialized early in your main and given to the handlers for consumption."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T07:06:36.630",
"Id": "485902",
"Score": "0",
"body": "you dont `utils.ParseToString` but marshal something to a string. that step being tightly related to the underlying store, it should be within the elastic dao service. Consider tomorrow you want to record into rdbms, you need not to marshal that object to a string for storage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T08:32:00.180",
"Id": "485908",
"Score": "0",
"body": "@mh-cbon How can I write these structs and use them while passing? Could you write a small snippet to demonstrate this? I am having trouble understanding how to do this, hence my very last statement in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T08:41:17.553",
"Id": "485909",
"Score": "0",
"body": "show your main please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T10:28:37.617",
"Id": "485919",
"Score": "0",
"body": "@mh-cbon the handlers are being hit by graphql, so there's no entrypoint as such. these function definitions are being automatically generated by gqlgen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:44:53.973",
"Id": "485948",
"Score": "0",
"body": "@mh-cbon I would really be glad if you provide some direction. Been stuck at this for 2 days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:16:11.943",
"Id": "485954",
"Score": "0",
"body": "i did. but it seems hopelessness."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T20:52:33.420",
"Id": "248058",
"Score": "2",
"Tags": [
"beginner",
"design-patterns",
"go"
],
"Title": "Structuring Service and DAO Layers in Go"
}
|
248058
|
<p>I'm working on WPF photo broswer app as a personal project. I realise my current strategy for thumbnail handling is poor as I read in the full image each time -- this shows when browsing a folder with more than a few images. If anybody can suggest changes that might improve this aspect of the code, or anything else, that would be very useful.</p>
<p>A slimmed down version of the code is below. This takes a folder and displays thumbnails and names of the images within it. (The full app also has buttons to perform various operations on the images.)</p>
<p><strong>MainWindow.xaml.cs</strong></p>
<pre><code>using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows;
namespace PhotoBrowser
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
}
class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private string _folder;
public string Folder
{
get => _folder;
set
{
_folder = value;
if (Directory.Exists(_folder))
{
var filesInFolder = Directory.EnumerateFiles(_folder);
var files_ = new ObservableCollection<FileItem>();
foreach (string file in filesInFolder)
{
files_.Add(new FileItem(file, false));
}
Files = files_;
}
else
{
Files = new ObservableCollection<FileItem>();
}
OnPropertyChanged();
}
}
private ObservableCollection<FileItem> _files;
public ObservableCollection<FileItem> Files
{
get => _files;
set
{
_files = value;
OnPropertyChanged();
}
}
public MainWindowViewModel() { }
}
}
</code></pre>
<p><strong>MainWindow.xaml</strong></p>
<pre><code><Window x:Class="PhotoBrowser.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:PhotoBrowser"
mc:Ignorable="d"
Title="Photo Browser" Height="800" Width="800" MinHeight="300" MinWidth="400">
<Grid HorizontalAlignment="Stretch" Height="Auto" Margin="10,10,10,10" VerticalAlignment="Stretch" Width="Auto" ShowGridLines="False">
<Grid.RowDefinitions>
<RowDefinition Height="35"/>
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="35"/>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="Folder"
Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBox x:Name="Folder"
Text="{Binding Folder, UpdateSourceTrigger=PropertyChanged}"
Grid.Column="1"
HorizontalAlignment="Stretch" Height="25" TextWrapping="NoWrap" Margin="5,5,5,5"
VerticalAlignment="Center"/>
<ListBox x:Name="FilesInCurrentFolder"
Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Stretch"
BorderBrush="Black" Height="Auto" Width="772" SelectionMode="Extended"
ItemsSource="{Binding Files, UpdateSourceTrigger=PropertyChanged}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Thumbnail}" Width="100" Height="100"/>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected, UpdateSourceTrigger=PropertyChanged}" />
</Style>
</ListBox.Resources>
</ListBox>
</Grid>
</Window>
</code></pre>
<p><strong>FileItem.cs</strong></p>
<pre><code>using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Media.Imaging;
namespace PhotoBrowser
{
public class FileItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
private string _fileName;
public string FileName
{
get => _fileName;
set
{
_fileName = value;
OnPropertyChanged();
OnPropertyChanged("Name");
}
}
private string _name;
public string Name
{
get => Path.GetFileName(_fileName);
set
{
_name = value;
_fileName = Path.Combine(Path.GetDirectoryName(_fileName), value);
OnPropertyChanged();
OnPropertyChanged("FileName");
}
}
private bool _isSelected;
public bool IsSelected
{
get => _isSelected;
set
{
_isSelected = value;
OnPropertyChanged();
}
}
private BitmapSource _thumbnail;
public BitmapSource Thumbnail
{
get => _thumbnail;
set
{
_thumbnail = value;
OnPropertyChanged();
}
}
public FileItem(string fileName)
{
this.FileName = fileName;
GetThumbnail();
}
public FileItem(string fileName, bool isSelected) : this(fileName)
{
this.IsSelected = isSelected;
}
public void GetThumbnail()
{
Image image = new Bitmap(FileName);
image = image.GetThumbnailImage(100, 100, () => false, IntPtr.Zero);
Thumbnail = new BitmapImage(new Uri(FileName));
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T12:09:04.447",
"Id": "486133",
"Score": "1",
"body": "There's a shell interface you can use to get thumbnail images from the windows shell. IShellItemImageFactory.GetImage"
}
] |
[
{
"body": "<p>I think some of your property setters are doing too much. For example in <code>MainWindow</code>, the <code>Folder</code> property setter doesn't just set the folder name but it also takes time to enumerate and collect all files within that folder. This goes against the <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> and perhaps the <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">Principle of Least Astonishment</a>. I have used such applications like that and get frustrated that when all I wanted to do was navigate to a folder but each click seems to force reads from a folder. In short, setting a folder should only set a folder, and enumerating the files in that folder should be a separate action.</p>\n<p>Performance could benefit from implementing some async calls and keep somethings streaming. You stream with <code>EnumerateFiles</code> but you add them to a list. This can take a performance hit. I would investigate the exact instant you think you need to read files, and delay reading them right up until that instant.</p>\n<p>You should read up on any async methods associated with <code>BitMap</code>. I find <a href=\"https://stackoverflow.com/questions/46709382/async-load-bitmapimage-in-c-sharp\">this post</a> how how to load a bitmap asynchronously with C#. And you might consider using a background Task to enumerate files or load thumbnails.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:23:51.993",
"Id": "248140",
"ParentId": "248059",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248140",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T21:30:54.337",
"Id": "248059",
"Score": "1",
"Tags": [
"c#",
"performance",
"image",
"wpf"
],
"Title": "Photo browser WPF app - performance improvements"
}
|
248059
|
<p>I'm new in Golang and haven't done concurrency in a bit. I would love to hear your opinion on my Dining problem Go solution. <a href="https://en.wikipedia.org/wiki/Dining_philosophers_problem" rel="nofollow noreferrer">Description here</a>, with a tl;dr below:</p>
<blockquote>
<p>Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed between each pair of adjacent philosophers.</p>
</blockquote>
<blockquote>
<p>Each philosopher must alternately think and eat. However, a philosopher can only eat spaghetti when they have both left and right forks. Each fork can be held by only one philosopher and so a philosopher can use the fork only if it is not being used by another philosopher. After an individual philosopher finishes eating, they need to put down both forks so that the forks become available to others. A philosopher can only take the fork on their right or the one on their left as they become available and they cannot start eating before getting both forks.</p>
</blockquote>
<blockquote>
<p>Eating is not limited by the remaining amounts of spaghetti or stomach space; an infinite supply and an infinite demand are assumed.</p>
</blockquote>
<blockquote>
<p>The problem is how to design a discipline of behavior (a concurrent algorithm) such that no philosopher will starve; i.e., each can forever continue to alternate between eating and thinking, assuming that no philosopher can know when others may want to eat or think.</p>
</blockquote>
<pre><code>package main
import "fmt"
import "sync"
import "time"
const NumPhilosophers = 5
var phi [NumPhilosophers]int
var forks [NumPhilosophers]sync.Mutex
func startPhilosopher(number int, c chan string){
left, right := (number+1)%NumPhilosophers, number
min, max := left,right
if min > max {
min, max = max, min
}
for i := 0; i < 4; i++ {
c <-"Thinking " + time.Now().Round(0).String()
forks[min].Lock()
forks[max].Lock()
c <- "Eating " + time.Now().Round(0).String()
forks[max].Unlock()
forks[min].Unlock()
}
close(c)
}
func main() {
var ch [NumPhilosophers]chan string
for i := 0; i < NumPhilosophers; i++ {
phi[i] = i
ch[i] = make(chan string)
go startPhilosopher(i, ch[i])
}
for a := 0; a < NumPhilosophers; a++ {
fmt.Println(a)
for i := range ch[a] {
fmt.Println(i)
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-17T23:09:15.097",
"Id": "248063",
"Score": "3",
"Tags": [
"go",
"concurrency"
],
"Title": "Dining philosophers problem in Go"
}
|
248063
|
<p>I've been teaching myself Python over the last few weeks, I have an interest in cryptography, codes, etc. so I figured starting a Morse code translator would be a good project. I know my variable names could be different, it's not really encrypting, decrypting, etc. I'm mostly looking for advice on how I can make the code cleaner and where I can be more efficient.</p>
<p>I think my biggest problem is not really knowing how to handle the inputs in a while loop like I usually would. The problem I had was that I couldn't check if the input was 'e' or 'd' so it just got really wonky.</p>
<p>Areas I know I could improve:</p>
<ul>
<li>Add input loop</li>
<li>The if, elif, else for the action</li>
<li>Make 'sound' an actual boolean value</li>
<li>Find the actual sound time for the dit and dah but that's not really a code issue</li>
</ul>
<pre><code># Started: 08/17/2020
# Finished: 08/17/2020
# Takes an input message and outputs the message in morse code
# Keys taken from 'https://en.wikipedia.org/wiki/Morse_code'
from playsound import playsound
import time
# Dictionary that holds each letter and it's corresponding value
dict = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--',
'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.', 's': '...', 't': '-', 'u': '..-', 'v': '...-', 'w': '.--', 'x': '-..-', 'y': '-.--', 'z': '--..',
'1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----',
' ': '/', '.': '.-.-.-', ',': '.-.-', '?': '..--..', "'": '.----.', '!': '-.-.--', '/': '-..-.', '(': '-.--.', ')': '-.--.-',
':': '---...', ';': '-.-.-.', '=': '-...-', '+': '.-.-.', '-': '-....-', '_': '..--.-', '"': '.-..-.', '$': '...-..-', '@': '.--.-.'}
outputMessage = "" # Holds our output message
# Sounds
sound = 'False'
dit = 'dit.wav'
dah = 'dah.wav'
def Encrypt(message):
output = ''
for char in message:
if char in dict:
output = output + dict[char]
output = output + ' '
return output
def Get_Key(val):
for key, value in dict.items():
if val == value:
return key
def Decrypt(message):
output = ''
letters = message.split(' ')
for letter in letters:
temp = Get_Key(letter)
output = output + temp
return output
def Get_Inputs():
# Get Inputs
inputString = input('Enter a message to start.\n')
action = input('(E)ncrypt or (D)ecrypt?\n')
# Format Inputs
message = inputString.lower().strip()
action = action.lower().strip()
return message, action
def Play_Sound(message):
for char in message:
if char == '.':
playsound(dit)
elif char == '-':
playsound(dah)
elif char == ' ':
time.sleep(0.15)
elif char == '/':
time.sleep(0.30)
message, action = Get_Inputs()
if action == 'e' or action == 'encrypt':
outputMessage = Encrypt(message)
elif action == 'd' or action == 'decrypt':
outputMessage = Decrypt(message)
else:
print('Error!')
print(outputMessage)
print('')
sound = input('Play sound? (T)rue / (F)alse\n')
if sound.lower().strip() == 't' or sound.lower().strip() == 'true':
Play_Sound(outputMessage)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T07:31:17.083",
"Id": "485785",
"Score": "0",
"body": "Welcome to Code Review, I added `morse-code` tag to your question."
}
] |
[
{
"body": "<h1>General Style</h1>\n<p>Your translation <code>dict</code> uses a keyword and lower case letters.\nConsider writing constants with upper-case letters and giving them expressive names like <code>MORSE_CODES = {...}</code>.</p>\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a>, functions should be named using <code>snake_case</code>. <code>CamelCase</code> is reserved for classes:\n<code>outputMessage</code> → <code>output_message</code>, <code>def Encrypt(...)</code> → <code>def encrypt(...)</code>, etc.</p>\n<h1>Performance</h1>\n<p>Using the <code>Get_Key</code> function is not very performant, since it performs a linear search of the dict. Just reverse the translation dict once and then use it:</p>\n<pre><code>MORSE_ENCODING = {\n 'a': '.-',\n 'b': '-...',\n ...\n}\nMORSE_DECODING = {value: key for key, value in MORSE_ENCODING.items()}\n\n...\n\n temp = MORSE_DECODING[letter]\n</code></pre>\n<h1>Handling errors</h1>\n<p>Currently the <code>Encrypt</code> function silently skips all non-translatable characters. Consider Throwing a <code>ValueError()</code> instead to indicate, that invalid input was provided:</p>\n<pre><code>def encode(message):\n """Encodes a string into morse code."""\n\n code = ''\n\n for index, char in enumerate(message):\n try:\n code += MORSE_ENCODING[char.lower()]\n except KeyError:\n raise ValueError(f'Char "{char}" at {index} cannot be encoded.')\n\n code += ' '\n\n return code[:-1] # Remove trailing space.\n\n\ndef decode(morse_code):\n """Decodes morse code."""\n\n message = ''\n\n for index, sequence in enumerate(morse_code.split()):\n try:\n message += MORSE_DECODING[sequence]\n except KeyError:\n raise ValueError(f'Cannot decode code "{sequence}" at {index}.')\n\n return message\n</code></pre>\n<h1>Correctness</h1>\n<p>Your <code>Encrypt</code> function currently always returns a trailing space. You can avoid that by returning <code>output[:-1]</code>.</p>\n<h1>Terminology</h1>\n<p>Converting from morse code to text back and forth is not really an encryption in its sense. You might want to rephrase <code>{en,de}crypt</code> with <code>{en,de}code</code>.</p>\n<h1>Globals</h1>\n<p>Using global variables like <code>outputMessage</code> can have nasty side-effects when the program is used as a library. All the code below the <code>def Play_Sound</code> function should go into a <code>def main()</code> function that you can invoke via</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>At the bottom of the unit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:25:58.057",
"Id": "248087",
"ParentId": "248068",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T02:43:13.627",
"Id": "248068",
"Score": "6",
"Tags": [
"python",
"performance",
"morse-code"
],
"Title": "Python Morse Code Translator"
}
|
248068
|
<p>I would like some feedback on my code, I'm new to coding with C# but I do have some knowledge on Lua and Python. Is there anything that I need to change/clean up to make it more simplified?</p>
<pre><code>using System;
using System.Linq;
class MainClass {
public static void Main () {
int[] cards = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10};
Console.WriteLine("Welcome to Blackjack. Here are your draws.");
Random drawCard = new Random();
int draw1 = drawCard.Next(cards.Min(), cards.Max());
int draw2 = drawCard.Next(cards.Min(), cards.Max());
Console.WriteLine("You recieved a " + draw1 + " card!");
Console.WriteLine("You recieved a " + draw2 + " card!");
int sum1 = draw1 + draw2;
if (sum1 == 21) //Blackjack Ending
{
Console.WriteLine("Congratulations! You got " + sum1 + "!");
}
else if (sum1 >= 11) //Choice of 3rd draw
{
Console.WriteLine("Is " + sum1 + " enough?");
bool cont1 = false;
drawChoice(cont1); //Call the draw choice function
if (cont1 == true)
{
int draw3 = drawCard.Next(cards.Min(), cards.Max());
Console.WriteLine("You drawed a " + draw3 + " card!");
int sum2 = draw3 + sum1;
Console.WriteLine("You have a total of " + sum2 + ".");
if (sum2 > 21) Console.WriteLine("Game Over!");
}
else //NPC's turn starts
{
}
}
else //Player has less than 11 cards, auto draw
{
Console.WriteLine("You have a total of " + sum1 + ".");
Console.WriteLine("You will be forced to draw another card.");
int draw3 = drawCard.Next(cards.Min(), cards.Max());
Console.WriteLine("You drawed a " + draw3 + " card!");
int sum2 = draw3 + sum1;
Console.WriteLine("You have a total of " + sum2 + ".");
}
}
static void drawChoice(bool contChoice) //Function for player to choose whether to draw
{
Console.WriteLine("Would you like to draw another card? Y/N");
string choice1 = Console.ReadLine();
if (choice1 == "Y" || choice1 == "y")
{
contChoice = true;
Console.WriteLine(contChoice);
}
else if (choice1 == "N" || choice1 == "n")
{
contChoice = false;
Console.WriteLine(contChoice);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T06:52:05.020",
"Id": "485780",
"Score": "0",
"body": "Sure thing, I'll edit it now. There are some code blocks that are unfinished but that's where I'll stop for now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T07:55:39.867",
"Id": "485788",
"Score": "5",
"body": "Welcome to Code Review! Don't touch the code now answers are coming in, but be careful with removing lines of code. A lot of questions are closed because they are lacking the much-needed context of the program, since code is unnecessarily hard to review without it and the answers may miss the mark for the actual program if the posted code is a modified version. Just something to keep in mind when posting your next question. For the full guide, please see our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) if you're interested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:48:11.767",
"Id": "485815",
"Score": "2",
"body": "Please do not modify the code after the question has been answered. See our [help center](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T14:01:56.450",
"Id": "485949",
"Score": "1",
"body": "You spelled \"received\" wrong"
}
] |
[
{
"body": "<p>Just a few notes so you can improve your code:</p>\n<blockquote>\n<pre><code>int sum1 = draw1 + draw2;\n\nif (sum1 == 21) //Blackjack Ending\n{\n Console.WriteLine("Congratulations! You got " + sum1 + "!");\n}\n</code></pre>\n</blockquote>\n<p>This won't ever be true, because</p>\n<ul>\n<li>you have nowhere in the cards an ace meaning having a possible value of eleven.</li>\n<li>the <code>maxValue</code> in <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.random.next?view=netcore-3.1#System_Random_Next_System_Int32_System_Int32_\" rel=\"noreferrer\"><code>Random.Next(int minValue, int maxValue)</code></a> is the exclusive upper bound of the random number returned.</li>\n</ul>\n<p>In <code>void drawChoice(bool contChoice)</code> the method argument <code>contChoice</code> is a value type. You can't modify it like you think. After leaving the method regardless wether the user typed y or n the value of <code>cont1</code> is still <code>false</code>. You should change the method signature to have no arguments but to return a <code>bool</code>.</p>\n<blockquote>\n<pre><code>if (cont1 == true) \n</code></pre>\n</blockquote>\n<p>because <code>cont1</code> already is a bool you won't need to <strong>compare</strong> it with a bool. You can simply use it as condition like <code>if (cont1)</code> and if you would need to check wether a bool variable is <code>false</code> you would use <code>if (!cont1)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:03:39.973",
"Id": "485808",
"Score": "0",
"body": "Thank you for your answer!\n1. I am aware of the `if` statement not being true, I plan to modify the array variable to define what the Ace card would be in integer values.\n2. What I originally planned was to have `Main` send the argument of `cont1` to `drawChoice` and the variable would be updated and has the data of what the user entered. How shall I execute that, and how can I leave `cont1` to be undefined? I will be adding another few more lines of code that would respond to the user if they did not enter Y nor N."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:10:41.903",
"Id": "485809",
"Score": "2",
"body": "You wouldn't need `cont1` anymore. You would just chang your `if` condition like so `if (drawChoice())`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T07:33:06.123",
"Id": "248075",
"ParentId": "248069",
"Score": "9"
}
},
{
"body": "<p>I've actually made a similar project myself, it's really good fun!</p>\n<h2>1. Keeping track of scores</h2>\n<p>First thing I noticed is that you keep track of the sum of the values for the player and presumably also for the dealer, but the score of a hand can actually change dramatically while playing.</p>\n<h3>1.1. Soft totals in blackjack</h3>\n<p>Blackjack has this concept called <em>soft</em> totals, which means the total sum can have a different value depending on if there's an ace or not. For example, if a player has an ace (1) and a 7, that actually counts as 18 (11 + 7). But if that same player draws another 7, their total will be 15 (1 + 7 + 7). The value of the ace changes as you draw more cards, so you'll have an easier time keeping scores if you somehow keep the cards separated from each other. This can be done using collections.</p>\n<h3>1.2. Collections</h3>\n<p>Collections are things like arrays (which you've already used), lists and dictionaries. A list of integers is a good candidate to represent a player's (or the dealer's) current collection of cards, because they can change sizes without complaining. Moreover, lists have built-in functions for getting sum of all the numbers inside them, the minimum and the maximum values of the list and plenty more. You can use those built-in functions to your advantage, as well as the fact that you always know the numbers inside the list to determine if someone's total is <em>soft</em> or not.</p>\n<h2>2. Game loop</h2>\n<p>The game of blackjack is played with a finite number of cards in real life, but of course in code you don't have to worry about that. If an (un)lucky player keeps drawing aces, they'll eventually still hit 21 and end the round. However, since you can't predict when a player (or the dealer) is going to lose, you can use something called a game loop. The game loop for blackjack starts executing all the game logic once a player or the dealer confirms that they want to draw a card, and once it's done executing, it'll ask to repeat if necessary.</p>\n<h3>2.1. Conditions for choosing another card</h3>\n<p>You'll notice that the player has a lot of freedom in blackjack, they can keep drawing cards until they get 21 or go over, at which point the round ends for them. The dealer, however, doesn't have that freedom. You can find more information on that online.</p>\n<p>Either way, if you think about it, both the player and the dealer at some point make the decision to either draw or not to draw another card. You do a check for <code>"Y"</code> or <code>"N"</code> when given an input, which makes sense.</p>\n<h3>2.2. Translating text input to <code>true</code> or <code>false</code></h3>\n<p>Your <code>DrawChoice</code> method alters a <code>bool</code> depending on the player's input, but you could also refactor that method so that it receives a <code>string</code> and returns a <code>bool</code>. That way, you can directly translate the user's input to <code>true</code> (yes, give me another card) or <code>false</code> (no, I don't want another card). It could look something like this:</p>\n<pre><code>// One option\npublic static bool DrawChoice(string input)\n{\n if (input == "Y" || input == "y") // You could also use input.ToLower() == "y"\n {\n return true;\n }\n else // If it's not "Y" or "y", it's gonna be "N" or "n"\n {\n return false;\n }\n\n// else if (input == "N" || input == "n")\n// {\n// return false;\n// }\n}\n\n// Alternative one-liner\npublic static bool DrawChoice2(string input) => input.ToLower() == "y";\n</code></pre>\n<p>Going back to the idea of a game loop, you now have a condition that dictates whether the game loop continues or not. One possible implementation would be this:</p>\n<pre><code>string choice = Console.ReadLine();\nwhile (DrawChoice(choice)) // No need to write "== true" or "== false"\n{\n // Stuff that happens if a player or the dealer draws another card\n choice = Console.ReadLine() // Ask again once the game logic has executed\n}\n// Stuff that happens when the loop ends\n</code></pre>\n<h3>2.3. Drawing cards</h3>\n<p>Blackjack is a card game, therefore you'll be drawing cards a lot, be it for a player or for the dealer. If something happens often in the game, it's generally a good idea to make it into a method so you don't have to write the same logic in different places.</p>\n<p>Your current implementation draws a random value between the minimum and the maximum of your array of cards. From the documentation, we learn the following:</p>\n<blockquote>\n<p><code>Next(Int32 minValue, Int32 maxValue)</code></p>\n<p>A 32-bit signed integer greater than or equal to <code>minValue</code> and less than <code>maxValue</code>; that is, the range of return values includes <code>minValue</code> <strong>but not</strong> <code>maxValue</code>. If <code>minValue</code>equals <code>maxValue</code>, <code>minValue</code>is returned.</p>\n</blockquote>\n<p>So when you write <code>Next(1, 10)</code> (from min and max), you will at most get a 9. Another issue is that even if you fix the implementation to <code>Next(1, 11)</code>, you will have equal probabilities to get any value from 1 through 10. But since there's multiple cards in the deck that have the value of 10, they should show up more often than non-10 cards.</p>\n<p>Fortunately, your array already has the correct distribution of cards, so instead you could generate a valid random <em>position</em> to get the corresponding value from your array.</p>\n<p>At the end of the day, what you'll end up with will look something like this:</p>\n<pre><code>public static int DrawCard()\n{\n int[] cards = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };\n int card;\n // Implement random draw here\n return card;\n}\n</code></pre>\n<p>And then you could even do something like this to repeatedly draw cards:</p>\n<pre><code>// You could also use a list, which is more flexible\npublic static int[] DrawCard(int count)\n{\n int[] drawn = new int[count];\n for (int i = 0; i < count; i++)\n {\n drawn[i] = DrawCard();\n }\n return drawn;\n}\n</code></pre>\n<p>Hope this helps! Good luck and have fun!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:33:26.043",
"Id": "485836",
"Score": "0",
"body": "This is really high quality, and really detailed. I'll go through it slowly and take my time as I read through it. But one question. For section 2.2, instead of using an `else if` statement and subbing it with `else`, wouldn't the user be able to enter anything else other than specifically N? (not that it is necessary, just clarifying.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:36:17.337",
"Id": "485837",
"Score": "1",
"body": "That's certainly a possibility, but even if you allow different inputs, you would only care about the ones that return `true` to keep the game loop going, right? So in that case I'd suggest you keep adding `||`'s in the branch that returns `true` rather than adding them as `else if`s. You could also invert that logic and define which inputs should specifically return `false`, and return `true` for any other input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:55:01.427",
"Id": "485840",
"Score": "1",
"body": "Oh my bad, I had misinterpreted your question. They can still input anything they'd like, because the if/else statement checks what they *have* typed, not what they *might* type. The method will only return true if the user typed `\"Y\"` or `\"y\"`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:18:53.930",
"Id": "248092",
"ParentId": "248069",
"Score": "6"
}
},
{
"body": "<p>I'm not sure how helpful I can be here, but IMHO you need to have a full fledged code review with someone talking you through the code. There's a bunch "wrong" here, but having said that I'm wondering what your aim is with C# - are you just scripting something quick out to learn the syntax, or are you wanting to better understand how to architect things in C#.</p>\n<p>If someone came to me with this in a professional setting the first thing I'd tell them: "You need to be able to test this". I would then talk about TDD, and really try to point out how this code is structured to do way too much. There's no abstractions, and everything is very procedural. Every class should do 1 thing. People I'm sure will argue with me on this point. Either way, the fact that you only have 1 class is bad.</p>\n<p>Past that, for just general "2 minute quick C# tips". I'd use enumerations for the cards so instead of 10, 10, 10, I'd have 10, Jack, Queen, Ace. Use var instead. <code>if (cont1 == true)</code> is the same as <code>if(cont1)</code>. Use better named variables: Just looking at cont1 I have no idea what that means.</p>\n<p>JansthcirlU also brought up collections. Looking at this code, it doesn't look like you understand them so I would really focus here as well.</p>\n<p>Keep coding :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T19:14:08.263",
"Id": "485856",
"Score": "1",
"body": "Yeah, I mainly brought up points that seemed useful in the long run, since I've run into plenty of roadblocks while doing my own blackjack project. Obviously you can't expect someone to 100% comprehend a language from a StackExchange answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T05:30:40.763",
"Id": "485892",
"Score": "0",
"body": "My aim in C# is to just use my basic knowledge from other coding languages to program a project and to know the syntax of C#. Though I only know the basic stuff like `variables` and `if..else` statements, things like `enumerations` and `collections` is something I've never heard of before so that can be helpful if I would want to use it in another project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T21:16:37.837",
"Id": "486081",
"Score": "0",
"body": "So my advice to you would be to pick one language, and then actually make something complex with it, like a game or application with a complete UI. Enums are in most and collections (or arrays) are used in every programming language there is. Instead of just learning a language become proficient in using it, don't switch around a bunch until you feel like you really understand what's going on.\n\nFor me, it's trivial to switch to other languages because I understand the concepts behind everything, I just make a mental map to use whatever syntax the current language I'm in needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T21:28:08.703",
"Id": "486082",
"Score": "0",
"body": "I'll go one further with explaining the SRP classes that I would start with off the top of my head: CardScoreCalculator (takes in array of cards, returns score array), DeckManager (what cards have been played, and still in the deck), GameManager (keeps array of all players, who's turn is it, what action did they take, who wins), Card (Friendly name, Values), Player (Current cards, their state, available actions, if this is a dealer). I would probalby employ a strategy pattern to Player as well... :P"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T17:27:24.123",
"Id": "248097",
"ParentId": "248069",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248092",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T03:44:13.393",
"Id": "248069",
"Score": "8",
"Tags": [
"c#",
"game",
"playing-cards"
],
"Title": "C# Blackjack prototype"
}
|
248069
|
<p>I have done this code. But I am not sure that I have got the exact answer. I have never solved this kind of problem earlier.
General form of a $2n+1$ degree Hermite polynomial:</p>
<p><span class="math-container">$$p_{2n+1} = \sum_{k=0}^{n} \left(f(x_k)h_k(x) + f'(x_k)\hat{h}_k(x)\right) \tag{1}$$</span></p>
<p><span class="math-container">$$h_k(x) = (1-2(x-x_k)l^\prime_k(x_k))l^2_k(x_k) \tag{2}$$</span></p>
<p>and,</p>
<p><span class="math-container">$$\hat{h}_k(x) = (x-x_k)l^2_k(x_k) \tag{3}$$</span></p>
<p>where the Lagrange basis function being,</p>
<p><span class="math-container">$$l_k(x) = \prod_{j=0, j\neq k}^{n} \frac{x-x_j}{x_k-x_j} \tag{4}$$</span></p>
<p><a href="https://i.stack.imgur.com/q9jUw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q9jUw.png" alt="Hermite Interpolation" /></a></p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from itertools import combinations
from numpy.polynomial import Polynomial
def l(k, x):
n = len(x)
assert (k < len(x))
x_k = x[k]
x_copy = np.delete(x, k)
denominator = np.prod(x_copy - x_k)
coeff = []
for i in range(n):
coeff.append(sum([np.prod(x) for x in combinations(x_copy, i)]) * (-1) ** (i) / denominator)
coeff.reverse()
return Polynomial(coeff)
def h(k, x):
# initialize with none
l_k=None
l_k_sqr=None
l_k_prime = None
coeff = None
p = None
coeff=x[k]
l_k = l(k,x)
l_k_sqr = Polynomial.__pow__(l_k,2)#l_k**2
l_k_prime=Polynomial.deriv(l_k,1)
p=(1-(2*x*l_k_prime)+(2*coeff*l_k_prime))*coeff
return p * l_k_sqr
def h_hat(k, x):
l_k = l(k,x)
l_k_sqr = Polynomial.__pow__(l_k,2)
coeff = None
p = None
coeff=x[k]
# place your code here!!!!!!!!!!!!!!!!!!!!!!!
p=(x-coeff)*coeff
return p * l_k_sqr
def hermit(x, y, y_prime):
assert (len(x) == len(y))
assert (len(y) == len(y_prime))
f = Polynomial([0.0])
for i in range(len(x)):
f += (y[i]*h(i,x))+(y_prime[i]*h_hat(i,x))
# pass statement does nothing
# place your code here!!!!!!!!!!!!!!!!!!!!!!!
return f
pi = np.pi
x = np.array([0.0, pi/2.0, pi, 3.0*pi/2.0])
y = np.array([0.0, 1.0, 0.0, -1.0])
y_prime = np.array([1.0, 0.0, 1.0, 0.0])
n = 1
f3 = hermit(x[:(n+1)], y[:(n+1)], y_prime[:(n+1)])
data = f3.linspace(n=50, domain=[-3, 3])
test_x = np.linspace(-3, 3, 50, endpoint=True)
test_y = np.sin(test_x)
plt.plot(data[0], data[1])
plt.plot(test_x, test_y)
plt.show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T09:16:10.217",
"Id": "485912",
"Score": "0",
"body": "Please give some more information. What do you expect? What does \"exact answer\" mean? ...?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T10:38:51.200",
"Id": "485920",
"Score": "0",
"body": "https://colab.research.google.com/drive/1YEOe5P9udLMGqTicvEGGaLRnSRQS71Cw?usp=sharing"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T07:35:07.430",
"Id": "248076",
"Score": "1",
"Tags": [
"python",
"numpy"
],
"Title": "Hermit Interpolation error check"
}
|
248076
|
<p>I have two table. I want count how many times a value is in other table. So the codice from table "sorgente" is different in table contatore, because I have the suffix 'BRANO-' before the code.</p>
<pre><code>sorgente
| codice | nome |
| 15 | mario |
| 16 | mary |
contatore
| nome_evento | data |
| BRANO-15 | 2020-08-15 |
| BRANO-15 | 2020-08-16 |
| BRANO-16 | 2020-08-14 |
</code></pre>
<p>the query for select is</p>
<pre><code>select
s.codice,
(
select count(*)
from contatore c
where c.nome_evento = concat('BRANO-', s.codice)
) no_matches_in_contatore
from sorgente s
</code></pre>
<p>but the original "sorgente" table has 25000 records, the "contatore" table has at now 60000 records.
when I try to execute the query it takes 600 seconds....
can you help me?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T14:25:21.550",
"Id": "530687",
"Score": "0",
"body": "let me know what indexes are on your tables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-16T04:09:31.600",
"Id": "530688",
"Score": "0",
"body": "Please read the [SQL tag wiki's guidelines](https://codereview.stackexchange.com/tags/sql/info) for requesting SQL reviews: 1) Provide context, 2) Include the schema, 3) If asking about performance, include indexes and the output of EXPLAIN SELECT."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T09:31:37.980",
"Id": "248079",
"Score": "1",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "MYSQL select count two table left join"
}
|
248079
|
<p><strong>Description</strong></p>
<p>A WinForms application has a function to export objects of the following type, in various formats:</p>
<pre><code>class Item
{
public int id { get; set; }
public string description { get; set; }
}
</code></pre>
<p>At the click of a button in a window, a <code>SaveFileDialog</code> is shown, and currently it provides the option to save the data in .txt, .csv or .xlsx format. Since there are sometimes hundreds or thousands of objects, and the UI should not freeze up, a <code>Task</code> is used to run this operation. This implementation works, but could be improved.</p>
<p><strong>Code</strong></p>
<pre><code>public partial class ExportWindow : Form
{
// objects to be exported
List<Item> items;
// event handler for the "Export" button click
private async void exportButton_click(object sender, System.EventArgs e)
{
SaveFileDialog exportDialog = new SaveFileDialog();
exportDialog.Filter = "Text File (*.txt)|*.txt|Comma-separated values file (*.csv)|*.csv|Excel spreadsheet (*.xlsx)|*.xlsx";
exportDialog.CheckPathExists = true;
DialogResult result = exportDialog.ShowDialog();
if (result == DialogResult.OK)
{
var ext = System.IO.Path.GetExtension(saveExportFileDlg.FileName);
try
{
// update status bar
// (it is a custom control)
statusBar.text("Exporting");
// now export it
await Task.Run(() =>
{
switch (ext.ToLower())
{
case ".txt":
saveAsTxt(exportDialog.FileName);
break;
case ".csv":
saveAsCsv(exportDialog.FileName);
break;
case ".xlsx":
saveAsExcel(exportDialog.FileName);
break;
default:
// shouldn't happen
throw new Exception("Specified export format not supported.");
}
});
}
catch (System.IO.IOException ex)
{
statusBar.text("Export failed");
logger.logError("Export failed" + ex.Message + "\n" + ex.StackTrace);
return;
}
}
}
private delegate void updateProgressDelegate(int percentage);
public void updateProgress(int percentage)
{
if (statusBar.InvokeRequired)
{
var d = updateProgressDelegate(updateProgress);
statusBar.Invoke(d, percentage);
}
else
{
_updateProgress(percentage);
}
}
private void saveAsTxt(string filename)
{
IProgress<int> progress = new Progress<int>(updateProgress);
// save the text file, while reporting progress....
}
private void saveAsCsv(string filename)
{
IProgress<int> progress = new Progress<int>(updateProgress);
using (StreamWriter writer = StreamWriter(filename))
{
// write the headers and the data, while reporting progres...
}
}
private void saveAsExcel(string filename)
{
IProgress<int> progress = Progress<int>(updateProgress);
// EPPlus magic to write the data, while reporting progress...
}
}
</code></pre>
<p><strong>Questions</strong></p>
<p>How can this be refactored to make it more extensible? That is, if I wanted to add support for more file types, make it easy and quicker to modify. The switch statement could get very long. Essentially, how to comply with the Open/Closed principle?</p>
|
[] |
[
{
"body": "<p>I would suggest moving the actual export(s) into their own class. We can create an interface for exports. Something along the lines of</p>\n<pre><code>public interface IExport<T>\n{\n Task SaveAsync(string fileName, IEnumerable<T> items, IProgress<int> progress = null);\n string ExportType { get; }\n}\n</code></pre>\n<p>Then each export type can implement this interface.</p>\n<pre><code>public class ExportItemsToText : IExport<Item>\n{\n public Task SaveAsync(string fileName, IEnumerable<Item> items, IProgress<int> progress = null)\n {\n throw new NotImplementedException();\n }\n\n public string ExportType => "txt";\n}\n</code></pre>\n<p>Then in your constructor of ExportWindow</p>\n<pre><code>public ExportWindow(IEnumerable<IExport<Item>> exports)\n{\n // if using DI otherwise could just fill in dictionary here\n ExportStrategy = exports.ToDictionary(x => x.ExportType, x => x);\n}\n</code></pre>\n<p>Instead of a switch statement you can now just look up the key in the dictionary to find what export should be ran and if not found would be the same as your default case.</p>\n<pre><code>IExport<Item> exporter;\nif (ExportStrategy.TryGetValue(ext.ToLower(), out exporter))\n{\n await exporter.SaveAsync(exportDialog.FileName, items, new Progress<int>(updateProgress))\n}\nelse\n{\n throw new Exception("Specified export format not supported.");\n}\n</code></pre>\n<p>Now in the future if adding support for more types you just implement the interface and update your DI container. Or if not using DI then would need to add it to the constructor of your ExportWindow.</p>\n<p><strong>I don't think this is a great idea</strong> but If you really don't want to create a class per export, which I think you should, you could make the dictionary <code>IDictionary<string, Action<string>></code> then just put your methods in there and when adding a new type create the method and update the dictionary.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T13:04:25.807",
"Id": "248089",
"ParentId": "248080",
"Score": "5"
}
},
{
"body": "<p>I just want to share what I have since I've already implemented this (sort of) in one of my previous projects (it was on ASP.NET), but it can be applied in any other environment. The implementation was similar to CharlesNRice suggestion. However, the requirement was to only have options to export system reports (which is used only one report template) to Pdf, Excel, and Word with a negotiation of having more export options in the future. So this is how I did it :</p>\n<p>First the interface :</p>\n<pre><code>public interface IExportTo<T>\n{\n IExportTo<T> Generate();\n\n void Download(string fileName);\n\n void SaveAs(string fileFullPath);\n}\n</code></pre>\n<p>then the container class :</p>\n<pre><code>public class ExportTo : IDisposable\n{\n private readonly IList<T> _source;\n\n public ExportTo(IList<T> source)\n {\n _source = source;\n }\n\n public ExportExcel Excel()\n {\n return new ExportExcel(_source);\n }\n\n public ExportPdf Pdf()\n {\n return new ExportPdf(_source);\n }\n \n public ExportWord Word()\n {\n return new ExportPdf(_source);\n }\n \n\n #region IDisposable\n\n private bool _disposed = false;\n\n public void Dispose()\n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n private void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n Dispose();\n }\n\n _disposed = true;\n }\n }\n\n\n ~ExportTo()\n {\n Dispose(false);\n }\n\n #endregion\n}\n</code></pre>\n<p>I've implemented a class for each export type as we can see in the above class. I'll share one class (I'll simplify it though from the actual class).</p>\n<pre><code>public sealed class ExportPdf : IExportTo<T>, IDisposable\n{\n private readonly IList<T> _source;\n\n private ExportPdf() { }\n\n public ExportPdf(IList<T> source) : this() => _source = source ?? throw new ArgumentNullException(nameof(source));\n\n public IExportTo<T> Generate()\n {\n // some implementation \n return this;\n }\n\n // another overload to generate by Id \n public IExportTo<T> Generate(long reportId)\n {\n // do some work \n return this;\n }\n\n // Download report as file \n public void Download(string fileName)\n {\n // do some work \n }\n\n public void SaveAs(string fileFullPath)\n {\n throw new NotImplementedException("This function has not been implemented yet. Only download is available for now.");\n }\n\n\n #region IDisposable\n\n private bool _disposed = false;\n\n public void Dispose()\n { \n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n\n private void Dispose(bool disposing)\n {\n if (!_disposed)\n {\n if (disposing)\n {\n Dispose();\n }\n\n _disposed = true;\n }\n }\n\n\n ~ExportPdf()\n {\n Dispose(false);\n }\n\n #endregion\n}\n</code></pre>\n<p><code>Download</code> and <code>SaveAs</code> are different (not the same). <code>Download</code> would download the exported file, while <code>SaveAs</code> would save the object instance. But this was implemented like this because the used dependencies.</p>\n<p>Now usage would like this :</p>\n<pre><code>new ExportTo(someList)\n.Pdf()\n.Generate()\n.Download(fileName);\n</code></pre>\n<p>This is how I've implemented in that project, it could be improved, but for business requirements it is enough.</p>\n<p>Whenever you need to add a new type of export, just create a new <code>sealed</code> class, then implement <code>IExportTo<T>, IDisposable</code> on that class. Finally, update the container class with the new type (add a method to open a new instance of this method) and you're good to go.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T23:22:59.203",
"Id": "248215",
"ParentId": "248080",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248089",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T09:37:59.170",
"Id": "248080",
"Score": "3",
"Tags": [
"c#",
".net"
],
"Title": "Exporting objects in various formats while reporting progress"
}
|
248080
|
<p>Basically, I have 20 very similar objects and most importantly I want to do the same thing for all of them.</p>
<p>This is the <code>ImportProcessor</code> class for <code>AutomobileExpense</code> (<code>AutomobileExpenseDataImportProcessor</code>). And in this scenario I would need another 19 <code>ImportProcessor</code> classes for the other similar objects.</p>
<p>I have made common logic with generic methods or not in the base class. The only things I cannot make generic or without some deep reflection logic are:</p>
<ul>
<li>the enums in the constructor</li>
<li>the repository in the constructor</li>
<li>the specific Object properties in if and else statements, method which returns <code>Guid -> this.ProcessDebt()</code> and his second and third arguments <code>xrefDebt.DebtsAutomobileExpense</code> and <code>converted.DebtsAutomobileExpense</code></li>
</ul>
<pre><code>public class AutomobileExpenseDataImportProcessor : BaseDebtDataImportProcessor
{
private GenericRepository<DebtsAutomobileExpense> _repo;
public AutomobileExpenseDataImportProcessor(MyCompanyIUnitOfWork unitOfWork, IAuthenticationUserSession user, SystemDecision systemDecisons, params Expression<Func<XRefClientBusiness, object>>[] include)
: base(unitOfWork, user, systemDecisons, include)
{
this._repo = this._unitOfWork.DebtsAutomobileExpenseRepository;
this._objectType = ObjectType.DebtsAutomobileExpense;
this._importObjType = ImportObjectType.DebtAutomobileExpense;
this._flag = ClientDebtFlag.AutomobileExpense;
}
protected override void ImportDebt(XRefClientBusiness xrefDb, XRefClientBusinessDebt converted)
{
if (this.IsDebtForUpdate(xrefDb, this._flag)) // Update
{
var xrefDebt = xrefDb.XRefClientBusinessDebts.FirstDefault(f => f.DebtSection.HasFlag(this._flag));
Guid updatedId = this.ProcessDebt(xrefDb, xrefDebt.DebtsAutomobileExpense, converted.DebtsAutomobileExpense, this._flag, this._repo);
this.AddUpdatedObjectToResult(updatedId, this._flag.ToString(),this._importObjType);
this.AddSystemDecisionObject(updatedId, this._objectType, ActivityAction.Modified);
}
else // Insert
{
Guid insertedId = this.ProcessDebt(xrefDb, null, converted.DebtsAutomobileExpense, this._flag, this._repo);
this.AddCreatedObjectToResult(insertedId, this._flag.ToString(), this._importObjType);
this.AddSystemDecisionObject(insertedId, this._objectType, ActivityAction.Added);
}
}
}
</code></pre>
<p>I have set up everything needed to change in the constructur, except two properties in the If Else statement. Imagine when I create the another 19 super similar cases, I will update the constructor enums and 3 places inside the If else statement like this:</p>
<pre><code> {
this._repo = this._unitOfWork.DebtsAutomobileExpenseRepository; // Update
this._objectType = ObjectType.DebtsAutomobileExpense; // Update
this._importObjType = ImportObjectType.DebtAutomobileExpense; // Update
this._flag = ClientDebtFlag.AutomobileExpense;
}
</code></pre>
<p>and</p>
<pre><code>// update second and third arguments (after the xrefDebt. and coverted. )
Guid updatedId = this.ProcessDebt(xrefDb, xrefDebt.DebtsAutomobileExpense, converted.DebtsAutomobileExpense, this._flag, this._repo);
</code></pre>
<p>I think this is the best approach, because it is clearer, the approach when every object deal with its own insert/update logic sound way more OOP correct.</p>
<p>But anyway, do you think there is a better way?</p>
<p>I was thinking for example, trying to make one generic <code>ImportProcessor</code> class, instead of 20, which will be called with all the needed enums in the constructor. The correct repository again in the constructor and for this part <code>xrefDebt.DebtsAutomobileExpense</code> to use some kind of reflection logic to take the correct property, but that sounds a bit confusing.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T11:42:19.723",
"Id": "485801",
"Score": "3",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T14:19:54.427",
"Id": "485825",
"Score": "0",
"body": "Is it better now? @Mast"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T14:22:29.233",
"Id": "485826",
"Score": "3",
"body": "The site standard is for the title to simply state the task accomplished by the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:54:34.717",
"Id": "485839",
"Score": "1",
"body": "@Jackie your title might be closest to the first example on the [How to Ask](https://codereview.stackexchange.com/help/how-to-ask) page under the list of examples that follow this text: _\"Here are some examples of titles that are unacceptable because they are too generic:\"_ Please see examples that follow the text \"_The norm is to summarize the goal of the code in the title. Some typical titles are:_\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T06:55:22.180",
"Id": "485899",
"Score": "0",
"body": "Ok, very helpfull! I have recieved 3 comments about question title and none about the real question. Sorry but this is not quite helpfull. I think the second title is OK. It is again generic, but otherwise i have to go too deep in details and write really long Title. However.."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T11:00:50.360",
"Id": "248082",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"generics"
],
"Title": "Making 90% similar code for 20 different objects"
}
|
248082
|
<p>This is some code written in a course I'm busy taking on Udemy. It serves as a basic toggle switch to flip between light and dark mode. This includes the nav bar, background, images and the icon that changes from a sun to a moon.</p>
<p>The objective after the lesson was to clean up the code and make it DRY. I've done so to some of the code already. But there are some instances where it still repeats, for instance <code>isDark</code> in my <code>lightDarkMode</code> function. Is there a way to eliminate the repetitive usage of <code>isDark</code>?</p>
<pre><code>const toggleSwitch = document.querySelector('input[type="checkbox"]');
const nav = document.getElementById('nav');
const toggleIcon = document.getElementById('toggle-icon');
const textBox = document.getElementById('text-box');
const darkLightTheme = ['dark', 'light'];
function imageMode(color) {
image1.src = `img/undraw_proud_coder_${color}.svg`;
image2.src = `img/undraw_feeling_proud_${color}.svg`;
image3.src = `img/undraw_conceptual_idea_${color}.svg`;
}
lightDarkMode = (isDark) => {
nav.style.backgroundColor = isDark ? 'rgb(0 0 0 / 50%)' : 'rgb(255 255 255 / 50%)';
textBox.style.backgroundColor = isDark ? 'rgb(255 255 255 / 50%)' : 'rgb(0 0 0 / 50%)';
toggleIcon.children[0].textContent = isDark ? 'Dark Mode' : 'Light Mode';
isDark ? toggleIcon.children[1].classList.replace('fa-sun', 'fa-moon') : toggleIcon.children[1].classList.replace('fa-moon', 'fa-sun');
isDark ? imageMode(darkLightTheme[0]) : imageMode(darkLightTheme[1]);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:55:03.153",
"Id": "485816",
"Score": "2",
"body": "Welcome to Code Review. The title of the question should be about what the code does, not what your concerns about the code are. You can put any concerns you have about the code into the body of the question. [Here](https://codereview.stackexchange.com/help/how-to-ask) are some suggestions on how to improve the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T13:29:11.313",
"Id": "485818",
"Score": "2",
"body": "It seems that there is no code repetition in the posted snippet. Maybe except for the RGB strings. getElementById is a function that you may need to call as many times as how many unique elements you want to look up. That's not code repetition. Anyway if you want some general feedback please include some description of the goal accomplished by the code. Maybe add some calling context of the code..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T13:42:07.863",
"Id": "485819",
"Score": "0",
"body": "Thank you for your feedback. I'm currently going over the documentation. I will then edit my post as suggested. @pacmaninbw"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T13:48:32.283",
"Id": "485820",
"Score": "0",
"body": "Thank you for the advice @slepic , I'm going to edit my post to make things clearer. I'm currently teaching myself. So i'm just learning as i go. I'm always doubting weather my code is sufficient enough. Or if i'm picking up the wrong way of doing things. So i appreciate your feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T18:52:06.667",
"Id": "485855",
"Score": "2",
"body": "Does this have to be primarily javascript based? In the case of toggling light/dark I prefer a simpler approach that applies a class to the body called `dark` assuming light is the default so it doesn't need a class. Then just reference `.dark nav{}` and `.dark #text-box{}` etc in your stylesheet. That would clean up the javascript tremendously as you would be simply toggling a class on the body and then only need to deal with the images."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T06:59:31.460",
"Id": "485900",
"Score": "1",
"body": "No it does not have to be primarily Javascript based. But i am struggling to understand Javascript. So i'm trying write as much code in Javascript as possible. But based on everyone's comment's the code looks fine as is. I guess i just needed that type of closure to know weather my code is sufficient enough. I don't want to pick up bad habits along the way and i don't have a mentor that could tell me if something is right or wrong. Thank you for your input about CSS. It is noted and it will be a route i go in future project. @imvain2"
}
] |
[
{
"body": "<p>One thing that you could update is how you are using the <code>ternary operator</code> for <code>isDark</code>.</p>\n<p>Ternary operators are used for returning something based on a boolean response, so either return X if true, or Y if false.</p>\n<p>However, every time it is used it is evaluating the statement being passed to it. In this case both times it is evaluating <code>isDark</code>. For the average website, this won't affect your processing time, but it is something to think about.</p>\n<p>Instead a classic if/else statement would allow you to run more code off a single evaluation.</p>\n<p>You will notice this isn't as <code>sleek looking</code> as ternary and is even more lines of code, but gives more capabilities when you need it.</p>\n<pre><code>if (isDark) {\n toggleIcon.children[1].classList.replace('fa-sun', 'fa-moon')\n imageMode(darkLightTheme[0])\n} else {\n toggleIcon.children[1].classList.replace('fa-moon', 'fa-sun')\n imageMode(darkLightTheme[1])\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T07:58:56.510",
"Id": "486112",
"Score": "0",
"body": "Thank you @imvain2 , That makes sense. Right now my main goal was to eliminate some of the ternary operators and this achieves that. Not to mention you have given me a better understanding if ternary operators and if else statements. I really appreciate your help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T17:55:00.133",
"Id": "248154",
"ParentId": "248086",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248154",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T12:17:30.797",
"Id": "248086",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Toggling between light and dark mode using JavaScript"
}
|
248086
|
<p>I recently started learning C, though I have some experience in other languages. I recently wrote a TicTacToe AI using the Minimax Algorithm in C. I would like to know how I could write better C.</p>
<pre><code>#include <stdio.h>
#define X -1
#define O -2
#define MAX_SIZE 50 //This is the Max size of the Input Buffer
int turn = O;
int board[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int variations = 0; //To keep track of no. of variations the ai has seen
void copyBoard(int from[], int to[]){
for(int i = 0; i < 9; i++){
to[i] = from[i];
}
}
//gets line WITHOUT \n
int getl(char s[], int lim){
int c, i;
for(i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; i++)
s[i] = c;
s[i] = '\0';
return i;
}
//Converts char[] to int
int bufferToNum(char buffer[]){
int n = 0;
for(int i = 0; buffer[i] != '\0'; i++){
n = 10 * n + buffer[i] - '0';
}
return n;
}
//converts the board numbers to char to display
char boardToChar(int i){
int a = board[i];
if (a == X){
return 'X';
} else if (a == O){
return 'O';
} else {
return a + '0';
}
}
//prints board
void printBoard(){
printf("=============\n| %c | %c | %c |\n-------------\n| %c | %c | %c |\n-------------\n| %c | %c | %c |\n=============\n", boardToChar(0), boardToChar(1), boardToChar(2), boardToChar(3), boardToChar(4), boardToChar(5), boardToChar(6), boardToChar(7), boardToChar(8));
}
//alternates turn
void alternateTurn(){
if (turn == O){
turn = X;
} else if (turn == X){
turn = O;
}
}
//returns 1 if draw, return 0 if not a draw
int drawCheck(int l_board[]){
for(int i = 0; i < 9; i++){
if (l_board[i] == i+1){
return 0;
}
}
return 1;
}
//returns X if X won and O if O one and 0 if nobody winning
int winCheck(int l_board[]){
//Rows
for (int i = 0; i < 3; i++){
if (l_board[3*i] == l_board[3*i + 1] && l_board[3*i + 1] == l_board[3*i + 2]){
return l_board[3*i];
}
}
//Columns
for (int j = 0; j < 3; j++){
if (l_board[j] == l_board[3 + j] && l_board[3 + j] == l_board[6 + j]){
return l_board[j];
}
}
//Diagonal Top Left to Bottom Right
if (l_board[0] == l_board[4] && l_board[0] == l_board[8]){
return l_board[0];
}
//Diagonal Top Right to bottom Left
if (l_board[2] == l_board[4] && l_board[2] == l_board[6]){
return l_board[2];
}
return 0;
}
//1 if nothing is ther and 0 if something was already ther
int putInBoard(int l_board[], int pos, int newVal){
if (l_board[pos] == pos+1){
l_board[pos] = newVal;
return 1;
} else
{
return 0;
}
}
//X if X win, O if O win, 0 if draw, 1 if nothing
int gameState(int l_board[]){
int wc = winCheck(l_board);
if (wc == X){
return X;
} else if(wc == O){
return O;
} else {
if (drawCheck(l_board)){
return 0;
}
}
return 1;
}
void legalMoves(int l_board[], int output[]){
for(int i = 0; i < 9; i++){
if (l_board[i] == i+1){
output[i] = 1;
} else {
output[i] = 0;
}
}
}
int max(int a, int b){
return a>b ? a : b;
}
int min(int a, int b){
return a<b ? a : b;
}
//X is ai
int minimax(int l_board[], int depth, int maximising){
int gs = gameState(l_board);
variations++;
if (gs == X){
return 10;
} else if (gs == O){
return -10;
} else if (gs == 0){
return 0;
}
if (depth == 0){
return 0;
}
if (maximising){
//Its AI's Turn so it has to maximise
int val = -100;
int legalMovesArr[9];
legalMoves(l_board, legalMovesArr);
for (int i = 0; i < 9; i++){
if (legalMovesArr[i]){
int tempBoard[9];
copyBoard(l_board, tempBoard);
putInBoard(tempBoard, i, X);
val = max(minimax(tempBoard, depth-1, 0), val);
}
}
return val;
} else {
int val = 100;
int legalMovesArr[9];
legalMoves(l_board, legalMovesArr);
for (int i = 0; i < 9; i++){
if (legalMovesArr[i]){
int tempBoard[9];
copyBoard(l_board, tempBoard);
putInBoard(tempBoard, i, O);
val = min(minimax(tempBoard, depth-1, 1), val);
}
}
return val;
}
}
int ai(int l_board[], int depth){
int legalMovesArr[9];
legalMoves(board, legalMovesArr);
int val = -100;
int best_move = 0;
for (int i = 0; i < 9; i++){
if (legalMovesArr[i]){
int tempBoard[9];
copyBoard(l_board, tempBoard);
putInBoard(tempBoard, i, X);
int temp = minimax(tempBoard, depth-1, 0);
if (val <= temp){
val = temp;
best_move = i;
}
}
}
return best_move;
}
int main(){
printBoard();
int gameOn = 0;
char buffer[MAX_SIZE];
while(!gameOn){
if (turn == O){
printf("%c's turn: ", turn == X ? 'X' : 'O');
getl(buffer, MAX_SIZE);
int num = bufferToNum(buffer);
while (num <= 0 || num > 9){
printf("Please enter an integer between 1 and 9: ");
getl(buffer, MAX_SIZE);
num = bufferToNum(buffer);
}
if (putInBoard(board, num-1, turn)){
;
} else {
while(!putInBoard(board, num-1, turn)){
printf("Something already exists, Please enter a new number: ");
getl(buffer, MAX_SIZE);
num = bufferToNum(buffer);
}
}
} else {
putInBoard(board, ai(board, 8), X);
printf("Calculated %d variations\n", variations);
variations = 0;
}
printBoard();
alternateTurn();
int gs = gameState(board);
if (gs == X){
printf("X won!");
return 0;
} else if (gs == O){
printf("O won!");
return 0;
} else if (gs == 0){
printf("Draw!");
return 0;
}
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h2>General Observations</h2>\n<p>I see a lot of good programming practices followed here already, keep up the good work.</p>\n<p>Most of the functions are small and follow the Single Responsibility Principle.</p>\n<h2>Use Library Functions When You Can</h2>\n<p>The function <code>getl()</code> can be implemented using 2 standard C library functions, <a href=\"http://www.cplusplus.com/reference/cstdio/fgets/\" rel=\"noreferrer\">fgets</a> and <a href=\"http://www.cplusplus.com/reference/cstring/strrchr\" rel=\"noreferrer\">strrchr</a>.</p>\n<p>The <code>fgets()</code> function inputs an entire line of characters at a time, rather than using character input, and the <code>strrchr()</code> will allow you to find the <code>\\n</code> character and replace it.</p>\n<h2>DRY Code</h2>\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n<p>The repetition occurs in the function <code>int minimax(int l_board[], int depth, int maximising)</code> :</p>\n<pre><code> if (maximising) {\n //Its AI's Turn so it has to maximise\n int val = -100;\n int legalMovesArr[9];\n legalMoves(l_board, legalMovesArr);\n for (int i = 0; i < 9; i++) {\n if (legalMovesArr[i]) {\n int tempBoard[9];\n copyBoard(l_board, tempBoard);\n putInBoard(tempBoard, i, X);\n val = max(minimax(tempBoard, depth - 1, 0), val);\n }\n }\n return val;\n }\n else {\n int val = 100;\n int legalMovesArr[9];\n legalMoves(l_board, legalMovesArr);\n for (int i = 0; i < 9; i++) {\n if (legalMovesArr[i]) {\n int tempBoard[9];\n copyBoard(l_board, tempBoard);\n putInBoard(tempBoard, i, O);\n val = min(minimax(tempBoard, depth - 1, 1), val);\n }\n }\n</code></pre>\n<p>This repeating code could be it's own function.</p>\n<p>The repeating code also makes the function too complex.</p>\n<h2>Complexity</h2>\n<p>The complexity of the function <code>minimax()</code> was mentioned above, the function <code>main()</code> is also too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>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 that module, class or function.</p>\n</blockquote>\n<p>The entire <code>while (!gameOn)</code> loop should be within its own function.</p>\n<h2>Avoid Global Variables</h2>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<h2>Update Answer to comment</h2>\n<pre><code>void game_loops()\n{\n if (turn == O) {\n printf("%c's turn: ", turn == X ? 'X' : 'O');\n char buffer[MAX_SIZE];\n getl(buffer, MAX_SIZE);\n int num = bufferToNum(buffer);\n while (num <= 0 || num > 9) {\n printf("Please enter an integer between 1 and 9: ");\n getl(buffer, MAX_SIZE);\n num = bufferToNum(buffer);\n }\n if (putInBoard(board, num - 1, turn)) {\n ;\n }\n else {\n while (!putInBoard(board, num - 1, turn)) {\n printf("Something already exists, Please enter a new number: ");\n getl(buffer, MAX_SIZE);\n num = bufferToNum(buffer);\n }\n }\n }\n else {\n putInBoard(board, ai(board, 8), X);\n printf("Calculated %d variations\\n", variations);\n variations = 0;\n }\n\n printBoard();\n alternateTurn();\n}\n\nint main() {\n printBoard();\n\n int gs = 1;\n while (gs == 1) {\n game_loops();\n gs = gameState(board);\n }\n\n switch (gs)\n {\n case X:\n printf("X won!");\n break;\n\n case O:\n printf("O won!");\n break;\n\n default:\n printf("Draw!");\n break;\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T17:38:05.883",
"Id": "485847",
"Score": "0",
"body": "First of all, thanks for your answer. I have few comments and questions though. 1)I understand your point of getl and I would use the standard library functions in actual code, but I wanted to do low-level stuff and implement my own functions for these tasks. 2) How would copying the whole main() code to a function help in readability? 3)I think I had minimal global variables, what variables should not have been in the global scope? Thank you for your time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T18:10:06.917",
"Id": "485853",
"Score": "4",
"body": "The minimal and desired number of global variables is zero, nothing should be done by side affects. This program is very easy to write without global variables. I've updated the answer to show how it readable the loop would be, but every removal of indentation helps readability. You don't want to use character by character input when you can use buffered input instead for performance reasons."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T02:22:11.133",
"Id": "485876",
"Score": "0",
"body": "I understand, thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T05:48:45.853",
"Id": "485895",
"Score": "1",
"body": "\"getl() can be implemented using 2 standard C library functions\" --> OP's `getl()` has an obscure advantage: it returns the correct number of characters read when one of them is surprisingly a _null character_. `fgets()/strrchr()` needs more to support that rare need. Also the `fgets()` approach needs a +1 size buffer."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T17:27:01.127",
"Id": "248096",
"ParentId": "248093",
"Score": "9"
}
},
{
"body": "<p>Small review</p>\n<p><strong>Break up that long line of code.</strong></p>\n<pre><code>//prints board\nvoid printBoard(){\n printf("=============\\n| %c | %c | %c |\\n-------------\\n| %c | %c | %c |\\n-------------\\n| %c | %c | %c |\\n=============\\n", boardToChar(0), boardToChar(1), boardToChar(2), boardToChar(3), boardToChar(4), boardToChar(5), boardToChar(6), boardToChar(7), boardToChar(8)); \n}\n</code></pre>\n<p>Perhaps as</p>\n<pre><code>//prints board\nvoid printBoard() {\n printf("=============\\n"\n "| %c | %c | %c |\\n"\n "-------------\\n"\n "| %c | %c | %c |\\n"\n "-------------\\n"\n "| %c | %c | %c |\\n"\n "=============\\n", //\n boardToChar(0), boardToChar(1), boardToChar(2), //\n boardToChar(3), boardToChar(4), boardToChar(5), // \n boardToChar(6), boardToChar(7), boardToChar(8)); \n}\n</code></pre>\n<p>For me, the <code>//</code> at the end of 3 lines prevent auto formatting of those lines into 1 or 2 lines.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T07:09:47.343",
"Id": "485903",
"Score": "0",
"body": "Yes, that looks much better. I remember from K&R that we can do \"hello\" \" world\" but I didn't think of it while coding. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T10:09:45.860",
"Id": "486414",
"Score": "0",
"body": "Wouldn't a printf for each line be cleaner and easier to maintain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-24T14:19:25.860",
"Id": "486434",
"Score": "0",
"body": "@CacahueteFrito Versu OP's code, \"printf for each line\" sounds like an interesting alternative to this answer's re-format only approach. Perhaps post as an answer? For me, 6.01 vs. half-a-dozen of the other - a difference, but not much."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T05:57:35.237",
"Id": "248123",
"ParentId": "248093",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T15:44:14.120",
"Id": "248093",
"Score": "6",
"Tags": [
"c",
"tic-tac-toe",
"ai"
],
"Title": "TicTacToe with AI in C"
}
|
248093
|
<p>recently I wanted to create a morse encoder/decoder with playback ability, the program needs <code>java version >= 11</code> to run.</p>
<p>the program requires a couple of <code>jar</code>s :</p>
<ul>
<li><p><code>com.google.common.collect.BiMap</code></p>
</li>
<li><p><code>javazoom.jl.player.Player</code></p>
</li>
</ul>
<p>I used the <code>BiMap</code> for the following reason:</p>
<blockquote>
<p>A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.<a href="https://guava.dev/releases/19.0/api/docs/com/google/common/collect/BiMap.html" rel="nofollow noreferrer">ref</a></p>
</blockquote>
<p>As many online Morse translators, use the character <code>'/'</code> or a <code>','</code> to be translated into space I used the <code>'\t'</code>.</p>
<p>Structure wise I used the Singleton Design pattern To allow the user of having a limited amount of objects thus there is no need to create an object to encode/decode if it already exists.</p>
<p>The program features the following:</p>
<ol>
<li><p>Flexible thus it can read from the desired database.</p>
</li>
<li><p>Compatible with all kinds of allowed <code>CharSet</code> backed by java(when using the right charset to read a certain file).</p>
</li>
<li><p>Audio playback to help people learn to understand morse code by hearing!.</p>
</li>
<li><p>Ability to write results into a file by the desired path.</p>
</li>
<li><p>The program takes regex into consideration when it comes to reading the database file as the regex would act as a separator between the actual letter and the sequence of dots and dashes.</p>
</li>
</ol>
<p><strong>So here is the Code:</strong></p>
<pre><code>import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import static com.google.common.collect.Maps.unmodifiableBiMap;
/**
* This class represents Encoder and Decoder for Morse code.
* @author Kazem Aljalabi.
*/
public final class Morse {
private Path dataBaseFile;
private BiMap<String, String> data;
private Charset cs = StandardCharsets.UTF_8;
private String charSeparationRegex = " ";
//Singleton Pattern via Lazy Instantiation = private constructor + static object that will be created once!.
private static Morse defaultObj, pathObj, objWithSeparator, objWithCharSet;
/**
* This Method creates a class instance of type {@link Morse} if not created before else return the already created object.
* @return a class instance of type {@link Morse}.
*/
public static Morse getInstance() {
if (null == defaultObj)
defaultObj = new Morse();
return defaultObj;
}
/**
* This Method creates a class instance of type {@link Morse} if not created before else return the already created object.
* @param dataBaseFile the path to the database which contains the actual decoding and encoding table of the morse code.
* @return a class instance of type {@link Morse} linked with a database of user's choice via a {@link Path}.
*/
public static Morse getInstance(final Path dataBaseFile) {
if (null == pathObj)
pathObj = new Morse(dataBaseFile);
return pathObj;
}
/**
* This Method creates a class instance of type {@link Morse} if not created before else return the already created object.
* @param dataBaseFile the {@link Path} to the database which contains the actual decoding and encoding table of the morse code.
* @param separator the regex which will act as a separator between the actual letter and its representation in morse code.
* @return a class instance of type {@link Morse} linked with database path and a separator.
*/
public static Morse getInstance(final Path dataBaseFile, final String separator) {
if (null == objWithSeparator)
objWithSeparator = new Morse(dataBaseFile, separator);
return objWithSeparator;
}
/**
* This Method creates a class instance of type {@link Morse} if not created before else return the already created object.
* @param dataBaseFile the path to the database which contains the actual decoding and encoding table of the morse code.
* @param separator the regex which will act as a separator between the actual letter and its representation in morse code.
* @param cs the {@link Charset} in which the database is written with.
* @return a class instance of type {@link Morse} linked with the database with a specific path, charset, and separator.
*/
public static Morse getInstance(final Path dataBaseFile, final String separator, final Charset cs) {
if (null == objWithCharSet)
objWithCharSet = new Morse(dataBaseFile, separator, cs);
return objWithCharSet;
}
/**
* @param dataBaseFile path to the new dataBaseFile to be set.
*/
public void setDataBaseFile(Path dataBaseFile) {
this.dataBaseFile = dataBaseFile;
checkForDataBase();
}
/**
* Constructor to create a class instance of type {@link Morse} with a default database called "Code.txt" placed in the same dir with the class.
*/
private Morse() {
dataBaseFile = Paths.get(Morse.class.getResource( "Morse.class" ).getPath()).toAbsolutePath().normalize().getParent().resolve("Code.txt");
checkForDataBase();
}
/**
* Constructor creates a class instance of type {@link Morse} with a custom database provided by the user via a valid path.
* @param dataBaseFile the path to the database which contains the actual decoding and encoding table of the morse code.
*/
private Morse(final Path dataBaseFile) {
this.dataBaseFile = dataBaseFile;
checkForDataBase();
}
/**
* Constructor creates a class instance of type {@link Morse} with a custom database with a specific separator provided by the user via a valid path.
* @param dataBaseFile the {@link Path} to the database which contains the actual decoding and encoding table of the morse code.
* @param separator the regex which will act as a separator between the actual letter and its representation in morse code.
*/
private Morse(final Path dataBaseFile, final String separator) {
this (dataBaseFile);
assert separator != null;
if ( checkForRegexValidity(separator) && !separator.contains(".") && !separator.contains("_") ) //those are reserved to the morse code!
this.charSeparationRegex = separator;
}
/**
* Constructor creates a class instance of type {@link Morse} with a custom database with a specific separator provided by the user via a valid path.
* The database file is written in a specific CharSet.
* @param dataBaseFile the path to the database which contains the actual decoding and encoding table of the morse code.
* @param separator the regex which will act as a separator between the actual letter and its representation in morse code.
* @param cs the {@link Charset} in which the database is written with.
*/
private Morse(final Path dataBaseFile, final String separator, final Charset cs) {
this (dataBaseFile, separator);
this.cs = cs;
}
/**
* Method to check the existence of database path.
*/
private void checkForDataBase () {
if (!Files.exists(dataBaseFile))
System.exit(1);
data = unmodifiableBiMap(populateFromDataBase());
}
/**
* Method to check if the separator provided by the user is a valid regex.
* @param regex database separator provided by the user.
* @return true if the regex is valid else false.
*/
private boolean checkForRegexValidity (String regex) {
PatternSyntaxException flag = null;
try {
Pattern.compile(regex);
} catch (PatternSyntaxException exception) { flag=exception; }
return flag == null;
}
/**
* Method to populate the Database from the database {@link java.io.File}.
* @return a {@link BiMap} which contains the encoding/decoding schema of the Morse code based on the database file.
*/
private BiMap<String, String> populateFromDataBase () {
List<String> encodingSchema = new ArrayList<>();
try {
encodingSchema = Files.readAllLines(dataBaseFile, cs);
} catch (IOException e) { e.printStackTrace(); }
//To prevent the empty of being inserted inside the Hash we need to filter it out!
return encodingSchema.stream().filter(s -> !s.equals(""))
.collect(Collectors.toMap(
e -> e.replaceAll(charSeparationRegex," ").strip().split("\\s+")[0]
, e -> e.replaceAll(charSeparationRegex," ").strip().split("\\s+")[1]
, (e1, e2) -> e2
, HashBiMap::create)
);
}
/**
* Method which will write a specific message to a given file.
* @param data The data to be written to a file. the data can be an already encoded message or the decoded message of an already encoded message!.
* @param resultsPath the path where the results would be written, if it doesn't exist it will be created.
*/
public void writeResultsToFile (String data, Path resultsPath) {
try {
Files.writeString(resultsPath, data, StandardOpenOption.CREATE);
} catch (IOException e) { e.printStackTrace(); }
}
/**
* Method to decode a given Message based on the given database and the morse code logic.
* @param message to be decoded assuming that the message contains only '_' and '.', assuming that the message given contains no foreign chars that don't exist in the database given.
* @return a decoded version of the provided message.
*/
public String decodeMessage(String message) {
var builder = new StringBuilder();
for (var str : message.strip().split("\t"))
builder.append(decodeHelper(str)).append(" ");
return builder.toString().strip();
}
/**
* A helper method to decode One Word at a time.
* @param word which consists of '_' and '.' which will be encoded accordingly to the given database.
* @return a valid decoded word.
*/
private StringBuilder decodeHelper (String word) {
return Arrays.stream(word.split(" "))
.collect(StringBuilder::new
, (builder, s) -> builder.append(data.inverse().getOrDefault(s, " "))
, StringBuilder::append
);
}
/**
* Method to encode a certain message based on the provided database.
* @param message to be encoded assuming that the message given contains no foreign chars that don't exist in the database given.
* @return an encoded version to the provided message which consists of only '_' and '.'.
*/
public String encodeMessage (String message) {
var builder = new StringBuilder();
for (var str : message.toUpperCase().strip().split("")) {
builder.append(data.getOrDefault(str, ""));
if (!str.equals(" "))
builder.append(" ");
else
builder.append("\t");//insert tap to tell when word ends!.
}
return builder.toString().strip();
}
/**
* Method to play the actual sound of a certain message while being encoded.
* @param data to be encoded.
*/
public void encodeAndPlayAudio (String data) {
var encoded = encodeMessage(data).split("\t");
var tabsNumber = encoded.length-1;
for (var c : encoded) {
playAudio(c);
if (tabsNumber-- > 0){
System.out.print("\t");
try { Thread.sleep(1000); } catch (InterruptedException ignored) { }
}
}
System.out.println();
}
/**
* @param filename of the soundtrack to be played.
*/
private void playMp3 (String filename) {
try (var fis = new FileInputStream(Morse.class.getResource(filename).getPath())) {
new Player(fis).play();
} catch (IOException | JavaLayerException e) { e.printStackTrace(); }
}
/**
* Method to decide which soundtrack will get played based on the current char.
* @param encodeMessage which will be played.
*/
private void playAudio (String encodeMessage) {
for (var c : encodeMessage.strip().toCharArray()){
if (c == '.')
playMp3("di.mp3");
else if (c == '_')
playMp3("dah.mp3");
System.out.print(c);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Morse morse = (Morse) o;
return dataBaseFile.equals(morse.dataBaseFile) &&
data.equals(morse.data);
}
@Override
public int hashCode() { return Objects.hash(dataBaseFile, data); }
@Override
public String toString() {
return "Morse{" +
"dataBaseFile=" + dataBaseFile +
", data=" + data +
'}';
}
}
</code></pre>
<p><strong>DataBase sample <code>code.txt</code></strong> (of course this can be extended when desired) :</p>
<pre><code>A ._
B _...
C _._.
D _..
E .
F .._.
G __.
H ....
I ..
J .___
K _._
L ._..
M __
N _.
O ___
P .__.
Q __._
R ._.
S ...
T _
U .._
V ..._
W .__
X _.._
Y _.__
Z __..
1 .____
2 ..___
3 ...__
4 ...._
5 .....
6 _....
7 __...
8 ___..
9 ____.
0 _____
</code></pre>
<p><strong>The user main would look like this</strong> :</p>
<pre><code>public class Main {
public static void main(String[] args) {
var obj = Morse.getInstance();
System.out.println(obj.encodeMessage("cool java"));
obj.encodeAndPlayAudio("cool java");
}
}
</code></pre>
<p><strong>The audio files can be found in Wikipedia</strong></p>
<ol>
<li>dot sound which is basically an <code>'E'</code> can be found <a href="https://en.wikipedia.org/wiki/File:E_morse_code.ogg" rel="nofollow noreferrer">here</a>!</li>
<li>dash sound which is basically a <code>'T'</code> can be found <a href="https://en.wikipedia.org/wiki/File:T_morse_code.ogg" rel="nofollow noreferrer">here</a>!</li>
</ol>
<p><strong>What to review:</strong></p>
<p>I would like a style, design, and functional review. What is done good, what should be done better or differently? What alternative solution would you propose?</p>
<p>Please note that this project is made for fun and educational purposes and is not a part of a university assignment!.</p>
<p>As explained by @Sᴀᴍ Onᴇᴌᴀ in the comments I shall not update my code to incorporate feedback from answers "doing so goes against the Question + Answer style of Code Review" thus here is the current status on my <a href="https://github.com/hakunamatata97k/Morse-Encoder-Decoder/blob/master/Morse_Code/src/MorseResolver/Morse.java" rel="nofollow noreferrer">Github</a>.</p>
<p>Thanks in Advance :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:38:00.837",
"Id": "485955",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://meta.codereview.stackexchange.com/a/1765)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:45:28.107",
"Id": "485957",
"Score": "0",
"body": "cool, I didn't know that! but you could just comment that you didn't have to force an edit. lol. but thnx for pointing that out."
}
] |
[
{
"body": "<p>The <code>getInstance</code> methods are severely limiting the class and are a source of potential bugs. There is no reason that it shouldn't be possible, for example, to create two objects with that access two different database files:</p>\n<pre><code>Morse morse1 = Morse.getInstance(Paths.get("file1"));\nMorse morse2 = Morse.getInstance(Paths.get("file2"));\n</code></pre>\n<p>However in this example, <code>morse2</code> unexpectedly doesn't use <code>"file2"</code>, instead is the same instance as <code>morse1</code> which uses <code>"file1"</code>.</p>\n<p>(EDIT: You should avoid setters, if you can. Immutable classes are usually preferable. If you, for example, want to change databases at runtime, it's preferable to create a new object using that other database, than changing an existing object.)</p>\n<hr />\n<p>The constructors should be structured differently, so that all the logic/validation only happens in a single one and the other constructors only call that one constructor with the default values.</p>\n<p>EDIT: Currently you have two constructors that call <code>checkForDataBase()</code>, and another one that validates the separator. Instead you should have a single "main" constructor (probably <code>Morse(final Path dataBaseFile, final String separator, final Charset cs)</code>), than contains all the validation and have the others call that one using the default values for the missing parameters. For eaxmple:</p>\n<pre><code>private final static String DEFAULT_SEPARATOR = " ";\nprivate final static CharSet DEFAULT_CHARSET = StandardCharsets.UTF_8;\n\npublic Morse(final Path dataBaseFile, final String separator, final Charset cs) {\n // All validation and setting instance fields here\n}\n\npublic Morse() {\n this(defaultDatabaseFile());\n // or: this(defaultDatabaseFile(), DEFAULT_SEPARATOR, DEFAULT_CHARSET)\n}\n\npublic Morse(final Path dataBaseFile) {\n this(dataBaseFile, DEFAULT_SEPARATOR);\n // or: this(dataBaseFile, DEFAULT_SEPARATOR, DEFAULT_CHARSET)\n}\n\npublic Morse(final Path dataBaseFile, final String separator) {\n this(dataBaseFile, separator, DEFAULT_CHARSET);\n}\n</code></pre>\n<hr />\n<p>Retrieving the default database file seems a bit convoluted, especially with the hard-coded class file name <code>"Morse.class"</code>, which easily can be overlooked, if the class is ever renamed.</p>\n<p>Unless I'm mistaken (I don't like handling resources), it should be possible with:</p>\n<pre><code>Paths.get(Morse.class.getResource("../Code.txt").toURI());\n</code></pre>\n<hr />\n<p>The <code>assert</code> keyword is not for validating parameters. It is used during development to catch states than should never occur. <code>assert</code> would normally be disabled at production runtime. Instead use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#requireNonNull-T-\" rel=\"nofollow noreferrer\"><code>Objects.requireNonNull</code></a>.</p>\n<hr />\n<p><code>separator.contains(".")</code> is an unreliable way to check if a regular expression matches a period, because it is special character in regular expressions that matches any character. It probably would be better to check for <code>\\.</code> (<code>"\\\\."</code> as a Java string). Or maybe not let the user directly assign a regular expression as the separator at all, but an array of chars/strings instead, from which you build a regular expression.</p>\n<hr />\n<p>Using <code>System.exit(1)</code> inside a utility class like this is unexpected and thus a bad idea. You should be throwing an exception here, which you could catch in <code>main()</code> and possibly use <code>System.exit()</code> there.</p>\n<hr />\n<p><code>checkForRegexValidity</code> seems unnesserily complex. There is no need to store the thrown exception. Just directly return <code>true</code> or <code>false</code>:</p>\n<pre><code>private boolean checkForRegexValidity (String regex) {\n try {\n Pattern.compile(regex);\n return true;\n } catch (PatternSyntaxException exception) { \n return false;\n }\n}\n</code></pre>\n<hr />\n<p>When encountering an exception when reading the database file, don't just print the stack trace and otherwise ignore the error. Personally I'd just let the exception go through and catch it outside this class. Actually you could just drop <code>checkForDataBase</code> and just have the IOException due to the missing file go through.</p>\n<hr />\n<p>During filling the map you are unnecessarily cleaning up and splitting the lines twice. With an additional <code>.map</code> step in the stream that can be avoided:</p>\n<pre><code>return encodingSchema.stream().filter(s -> !s.equals(""))\n .map(e -> e.replaceAll(charSeparationRegex," ").strip().split("\\\\s+"))\n .filter(e -> e.length < 2) // also skip invalid lines\n .collect(Collectors.toMap(\n e -> e[0]\n , e -> e[1]\n , (e1, e2) -> e2\n , HashBiMap::create)\n );\n</code></pre>\n<hr />\n<p>I don't really see the point in using a <code>BiMap</code> here. If you where constantly adding or removing entries from it, then it would be certainly be a good idea, however in this case the map is static so I'd just create two normal maps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:49:01.950",
"Id": "485959",
"Score": "0",
"body": "thanks for your suggestion. I took your suggestions into my consideration. in my code i replaced assertion, with `Objects.requireNonNull` and I would rather use `getPath()` instead of using `toUrl()` thus I won't have to catch exceptions in my constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:57:44.470",
"Id": "485961",
"Score": "0",
"body": "please provide me with a better explanation about what you mean with \"The constructors should be structured differently\".\n\n\nplease provide me with a better explanation about what you mean with \"The constructors should be structured differently\". \n\n\n\nabout what you mentioned about creating a second object for a different database I think there is no need for having a new object while I can add a database setter that would resolve that problem in my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T16:07:53.253",
"Id": "485962",
"Score": "0",
"body": "I just added the setter which I already wrote but didn't upload because I thought it was not needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T07:42:26.527",
"Id": "486010",
"Score": "0",
"body": "@Studenaccount4 Updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T19:43:33.357",
"Id": "486180",
"Score": "0",
"body": "using the `HashBiMap` was very helpful for me because of the `inverse()` in the decoding where one would need to get key by value which is not supported by the default hashmap. and about the regex well checking for the dot and the underscore is the easiest thing and yet gets the job done without getting into trouble of creating the regex myself based on a string given by the user.\nI linked the GitHub link and i would really appreciate it if you look at it :) thanks for the efforts taken to write this review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T19:46:15.183",
"Id": "486181",
"Score": "0",
"body": "later on, I added a hashmap to act as a \"set\" it will check if the object has been created it will return it to the user. due to the fact that one cant retrieve elements from a Set, I used hashmap with the object itself as key and value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-21T19:48:49.943",
"Id": "486182",
"Score": "0",
"body": "in my opinion, I can't see a situation where `filter(e -> e.length < 2)` would be triggered, and placing 2 would result in an empty map. changing the 2 to 3 would solve it but still can't imagine a situation where this could be triggered."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:02:12.000",
"Id": "248148",
"ParentId": "248094",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248148",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T16:33:43.617",
"Id": "248094",
"Score": "4",
"Tags": [
"java",
"morse-code"
],
"Title": "Morse code encoder/decoder with playback ability"
}
|
248094
|
<p>Given a text I have to find the preceding words to all numbers up to a stop word belonging to a check_words list (kind of stopwords).</p>
<p>My code:</p>
<pre><code>check_words = ['the', 'a', 'with','to']
mystring = 'the code to find the beautiful words 78 that i have to nicely check 45 with the snippet'
list_of_words = mystring.split()
</code></pre>
<p>In that particular text I would check before <code>'78'</code> and <code>'45'</code> and will go backwards up to the point where I find any of the words in check_words (but not more than 8 words).</p>
<p>The code for doing that might be:</p>
<pre><code>preceding_chunks = []
for i,word in enumerate(list_of_words):
if any(char.isdigit() for char in word):
# 8 precedent words (taking into account that I can not slice with 8 back at the beginning)
preceding_words = list_of_words[max(0,i-8):i]
preceding_words[::-1]
# I check from the end of the list towards the start
for j,sub_word in enumerate(preceding_words[::-1]):
if sub_word in check_words:
# printing out j for checking
myposition = j
print(j)
real_preceding_chunk = preceding_words[len(preceding_words)-j:]
print(real_preceding_chunk)
preceding_chunks.append(real_preceding_chunk)
break
</code></pre>
<p>This code works.
basically I check every word tha
But I have the impression (perhaps I am wrong) that it can be achieved with a couple of one liners and hence without loops.
Any idea?</p>
<hr />
<p>NOTE:
This question is about improvement the readability of the code, trying to get rid of the loops to make the code faster, and trying to make the code nicer, which is part of the Zen of Python.</p>
<hr />
<p>NOTE 2: Some previous checks that I did:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/43124086/finding-the-position-of-an-item-in-another-list-from-a-number-in-a-different-lis">Finding the position of an item in another list from a number in a different list</a></li>
<li><a href="https://stackoverflow.com/questions/176918/finding-the-index-of-an-item-in-a-list">Finding the index of an item in a list</a></li>
<li><a href="https://stackoverflow.com/questions/9542738/python-find-in-list">Find in list</a></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T18:22:21.507",
"Id": "485854",
"Score": "2",
"body": "[Cross-posted to Stack Overflow](https://stackoverflow.com/q/63473158/1014587)"
}
] |
[
{
"body": "<p>I came up with this:</p>\n<pre><code>import itertools\nimport re\n\nchunks = (grouped_chunk.split() for grouped_chunk in re.split("\\\\s+\\\\d+\\\\s+", mystring))\npreceding_chunks = []\n\nfor reversed_chunk in map(reversed, chunks):\n preceding_chunk = list(itertools.takewhile(lambda word: word not in check_words, reversed_chunk))[::-1]\n preceding_chunks.append(preceding_chunk)\n</code></pre>\n<p>We apply <code>itertools.takewhile</code> to the <code>reversed_chunk</code> which gives us the preceding chunk in reversed order. We then obtain the correctly ordered <code>preceding_chunk</code> by reversing at the end with <code>[::-1]</code>.</p>\n<p>The regex splits <code>mystring</code> based on a number (the escaped <code>\\d+</code>). The surrounding escaped <code>\\s+</code>s represent any padding around the number. This causes this code to have different behavior than yours if digits and letters are mixed in the same words (for example, <code>a1</code>).</p>\n<p>For your original code, I'd make a couple suggestions:</p>\n<ol>\n<li>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. For example, add spacing after the comma in <code>i,word</code>.</li>\n<li>Remove the redundant expression <code>preceding_words[::-1]</code>. While this does evaluate to the reversed <code>preceding_words</code>, because it is not in-place, the evaluation has no side-effects. Plus, you already perform this reversal in <code>enumerate(preceding_words[::-1])</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T02:13:21.987",
"Id": "248116",
"ParentId": "248099",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "248116",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T17:57:53.343",
"Id": "248099",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Find the noun phrase before and after a number in a text"
}
|
248099
|
<h1>Problem</h1>
<p>I'm writing a simple shell, and I want to have the nice autocomplete feature that bash has when you partially type a word then press <kbd>tab</kbd>:</p>
<p><a href="https://i.stack.imgur.com/v6cT3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/v6cT3.png" alt="bash example" /></a></p>
<p>Right now it can work independently from a shell, but it has features that allow it to find commands on the system. Examples:</p>
<pre><code>>>> table = make_lookup_table_from(["hell", "water", "help", "air", "hello", "fire", "earth"])
>>> find_matching(table, "hel")
['hell', 'hello', 'help']
>>> table = make_lookup_table_from_path()
>>> find_matching(table, "gcc-")
['gcc-ar', 'gcc-ar-8', 'gcc-ar-9', 'gcc-nm', 'gcc-nm-8', 'gcc-nm-9', 'gcc-ranlib', 'gcc-ranlib-8', 'gcc-ranlib-9', 'gcc-8', 'gcc-9']
>>> find_matching(table, "pyth")
['python3.8', 'python3.8-config', 'python3', 'python3-qr', 'python3-futurize', 'python3-pasteurize', 'python3-tor-prompt', 'python3-config', 'python3-wsdump', 'python', 'python-argcomplete-check-easy-install-script', 'python-argcomplete-check-easy-install-script3', 'python-argcomplete-tcsh', 'python-argcomplete-tcsh3', 'python-config', 'python-faraday', 'python2-config', 'python2-futurize', 'python2-pasteurize', 'python2-pbr', 'python2', 'python2.7-config', 'python2.7']
</code></pre>
<h1>How it works:</h1>
<p>Each word is put into a nested dictionary letter-by-letter, then terminated by a null character to mark the end of a word:</p>
<pre><code>>>> make_lookup_table_from(["hell", "water", "help", "air", "hello", "fire", "earth"])
{'h': {'e': {'l': {'l': {'\x00': {}, 'o': {'\x00': {}}}, 'p': {'\x00': {}}}}}, 'w': {'a': {'t': {'e': {'r': {'\x00': {}}}}}}, 'a': {'i': {'r': {'\x00': {}}}}, 'f': {'i': {'r': {'e': {'\x00': {}}}}}, 'e': {'a': {'r': {'t': {'h': {'\x00': {}}}}}}}
</code></pre>
<p>To do a lookup to find matches, the tree is walked until the common sub-dictionary is found, then each word is recursively reconstructed.</p>
<h1>Focus:</h1>
<p>Honestly, I've been in school focusing on other things beside code, so I've gotten a little rusty. I'm using a couple less-than-ideal techniques, so any recommendations are welcome:</p>
<ul>
<li><p>The lookup function <code>_extract_strings</code> makes use of recursion, because this seemed like a painful problem to solve iteratively. If I'm missing an obvious alternate way, I'd appreciate any tips there.</p>
</li>
<li><p>In the recursive function, I'm using strings to keep track of the word "so far", and passing concatenated copies to the children for them to use. I was originally using lists so I could just <code>append</code> without creating a new object each time, but sharing the mutable list between recurses proved to be problematic. I'm also returning only endings from the lookup function then reconstructing the full word in <code>find_matching</code>. This necessitates <code>string +</code> for every found string though, which isn't great.</p>
</li>
</ul>
<p>These functions actually perform surprisingly fast. I was going to setup a caching, load-from-disk-on-start system to avoid needing to reconstruct the table constantly, but it's so fast that it doesn't seem worth it. As a result, both my concerns above probably fall under "premature-optimizations", but I'd still like suggestions on them or anything else, from style to other best practices.</p>
<h1>Code:</h1>
<pre><code>import os
from typing import List, Iterable, Dict
_TERMINATOR = "\0"
_PATH_KEY = "PATH"
_PATH_DELIM = ":"
Table = Dict[str, "Table"]
def _get_paths() -> List[str]:
return os.environ[_PATH_KEY].split(_PATH_DELIM)
def _find_filenames_in(paths: List[str]) -> Iterable[str]:
return (fname
for path in paths
for _, _, fnames in os.walk(path)
for fname in fnames)
def _add_string(table: Table, string: str) -> None:
term_string = string + _TERMINATOR
cur_level = table
for c in term_string:
if c not in cur_level:
cur_level[c] = {}
cur_level = cur_level[c]
def make_lookup_table_from(strings: Iterable[str]) -> Table:
table = {}
for string in strings:
_add_string(table, string)
return table
def make_lookup_table_from_path() -> Table:
paths = _get_paths()
fnames = _find_filenames_in(paths)
return make_lookup_table_from(fnames)
def _extract_strings(table: Table) -> Iterable[str]:
acc = []
def rec(cur_path: str, cur_level: Table):
for char, child in cur_level.items():
if char == _TERMINATOR:
acc.append(cur_path)
else:
rec(cur_path + char, child)
rec("", table)
return acc
def find_matching(table: Table, string: str) -> Iterable[str]:
cur_level = table
for c in string:
try:
cur_level = cur_level[c]
except KeyError:
return []
return [string + end for end in _extract_strings(cur_level)]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T19:37:11.423",
"Id": "485857",
"Score": "0",
"body": "How are you expecting to use this? Will the trie be built once or will you be building it before each call to `find_matching`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T19:43:36.040",
"Id": "485858",
"Score": "0",
"body": "@Peilonrayz The plan so far will be to have a call to `make_lookup_table_from_path` once when the shell is loaded, save the table in a variable outside of the main loop, then do lookups on the saved table (the more I write \"table\", the more I'm realizing that that's probably not the right word)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T19:45:19.470",
"Id": "485859",
"Score": "0",
"body": "I have yet to figure out how to listen unbuffered for a tab key easily though, or how to overwrite user input with the autocomplete suggestion without resorting to ANSII escape codes and such, so it may be a bit before I get to that point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T21:08:08.550",
"Id": "485862",
"Score": "1",
"body": "\"I have yet to figure out how to listen unbuffered for a tab key easily though.\" You may be interested in [this](https://github.com/Peilonrayz/alphabet_learner/blob/master/src/alphabet_learner/get_char.py) I think you'll have to deal with ANSII and/or Window's key codes regardless. When I was making my little application the hardest part was dealing with the text moving all over the place D:"
}
] |
[
{
"body": "<ol>\n<li><p>You can use <code>dict.setdefault</code> rather than conditionally modifying the trie.\nThis has the benefit of only looking up the key once as opposed to a maximum of 3 times with your current code.</p>\n</li>\n<li><p>I'm not a fan of your terminology:</p>\n<ul>\n<li><code>table</code> makes me think 2d array rather than a tree.</li>\n<li>I'd prefer <code>node</code> to <code>cur_level</code>.</li>\n<li>What does <code>c</code> mean?</li>\n<li>Why not just call it <code>_add_value</code>?</li>\n</ul>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def _add_value(root: Table, string: str) -> None:\n node = root\n for char in string + _TERMINATOR:\n node = node.setdefault(char, {})\n</code></pre>\n<ol start=\"3\">\n<li><p>In <code>_extract_strings</code> I'd move <code>acc = []</code> after the function definition so the code isn't all over the place.</p>\n</li>\n<li>\n<blockquote>\n<p>In the recursive function, I'm using strings to keep track of the word "so far", and passing concatenated copies to the children for them to use. I was originally using lists so I could just append without creating a new object each time, but sharing the mutable list between recurses proved to be problematic. I'm also returning only endings from the lookup function then reconstructing the full word in find_matching. This necessitates string + for every found string though, which isn't great.</p>\n</blockquote>\n<p>When getting one value your code runs in <span class=\"math-container\">\\$O(l^2)\\$</span> where <span class=\"math-container\">\\$l\\$</span> is the maximum length of a string.\nThis is because each <code>cur_path + char</code> is an <span class=\"math-container\">\\$O(l)\\$</span> operation and you do it <span class=\"math-container\">\\$l\\$</span> times.</p>\n<p>With the current algorithm I'd suggest following an 'eh, screw it' approach and just be happy that it's sufficiently fast. As manually dealing with the stack is <em>no fun</em>.</p>\n<p>Personally I'm not a fan of <code>acc.append</code>, I'd instead use <code>yield</code> and <code>yield from</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _extract_strings(table: Table) -> Iterator[str]:\n def rec(cur_path: str, cur_level: Table):\n for char, child in cur_level.items():\n if char == _TERMINATOR:\n yield cur_path\n else:\n yield from rec(cur_path + char, child)\n return rec("", table)\n</code></pre>\n</li>\n<li>\n<blockquote>\n<p>The lookup function _extract_strings makes use of recursion, because this seemed like a painful problem to solve iteratively. If I'm missing an obvious alternate way, I'd appreciate any tips there.</p>\n</blockquote>\n<p>Whilst manually building the stack is possible, it's not super simple. Given that the trie is unlikely to exceed Python's 1000 stack limit you can probably ignore this.<br />\nAs touched on before when building the stack we could easily build the result at the same time, changing the <span class=\"math-container\">\\$O(l^2)\\$</span> performance to just <span class=\"math-container\">\\$O(l)\\$</span>.</p>\n<p>However as you should be able to see this is an abomination.\nI don't think anyone wants to maintain this.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def _extract_strings(table: Table) -> Iterator[str]:\n stack = [iter(table.items())]\n stack_value = []\n while stack:\n try:\n key, value = next(stack[-1])\n except StopIteration:\n stack.pop()\n if stack_value:\n stack_value.pop()\n continue\n if key == '\\0':\n yield ''.join(stack_value)\n stack_value.append(key)\n stack.append(iter(value.items()))\n\n\ntable = {\n 'b': {'a': {'r': {'\\0': {}}, 'z': {'\\0': {}}}},\n 'f': {'o': {'o': {'\\0': {}}}},\n}\nfor path in _extract_strings(table):\n print(path)\n</code></pre>\n</li>\n<li><p>I'm not a fan of a lot of your empty lines. They seem random and not needed.</p>\n</li>\n<li><p>The trie would be better described in a class. A class, even with no sugar, would make your code easier to understand, as then you don't have to think "what is <code>_add_string</code>" and "how do I handle <code>table</code>".<br />\n<a href=\"https://codereview.stackexchange.com/search?q=user%3A42401+trie\">I've written a few tries over the years</a>, they may help if you decide to make it a class.</p>\n<pre class=\"lang-py prettyprint-override\"><code>trie = Trie()\ntrie.add('foo')\ntrie.add('bar')\ntrie.add('baz')\n# Could use the following to add instead if you need a value\n# trie['foo'] = ???\n\nkey = 'ba'\nfor value in trie[key]:\n print(key + value)\n</code></pre>\n</li>\n<li>\n<blockquote>\n<p>The plan so far will be to have a call to <code>make_lookup_table_from_path</code> once when the shell is loaded, save the table in a variable outside of the main loop, then do lookups on the saved table (the more I write "table", the more I'm realizing that that's probably not the right word).</p>\n</blockquote>\n<p>Using a Trie here is a good solution.<br />\nIf you were rebuilding the table each time you call <code>find_matching</code> then a simple <code>str.startswith</code> would probably out perform this by miles.</p>\n</li>\n</ol>\n<h1>Overall</h1>\n<p>Your code's style seems a little odd. But otherwise it's good. I'd suggest using a class most of all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T20:51:46.717",
"Id": "485861",
"Score": "0",
"body": "Thank you. This is good stuff. And ya, I get a lot of comments about my code style. I'm slowly changing to less whitespace."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T20:46:29.337",
"Id": "248104",
"ParentId": "248100",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "248104",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T18:16:37.053",
"Id": "248100",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"autocomplete"
],
"Title": "A simple word autocompleter meant for use in a shell"
}
|
248100
|
<p><strong>Ask user to input 10 integers and then print the largest odd number that was entered. If no odd number was entered, print a message to that effect.</strong></p>
<p>I've been trying to solve this problem with python and I think I've figured out a way that covers all the cases that are possible given the mathematical definition of an odd number. In order to be sure, I would like to check if my code is correct given your own criteria.</p>
<pre><code>counter = 0
odd = []
while counter < 10:
x = int(input("Enter a number: "))
if abs(x)%2 != 0:
odd.append(x)
counter += 1
if len(odd) == 0:
print("No odd number was entered")
else:
print("The largest odd number is:", max(odd))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T02:01:20.817",
"Id": "485873",
"Score": "2",
"body": "Doesn't even run, has multiple indentation errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T08:15:01.863",
"Id": "485907",
"Score": "13",
"body": "Why is storing all numbers required ? Keep only a `max_odd` and update it if a bigger odd number appears."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T09:25:53.497",
"Id": "485914",
"Score": "1",
"body": "@anki I was thinking the EXACT same thing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T10:46:17.727",
"Id": "485921",
"Score": "1",
"body": "it does run, at least it does in my IDLE. Thanks @anki, I didn't know how to tell python to store only the maximum odd while running."
}
] |
[
{
"body": "<p>For your current program we can improve a couple things:</p>\n<ol>\n<li>Rename <code>odd</code> to <code>odds</code> (since it is a <code>list</code>).</li>\n<li>Use <code>not odds</code> instead of <code>len(odds) == 0</code> (see <a href=\"https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty\">How do I check if a list is empty?</a> for a reason as to why this is preferred).</li>\n<li>Delete <code>counter</code>. Since we only use <code>counter</code> in the <code>while</code> condition, we can actually replace the whole <code>while</code> with <code>for _ in range(10)</code>.</li>\n<li>Follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP 8</a>. For example, using 4 spaces for each indentation level.</li>\n</ol>\n<p>Factoring in all these changes, we get:</p>\n<pre><code>odds = []\n\nfor _ in range(10):\n x = int(input("Enter a number: "))\n if abs(x) % 2 != 0:\n odds.append(x)\n\nif not odds:\n print("No odd number was entered")\nelse:\n print("The largest odd number is:", max(odds))\n</code></pre>\n<p>But we can also improve the efficiency of this program. Right now we keep track of all odd numbers, before choosing the max. This means that the space complexity is O(N). We can change this to O(1) by keeping track of the largest odd number like so:</p>\n<pre><code>max_odd = None\n\nfor _ in range(10):\n x = int(input("Enter a number: "))\n\n if abs(x) % 2 != 0:\n max_odd = x if max_odd is None else max(max_odd, x)\n\nif max_odd is None:\n print("No odd number was entered")\nelse:\n print("The largest odd number is: ", max_odd)\n</code></pre>\n<p>Note that we use <code>None</code> to signify that no odd number has been entered so far, in which case upon an odd number being entered we set <code>max_odd</code> to <code>x</code> directly. Otherwise, we set <code>max_odd</code> to <code>max(max_odd, x)</code>.</p>\n<p>For this type of program you will not notice the increase in efficiency due to reducing the space complexity. But learning to recognize where these reductions are possible will allow you to see the same patterns in programs where it does matter.</p>\n<p>There is finally one more thing you can do. If you want to allow the program to keep accumulating numbers in the event that a <code>str</code> is accidentally typed which cannot be parsed as a number (such as <code>""</code>), we can use a <code>try</code> / <code>except</code> wrapped in a <code>while</code> like so:</p>\n<pre><code>while True:\n try:\n x = int(input("Enter a number: "))\n break\n except ValueError:\n continue\n</code></pre>\n<p>This would replace:</p>\n<pre><code>x = int(input("Enter a number: "))\n</code></pre>\n<p>in the original code. This would keep prompting the user to type a <code>str</code> that is parsable as an <code>int</code> until they do. Since this is all happening in the same iteration of the <code>for</code>, the count of numbers they get to type (10 in our case) would not be reduced.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T01:29:22.960",
"Id": "485870",
"Score": "4",
"body": "The second-to-last code block could be written without the `x_is_valid` variable. The are two approaches: (1) change loop condition to `while True:` and `x_is_valid = True` to `break`; (2) use the `counter` variable in the original solution and replace `x_is_valid = True` with `counter += 1`. The second approach also avoids the need of the inner loop entirely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T01:39:10.357",
"Id": "485871",
"Score": "0",
"body": "@GZO Great catch, edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T10:49:45.927",
"Id": "485923",
"Score": "0",
"body": "Thanks @GZO for all your contribution to my program, you've really enlightened me. I would like to know why you consider more optimal to use for loops instead of while loops? I'm certainly just a beginner and still don't get given which situations one is more convenient than the other..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T11:52:42.253",
"Id": "485926",
"Score": "3",
"body": "@NeisySofíaVadori A common pattern you'll find in programming is that you have a collection of things (whether it's a list, a range of numbers, etc); and that you want to loop over each item in it in order. This is so common that `for` loops are standard to let you do this faster, rather than having to write all the boilerplate logic to define an iteration variable, ensure it is within the range, and then increment / move that iteration variable at the end of the loop: instead, you're able to write all of this in a single line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T11:54:49.533",
"Id": "485927",
"Score": "2",
"body": "`for` loops are used more over an iterator (list, dict, set, etc) or when you have some constant amount of repeat times. `while` loops are used when you know only a stop/continue condition. @NeisySofíaVadori"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T17:00:49.520",
"Id": "485964",
"Score": "0",
"body": "Why `max_odd = x if max_odd is None else max(max_odd, x)` instead of `max_odd = max(max_odd, x)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T17:04:23.510",
"Id": "485965",
"Score": "1",
"body": "@Ben In Python 2 that would have worked, but in Python 3 `max(None, x)` (the very first iteration) raises `TypeError`. See https://stackoverflow.com/questions/8961005/comparing-none-with-built-in-types-using-arithmetic-operators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T14:02:28.243",
"Id": "486044",
"Score": "0",
"body": "@NeisySofíaVadori If the loop simply iterates through a range (e.g., 0 to n), using a `for`-loop provides better readability and performance **in Python**. However, if you need more flexibility, e.g. increase `counter` conditionally like I mentioned in my second approach, then a `while` loop would fit the need."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T00:14:12.030",
"Id": "248113",
"ParentId": "248102",
"Score": "19"
}
},
{
"body": "<p>Adding to the previous review:</p>\n<ul>\n<li>When <code>x</code> is an integer, <code>abs(x) % 2</code> is equivalent to <code>x % 2</code> in Python. The output of the modulo operator <code>%</code> has the same sign as the second operand.</li>\n<li>When running code outside a method / class, it is a good practice to put the code inside a <em>main guard</em>. See <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">here</a> for more explanation.</li>\n</ul>\n<p>In Python 3.8, the code can be shortened using the assignment operator <code>:=</code> together with <code>max</code> function.</p>\n<pre><code>if __name__ == "__main__":\n # Number generator\n num_gen = (o for _ in range(10) if (o := int(input("Enter a number: "))) % 2 != 0)\n max_odd = max(num_gen, default=None)\n if max_odd is None:\n print("No odd number was entered")\n else:\n print(f"The largest odd number is: {max_odd}")\n</code></pre>\n<p>Wrapping <code>int(input("Enter a number: "))</code> into a function provides better readability:</p>\n<pre><code>def read_input() -> int:\n return int(input("Enter a number: "))\n\nif __name__ == "__main__":\n num_gen = (o for _ in range(10) if (o := read_input()) % 2 != 0)\n max_odd = max(num_gen, default=None)\n if max_odd is None:\n print("No odd number was entered")\n else:\n print(f"The largest odd number is: {max_odd}")\n</code></pre>\n<p>Another variant that handles invalid user inputs is as follows:</p>\n<pre><code>def read_input() -> int:\n while True:\n try:\n return int(input("Enter a number: "))\n except ValueError:\n continue\n\nif __name__ == "__main__":\n try:\n max_odd = max(o for _ in range(10) if (o := read_input()) % 2 != 0)\n print(f"The largest odd number is: {max_odd}")\n except ValueError:\n # Since read_input() no longer raises ValueError, the except\n # statement here only handles the cases where max() gets no inputs\n print("No odd number was entered")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T07:24:22.043",
"Id": "485904",
"Score": "8",
"body": "Shorter isn't necessarily better. I certainly need more time to read this code to understand what it does, compared to Mario's or the OP's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T17:54:29.110",
"Id": "485966",
"Score": "2",
"body": "I'd use `max(..., default=None)` and an `if max_odd is not None:` `else:` statement, instead of the try-except, since a `ValueError` could come from a non-integer input and doesn't truly mean no odd value was entered."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T13:21:41.603",
"Id": "486036",
"Score": "0",
"body": "@AJNeufeld Thanks. I've updated my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T13:30:27.927",
"Id": "486043",
"Score": "0",
"body": "@FlorianF The generator expression is a bit too long to comprehend. I've edited my post."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T01:58:17.083",
"Id": "248115",
"ParentId": "248102",
"Score": "6"
}
},
{
"body": "<p>May I ask what programming language did you practice before python?<br />\nI want to mention a one-liner for this:</p>\n<pre><code>max(l,key=lambda x:(x%2,x))\n</code></pre>\n<p>assuming you already have <code>l</code> somehow inputed, like</p>\n<pre><code>s='Enter a number: '\nl=[int(input(s)) for i in range(10)]\n</code></pre>\n<hr />\n<p>How does the code work? It looks for maximum of <code>key(x)</code> for <code>x</code> in <code>l</code> and returns such <code>x</code>. Key here is the lambda function that returns tuple <code>(1,x)</code> for odd <code>x</code> and <code>(0,x)</code> for even <code>x</code>. Tuples are compared left to right, e.g. <code>(1,x)>(0,y)</code> for every <code>x</code> and <code>y</code>. So we are just saying "give me the maximum of <code>l</code>, assuming that an odd number is always larger than an even number".</p>\n<p>So all program will look like</p>\n<pre><code>s='Enter a number: '\nl=[int(input(s)) for i in range(10)]\nm=max(l,key=lambda x:(x%2,x))\nif m%2:\n print('The largest odd number is: %d'%m)\nelse: #the greatest is even, therefore no odd numbers\n print('No odd number was entered')\n</code></pre>\n<p>Short, nice and easy, as python.</p>\n<p>But I agree that a try-except block around <code>int(input())</code> form the accepted answer is useful, along with no pre-storing the entire list of odd values.</p>\n<p>I only wanted to demonstrate the paradigm of functional programming in python, when you just tell python 'I want that done (e.g. a maximum value)' and it does it for you, you don't need to explain how should it do it.</p>\n<p>Thanks for reading.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T10:52:46.590",
"Id": "485924",
"Score": "0",
"body": "Thanks @AlexeyBurdin, I found your code really elegant and I definetely appreciate that. Regarding your question, I started learning python just some weeks ago and is the first programing language I'm learning, but I'm studing physics so my math knowledge definitely helps."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T05:56:40.493",
"Id": "248122",
"ParentId": "248102",
"Score": "3"
}
},
{
"body": "<p>I'll try to build on the last suggestion of the accepted answer.</p>\n<pre><code>while True:\n try:\n x = int(input("Enter a number: "))\n break\n except ValueError:\n continue\n</code></pre>\n<p>I definitely endorse this suggestion, it allows your program to handle invalid input gracefully instead of just crashing.</p>\n<p>However, it creates an usability problem. The user who just typoed a letter into a number probably did not notice it. They'll think they got the intended number in, proceed with the next, and then get confused at the end, when they <em>think</em> they got all numbers in, but the computer is still asking for the next one.</p>\n<p>Better to give them feedback:</p>\n<pre><code>while True:\n try:\n x = int(input("Enter a number: "))\n break\n except ValueError:\n print("Invalid number will be ignored.")\n continue\n</code></pre>\n<p>... or even better, print their typoed number back at them:</p>\n<pre><code>while True:\n try:\n inputString = input("Enter a number: ")\n x = int(inputString)\n break\n except ValueError:\n print("Invalid number will be ignored: {}".format(inputString))\n continue\n</code></pre>\n<p>I would also consider keeping the full list of valid numbers entered, not just odd ones, and printing them all back at the user before the result, to give them a last chance to spot typos. They can, after all, have mistyped a valid but unintended number. Note that this would increase memory usage, and some would consider it over-communication.</p>\n<pre><code>print("Numbers provided are: {}".format(all_valid_numbers_inputted))\nif not odds:\n print("No odd number was entered")\nelse:\n print("The largest odd number is:", max(odds))\n</code></pre>\n<p>If you do this, the next step would be to get rid of the "odds" variable, and figure out the largest odd directly from the full list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T14:36:56.633",
"Id": "248146",
"ParentId": "248102",
"Score": "3"
}
},
{
"body": "<p>The key point here: each step in the process does just one simple thing. You\nbuild programs that way -- one incremental, tightly defined step at a time. Don't\nmix everything in a jumble -- e.g. a loop where we interact with a user while also making conversions and calculations needed later.</p>\n<pre><code>def as_int(s):\n try:\n return int(s)\n except Exception:\n return 0\n\nN = 3\nMSG = 'Enter number: '\n\nreplies = [input(MSG) for _ in range(N)] # Interact.\nnums = [as_int(r) for r in replies] # Convert.\nodds = [n for n in nums if n % 2] # Compute.\n\nif odds: # Report.\n print(max(odds))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T08:40:59.683",
"Id": "486517",
"Score": "0",
"body": "Silently replacing a typo with a zero is no good. And you can't even fix it by adding a loop to `as_int`, since at that point it's already too late, all input has been done. That's a real *downside* of how you split the steps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T14:54:30.257",
"Id": "486563",
"Score": "0",
"body": "@superbrain Sure, in some contexts; in others, not so much. If the input-stage needs typo fixing/validation, it can be added easily, during that stage. But those are details the OP can sort out. My general point stands."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T07:44:24.693",
"Id": "486648",
"Score": "0",
"body": "`as_int` is an absolute no-go. input validation has to be in the interact stage. any silent and hidden assumption what-the-user-may-want is a no-go. that's what exceptions are for - unless fixed in the interact stage. if you cannot control the interact stage you shall implement an explicit validation stage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-26T14:36:11.223",
"Id": "486678",
"Score": "0",
"body": "@stefan You are mistaken. First, neither of us know the purpose of the OP's larger program -- input validation needs might be irrelevant or unusual. Second, input validation can easily happen during the input stage: wrap the `input()` call in a function and do whatever is necessary. But that validation need not necessarily involve conversion of string to integer. It *could* involve such conversion, but my answer's main point is aimed elsewhere -- namely, the correct and important lesson of organizing your programs into discrete, readily understood steps."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T05:23:16.843",
"Id": "248396",
"ParentId": "248102",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "248113",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T20:28:12.697",
"Id": "248102",
"Score": "8",
"Tags": [
"python",
"beginner"
],
"Title": "Largest odd number"
}
|
248102
|
<p>Currently Rubberduck VBA files all the VBProject VBComponents in that do not have a Folder Annotation in a Folder named after the VBProject. It can be time consuming to manually organize the components for the first time and a inconvenient to add annotations to every Worksheet, Userform, Class, ...ect. When ran my code will organize any unfiled component by <code>ProjectName.ComponentType</code>.</p>
<p><strong>Before</strong></p>
<p><img src="https://i.stack.imgur.com/7RKIi.png" alt="Rubberduck Code Explorer - No Folders" /></p>
<p><strong>After</strong></p>
<p><img src="https://i.stack.imgur.com/d8f9M.png" alt="Rubberduck Code Explorer - With Default Folder Annotations" /></p>
<p>You will need to add a reference to the <code>Microsoft Visual Basic for Applications Extensibility 5.3</code> and from file options check "Trust access to VBA project object model".</p>
<p><img src="https://i.stack.imgur.com/zmXtE.png" alt="Programmatic Access" /></p>
<pre><code>Private Sub AddDefaultFolderAnnotationsToVBComponents()
Dim Component As VBComponent
Dim Project As VBProject
Select Case Application.Name
Case "Microsoft Access", "Microsoft Word"
Set Project = IIf(True, Application, 0).VBE.ActiveVBProject
Case "Microsoft Excel"
Set Project = IIf(True, Application, 0).ActiveWorkbook.VBProject
Case "Microsoft PowerPoint"
Set Project = IIf(True, Application, 0).VBE.VBProjects(1)
End Select
Dim FolderName As String
Dim HasFolder As Boolean
For Each Component In Project.VBComponents
With Component.CodeModule
If .CountOfLines = 0 Then
HasFolder = False
Else
HasFolder = InStr(.Lines(1, .CountOfLines), Chr(39) & "@Folder")
End If
End With
If Not HasFolder Then
Select Case Component.Type
Case vbext_ComponentType.vbext_ct_StdModule
FolderName = Project.Name & ".Modules"
Case vbext_ComponentType.vbext_ct_ClassModule
FolderName = Project.Name & ".Classes"
Case vbext_ComponentType.vbext_ct_MSForm
FolderName = Project.Name & ".Forms"
Case vbext_ComponentType.vbext_ct_ActiveXDesigner
FolderName = Project.Name & ".Designers"
Case vbext_ComponentType.vbext_ct_Document
FolderName = Project.Name & ".Documents"
End Select
Component.CodeModule.InsertLines 1, Chr(39) & "@Folder(""" & FolderName & """)"
End If
Next
End Sub
</code></pre>
<p>Note: I purposely kept all the functionality in a single procedure for portability.</p>
<p>Kudos to the Rubberduck team the latest version <a href="https://rubberduckvba.com/" rel="nofollow noreferrer">Rubberduck VBA v2.5</a> is a C# WPF that follows the MVVM pattern to the letter!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T02:17:51.577",
"Id": "485996",
"Score": "1",
"body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/111999/discussion-on-question-by-tinman-add-default-rubberduck-vba-folder-annotation-to)."
}
] |
[
{
"body": "<blockquote>\n<pre><code>HasFolder = InStr(.Lines(1, .CountOfLines), Chr(39) & "@Folder")\n</code></pre>\n</blockquote>\n<p>That condition can <em>technically</em> be <code>True</code> in modules that don't <em>actually</em> have the annotation; a <code>@Folder</code> Rubberduck annotation is only valid in a module's <em>declarations section</em>, so there's no need to grab the module content any further than <code>.CountOfDeclarationLines</code> - if the module is nearing the 10K lines capacity, using this instead of <code>.CountOfLines</code> could make a significant difference in the size of the string being passed to the <code>InStr</code> function.</p>\n<blockquote>\n<pre><code>Select Case Component.Type\n Case vbext_ComponentType.vbext_ct_StdModule\n FolderName = Project.Name & ".Modules"\n Case vbext_ComponentType.vbext_ct_ClassModule\n FolderName = Project.Name & ".Classes"\n Case vbext_ComponentType.vbext_ct_MSForm\n FolderName = Project.Name & ".Forms"\n Case vbext_ComponentType.vbext_ct_ActiveXDesigner\n FolderName = Project.Name & ".Designers"\n Case vbext_ComponentType.vbext_ct_Document\n FolderName = Project.Name & ".Documents"\nEnd Select\n</code></pre>\n</blockquote>\n<p>I wouldn't repeat the concatenation here - just work out the last part of the name per the component type, and <em>then</em> concatenate with <code>Project.Name & "."</code> (I'd pull the separator dot out of the <code>Case</code> blocks as well) - and then I might give it a bit of breathing room, but that's more subjective:</p>\n<pre><code> Select Case Component.Type\n Case vbext_ComponentType.vbext_ct_StdModule\n ChildFolderName = "Modules"\n\n Case vbext_ComponentType.vbext_ct_ClassModule\n ChildFolderName = "Classes"\n\n Case vbext_ComponentType.vbext_ct_MSForm\n ChildFolderName = "Forms"\n\n Case vbext_ComponentType.vbext_ct_ActiveXDesigner\n ChildFolderName = "Designers" 'note: not supported in VBA\n\n Case vbext_ComponentType.vbext_ct_Document\n ChildFolderName = "Documents"\n\n End Select\n FolderName = Project.Name & "." & ChildFolderName\n</code></pre>\n<p>I like the <code>@Folder("Parent.Child")</code> syntax and I see that's what you're generating here:</p>\n<blockquote>\n<pre><code>Component.CodeModule.InsertLines 1, Chr(39) & "@Folder(""" & FolderName & """)"\n</code></pre>\n</blockquote>\n<p>Note that this would also be legal... and simpler to generate:</p>\n<pre><code>Component.CodeModule.InsertLines 1, "'@Folder " & FolderName\n</code></pre>\n<p>Obviously if you prefer the parenthesized syntax (either works, it's really just down to personal preference) like I do then by all means keep it, but Rubberduck's new <em>Move to Folder</em> command doesn't put the parentheses in. I'd probably have the single-quote <code>'</code> character spelled out, too, but I can see how a <code>'</code> might be harder than necessary to read in the middle of a bunch of <code>"</code> double quotes. On the other hand, defining a constant for it would remove the need to have the <code>"@Folder</code> string literal defined in multiple places:</p>\n<pre><code>Private Const RD_FOLDER_ANNOTATION As String = "'@Folder "\n\n...\n\nComponent.CodeModule.InsertLines 1, RD_FOLDER_ANNOTATION & FolderName\n</code></pre>\n<p>I have to mention that Rubberduck <em>deliberately</em> shoves all modules under the same default named-after-the-project folder (they can easily be sorted by component type in the <em>Code Explorer</em>), because we <strong>strongly</strong> believe grouping modules by component type is utterly useless and counter-productive: when I look at the code for a given functionality, I want to see all the code related to that functionality - and I couldn't care less about the component type of the code I'm looking at... it's mostly all class modules anyway.</p>\n<p>A <em>sane</em> way to organize the modules in a project, is by <em>functionality</em>: you want your <code>ThingView</code> user form in the same place as your <code>ThingModel</code> class and your <code>ThingPresenter</code> and the <code>Things</code> custom collection - that way when you're working on that <em>Thing</em>, you don't have to dig up the various pieces in an ever-growing list of components under some useless "Class Modules" folder.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T16:58:03.047",
"Id": "486244",
"Score": "0",
"body": "I really like the `ChildFolderName`, the extra white-space really cleans up the `Select Case`. I didn't not realize the parenthesis were optional. `Chr(39)` is the module that the `AddDefaultFolderAnnotationsToVBComponents` is in will not be skipped."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:36:29.360",
"Id": "486249",
"Score": "0",
"body": "I disagree about categorizing by type being useless. This is how MVC Bootstraps folder structure are typically organized `Project, Project.Views`, `Project-Models`, `Project.Controllers`. Recommended Websites layout are usually structured by `Root`, `Root.Css`, `Root.JS`,`Root.Php`...etc. Having a default filing system also makes it easier to re-organize your folders because you will not have all the documents without code-behind cluttering up the place. A drop down to change folder views would go along way to making your point"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:38:10.397",
"Id": "486250",
"Score": "1",
"body": "Eureka! Only checking the declaration portion would eliminate the need for `Chr(39)`!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T17:47:06.657",
"Id": "486252",
"Score": "0",
"body": "What do you think about allowing multiple folder annotations? This would allow us to associate worksheets with more than one set of files."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:05:04.443",
"Id": "486255",
"Score": "1",
"body": "Multiple folder annotations would result in... source files showing up in multiple places in the code explorer? How should we handle this? As for MVC default namespaces/folders, it's not the same thing at all because namespaces *may or may not match/follow the folder structure* (although it would be recommended that they do), ...and there is no distinct folders for `Classes`, `Interfaces`, `Enums`, `Structs`, `Delegates`, ...nor should there be any! You'll also find various blog posts about whether the default MVC project structure is useful..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:11:24.667",
"Id": "486256",
"Score": "0",
"body": "...the conclusion I've drawn boils down to *use the default structure because otherwise you're going to be fighting VS... and you will want to avoid that*. But yes, perhaps a CE view matching the vanilla-VBE by-component (but still drill-down to member level) folders could be useful... I would just find it a bit sad I guess, if users mostly just picked that view over the fully-customizable one where their *actual* project structure can *really* pop out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:20:43.467",
"Id": "486258",
"Score": "0",
"body": "Hey Matt, the OP has added an \"ADDENDUM\". Not sure if you've seen it but I'll leave you to handle it however you think is best since you seem to be around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:24:39.017",
"Id": "486260",
"Score": "0",
"body": "From a purist standpoint, I agree with your arguments. But in practice, I will work on a project for 1 to 3 hours and never see it again. That is the main reason that I want to filter out the documents without code, instead of filing them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:33:47.367",
"Id": "486262",
"Score": "1",
"body": "@TinMan Peilonrayz is correct - including the updated code in the OP makes it kind of implicitly feel like the case is closed and no other input would be considered; that's why we encourage you to put the updated version in a new/follow-up \"question\" if you want additional feedback on the updated code. Basically we're all about the *review* and what good comes out of it - often the \"final\" result is never quite *final* anyway, ..for many of us anyway ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T18:38:42.033",
"Id": "486264",
"Score": "0",
"body": "You and @Peilonrayz are right. I know better. I might come back to this at a latter date. I don't like the fact that the code will not work on hidden projects."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-22T16:05:46.273",
"Id": "248280",
"ParentId": "248109",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "248280",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T22:04:13.373",
"Id": "248109",
"Score": "6",
"Tags": [
"vba",
"excel",
"rubberduck",
"ms-access",
"powerpoint"
],
"Title": "Add Default Rubberduck VBA Folder Annotation to VBProject.VBComponents"
}
|
248109
|
<p>A simple terminal blackjack game written in Python.
Follows basic blackjack rules: Blackjack pays 3 to 1, Hit, Stick, Double Down and Splits
Dealer hits until 17
Keeps track of some data
Wrote it for working on my object-oriented programming, i am recently new to coding, if anyone takes a look please comment could be done better, thank you.
<a href="https://github.com/jamucar/terminal-blackjack" rel="nofollow noreferrer">https://github.com/jamucar/terminal-blackjack</a></p>
<pre><code>#!/usr/bin/env python3
'''
Terminal Blackjack game with basic rules, bet, hit, stick, blackjack pays 3 to 2, double down and split your first hand.
'''
import random
import time
import os
import csv
import datetime
from functools import reduce
class Card:
def __init__(self, suit, value):
'''every card has a suit and value'''
self.suit = suit
self.value = value
def __repr__(self):
'''Oveloading the objects prit() function as if one card up one down'''
return(f"+---+ +---+\n|{self.suit} | |X X| \n| {self.value} | | X | \n| {self.suit}| |X X|\n+---+ +---+")
class Deck:
def __init__(self):
'''Creates a list of card obects for every suit and value'''
self.cards = 6 * [Card(s, v) for s in ["♣", "♠", "♦", "♥"] for v in
["A", "2", "3", "4", "5", "6", "7", "8", "9", "T", "J", "Q", "K"]]
def shuffle(self):
'''shuffle the card deck'''
if len(self.cards) > 1:
random.shuffle(self.cards)
def cards_left(self):
'''returns cards left in deck as int'''
return (len(self.cards))
def cards_in_deck(self):
'''displays cards left in string'''
return f'Cards in deck: {len(self.cards)}'
def deal(self):
'''removes a card from the deck'''
return self.cards.pop(0)
class Hand:
def __init__(self, dealer=False):
'''the hand inclues a list with the cards, and the hands value'''
self.dealer = dealer
self.cards = []
self.value = 0
self.bet = 0
def add_card(self, card):
'''adds a card to the hand'''
self.cards.append(card)
def calculate_value(self):
'''calculates the value of the hand'''
self.value = 0
has_ace = False
for card in self.cards:
if card.value.isnumeric():
self.value += int(card.value)
else:
if card.value == "A":
has_ace = True
self.value += 11
else:
self.value += 10
if has_ace and self.value > 21:
self.value -= 10
def get_cards(self):
return self.cards
def get_value(self):
'''calls calculate_value and returns the hand value'''
self.calculate_value()
return self.value
def display(self):
'''displays player cards and one of dealers cards'''
if self.dealer and len(self.cards) == 2:
print(self.cards[0])
else:
self.display_dealer()
def display_dealer(self):
'''Normal display for non hidden cards'''
for i in range(len(self.cards)):
print("+---+ ", end="")
print()
for i in range(len(self.cards)):
card = self.cards[i]
print("|{} | ".format(card.suit), end="")
print()
for i in range(len(self.cards)):
card = self.cards[i]
print("| {} | ".format(card.value), end="")
print()
for i in range(len(self.cards)):
card = self.cards[i]
print("| {}| ".format(card.suit), end="")
print()
for i in range(len(self.cards)):
print("+---+ ", end="")
print("\nValue:", self.get_value())
class Bankroll:
def __init__(self):
'''starts as 10000'''
#self.money = 10000
try:
with open('data.csv','r') as file:
reader = csv.reader(file)
csv_file = csv.DictReader(file)
rows = list(csv_file)
x = rows[len(rows)-1]
self.money = float(x.get("Bankroll"))
except FileNotFoundError:
with open('data.csv', 'w', newline = '') as file:
writer = csv.writer(file)
writer.writerow(["Date", "Hands_Won", "Hands_Lost", "Bankroll"])
writer.writerow([datetime.datetime.now(), 0, 0, 10000])
self.money = 10000
def close(self, w, l):
'''enters data in csv file, keeps track of bank'''
with open('data.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([datetime.datetime.now(), w, l, self.money])
def get_bankroll(self):
'''returns money left'''
return self.money
def win(self, x):
'''adds bet amount to bankroll if you win'''
self.money += x
def loose(self, x):
'''removes bet amount from bankroll if you loose'''
self.money -= x
def __repr__(self):
'''overloads bankroll print()'''
return (f"{self.money}")
class Bet:
def __init__(self):
'''minimum bet is 50$, it is your rent for sitting in the table'''
self.min = 50
self.amount = self.min
def get_bet(self):
'''returns bet amount'''
return self.amount
def create(self, x):
self.amount = x
return self.amount
def more(self):
'''adds min amount to current bet'''
self.amount += self.min
def double(self):
self.amount += self.amount
def display_bet(self):
print(f'Current bet is {self.amount}')
def __repr__(self):
return (f"{self.amount}")
class Game:
def __init__(self):
self.hands_won = 0
self.hands_lost = 0
self.bankroll = Bankroll()
def play(self):
'''Order of executions'''
self.clear()
self.init_deck()
playing = True
while playing:
self.split = False
self.player_hand = Hand()
self.dealer_hand = Hand(dealer=True)
self.bet = Bet()
self.print_game(open = True)
self.place_bet()
for i in range(2):
self.player_hand.add_card(self.deck.deal())
self.print_game()
self.dealer_hand.add_card(self.deck.deal())
self.print_game()
while True:
if self.calculate_split():
self.split_hand()
else:
self.hit_stick_double(self.bet, self.player_hand)
self.dealer_turn()
self.get_results()
break
again = input("Play Again? [Y/N] ")
while again.lower() not in ["y", "n"]:
again = input("Please enter Y or N ")
if again.lower() == "n":
self.close()
playing = False
def hit_stick_double(self, bet, hand, hit = False):
while hand.get_value() < 21:
if hit:
choice = self.choice(h = True)
if choice in ['hit', 'h']:
hand.add_card(self.deck.deal())
self.print_game()
else:
self.print_game()
break
else:
choice = self.choice()
if choice in ['hit', 'h']:
hit = True
hand.add_card(self.deck.deal())
self.print_game()
elif choice in ["d", "double"]:
hand.add_card(self.deck.deal())
bet.double()
self.print_game()
break
else:
self.print_game()
break
def split_hand(self):
'''creates two new hands'''
choice = self.choice(s = True)
if choice in ['y', 'yes']:
self.split = True
cards = self.player_hand.get_cards()
self.hand_1 = Hand()
self.bet_1 = Bet()
self.hand_1.add_card(card = cards[0])
self.bet_1.create(self.bet.get_bet())
self.hand_2 = Hand()
self.bet_2 = Bet()
self.hand_2.add_card(card = cards[1])
self.bet_2.create(self.bet.get_bet())
self.print_game()
self.hand_1.add_card(self.deck.deal())
self.hand_2.add_card(self.deck.deal())
self.print_game()
self.hit_stick_double(self.bet_1, self.hand_1)
self.hit_stick_double(self.bet_2, self.hand_2)
else:
self.hit_stick_double(self.bet, self.player_hand)
#
def choice(self, s = False, h = False):
if s:
print ("You can split your hand!")
choice = input("Do you want to split? [Yes / No] ").lower()
while choice not in ["y", "n", "Yes", "No"]:
choice = input("Please enter 'yes', 'no' or (or Y / N ) ").lower()
return choice
if h:
choice = input("Please choose [Hit / Stick ] ").lower()
while choice not in ["h", "s", "hit", "stick"]:
choice = input("Please enter 'hit' or 'stick' (or H/S) ").lower()
return choice
else:
choice = input("Please choose [Hit / Stick / Double] ").lower()
while choice not in ["h", "s", "d", "hit", "stick", "double"]:
choice = input("Please enter 'hit' , 'stick' or 'double' (or H/S/D) ").lower()
return choice
def clear(self):
'''Clearing for os system'''
# windows
if os.name == 'nt':
_ = os.system('cls')
# mac and linux
else:
_ = os.system('clear')
def init_deck(self):
'''initialices the deck'''
self.deck = Deck()
self.deck.shuffle()
print("Shuffling deck")
for i in range(int((self.deck.cards_left()) / 6)):
time.sleep(0.02)
x = "/"
print(i*x, end="\r")
def place_bet(self):
'''Asks the player if he wants the minimum bet or he wants to raise,
will raise on 50 dollar intervals,
will keep asking until he settles for ammount or reaches table limit which is 1000'''
money = self.bet.get_bet()
while money < 1000:
self.print_game()
print(f"Your bankroll is {self.bankroll} $")
self.bet.display_bet()
choice = input("Please choose [Raise or Stay] ").lower()
while choice not in ["r", "s", "raise", "stay"]:
choice = input("Please enter 'raise' or 'stay' (orR/S) ").lower()
if choice in ['raise', 'r']:
self.bet.more()
else:
break
def calculate_split(self):
'''calculates if split is possible'''
cards = self.player_hand.get_cards()
if cards[0].value == cards[1].value:
return True
def dealer_turn(self):
'''Dealer allways hits untill 17'''
self.print_game(dealer = True)
while self.dealer_hand.get_value() < 17:
self.dealer_hand.add_card(self.deck.deal())
self.print_game(dealer = True)
if self.player_is_over(dealer = True):
print("Dealer Bust!")
continue
def get_results(self):
'''
Displays the results, if players hand value is bellow and closer to 21 than the dealers he wins, and adds bet to baknroll
else if values are equal, as long as its bellow 21, its a tie, and you keep your bet.
else if dealer goes over and you dont, you win and add bet to bankroll.
else if both go over or any other condition, you loose the bet, like in casino
'''
if self.split:
dealer_hand_value = self.dealer_hand.get_value()
values = [[self.bet_1.get_bet() , self.bet_2.get_bet()] , [self.hand_1.get_value(), self.hand_2.get_value()]]
self.print_game()
self.get_winner(dealer_hand_value, values)
else:
player_hand_value = self.player_hand.get_value()
dealer_hand_value = self.dealer_hand.get_value()
bet = self.bet.get_bet()
values =[[bet],[player_hand_value]]
self.get_winner(dealer_hand_value, values)
def get_winner(self, dealer_hand_value, values):
'''analize who the winner is and money won or lost, works for split hand and normal hand'''
self.print_game(dealer = True)
print("Final Results:" )
for i in range(len(values[1])):
print("Hand:", i+1)
if values[1][i] == 21 and dealer_hand_value != 21:
print ("You Win")
print ("Blackjack pays 3 to 2")
print (f'collect your {(values[0][i] * 3) / 2}')
self.hands_won += 1
self.bankroll.win((values[0][i] * 3) / 2)
elif (values[1][i] < 21) and (values[1][i] > dealer_hand_value):
print("You Win!")
print(f"collect your {values[0][i]} $")
self.bankroll.win(values[0][i])
self.hands_won += 1
elif self.player_is_over(dealer = True) and values[1][i] <= 21:
print("You Win, Dealer Bust!")
print(f"collect your {values[0][i]} $")
self.bankroll.win(values[0][i])
self.hands_won += 1
elif (values[1][i] == dealer_hand_value) and (values[1][i] <= 21):
print("Tie!")
else:
print("Dealer Wins!")
print (f"You loose {values[0][i]} $")
self.bankroll.loose(values[0][i])
self.hands_lost += 1
print(f"Your bankroll is {self.bankroll} $")
game_over = True
def print_game(self, dealer = False, open = False):
'''
Prints the game, if dealer is false, one of his card is hidden
if dealer is true he reaveals all his cards_in_deck
the terminal is renewed everytime the function is called.
'''
time.sleep(0.5)
self.clear()
width, height = os.get_terminal_size()
# print_header()
self.header()
self.dealer = dealer
print("\n---DEALER---")
self.dealer_hand.display_dealer() if self.dealer else self.dealer_hand.display()
if open and self.deck.cards_left() < 18:
self.init_deck()
else:
print("/"* self.deck.cards_left())
print("\n---PLAYER---")
if self.split:
print("First Hand")
self.hand_1.display()
print ('*'* self.bet_1.get_bet())
print("Second Hand")
self.hand_2.display()
print ('*'* self.bet_2.get_bet())
else:
self.player_hand.display()
self.bet.display_bet()
print("*"* self.bet.get_bet())
def player_is_over(self, dealer = False):
'''Check if dealer or player have busted'''
self.dealer = dealer
if self.dealer:
return self.dealer_hand.get_value() > 21
return self.player_hand.get_value() > 21
def close(self):
'''enters data in csv file, keeps track of bank'''
self.clear()
self.header()
print("Thanks for playing!")
with open('data.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([datetime.datetime.now(), self.hands_won, self.hands_lost, self.bankroll])
with open('data.csv', 'r') as file:
reader = csv.reader(file)
csv_file = csv.DictReader(file)
rows = list(csv_file)
wins = []
loose = []
for i in rows:
wins.append(int(i.get("Hands_Won")))
loose.append(int(i.get("Hands_Lost")))
total_wins = reduce(lambda x, y: x + y, wins)
total_loose = reduce(lambda x, y: x + y, loose)
hands_played = total_wins + total_loose
win_percent = int((total_wins / hands_played) * 100)
loose_percent = int((total_loose / hands_played) * 100)
print (f"You ar winning {win_percent}% of hands")
print (f"You are loosing {loose_percent}% of hands")
average_hand = round((abs(10000 - self.bankroll.get_bankroll())) / hands_played, 2)
print (f"You are winning an average of {average_hand}$ per hand") if self.bankroll.get_bankroll() >= 10000 \
else print (f"You are loosing an average of {average_hand}$ per hand")
print (f"Your bankroll is {self.bankroll}$")
def header(self):
width, height = os.get_terminal_size()
print("#" * width)
name = "Natural 21"
m = " " * (int(width/2) - len(name))
print(m + name + m)
print("#" * width)
if __name__ == "__main__":
g = Game()
try:
g.play()
except (KeyboardInterrupt, SystemExit):
g.close()
</code></pre>
|
[] |
[
{
"body": "<p><strong>Logic 1</strong></p>\n<pre><code>def shuffle(self):\n '''shuffle the card deck'''\n if len(self.cards) > 1:\n random.shuffle(self.cards)\n</code></pre>\n<p>The <code>len</code> check is unnecessary. <code>shuffle</code> will not crash on a list with 0 or 1 elements in it.</p>\n<p><strong>Logic 2</strong></p>\n<pre><code>if has_ace and self.value > 21:\n self.value -= 10\n</code></pre>\n<p>What if you have more than one Ace in hand? Can each of them count as <code>1</code> or just the first one? I think you have a logical error here.</p>\n<p><strong>Code 1</strong></p>\n<pre><code>def get_value(self):\n '''calls calculate_value and returns the hand value'''\n self.calculate_value()\n return self.value\n</code></pre>\n<p>You always calculate the value before returning it, which I think is a good thing.</p>\n<p>But that also means there is no use storing the value in the hand's <code>this.value</code> . You should rather just return the calculated value from the <code>calculate_value()</code> function without storing it in <code>this.value</code>.</p>\n<p>Then you also don't need both functions <code>calculate_value()</code> and <code>get_value()</code>, since <code>get_value()</code> just returns <code>calculate_value()</code>.</p>\n<p><strong>Code improvement 1</strong></p>\n<pre><code> for i in range(len(self.cards)):\n print("+---+ ", end="")\n</code></pre>\n<p>Since you're not using the index nor the card in this loop, you can just print a long string directly like this:</p>\n<pre><code>print("+---+ " * len(self.cards), end="")\n</code></pre>\n<p><strong>Code improvement 2</strong></p>\n<pre><code> for i in range(len(self.cards)):\n card = self.cards[i]\n print("|{} | ".format(card.suit), end="")\n</code></pre>\n<p>You can iterate over the cards directly like this</p>\n<pre><code>for card in self.cards:\n print("|{} | ".format(card.suit), end="")\n</code></pre>\n<p><strong>Naming 1</strong></p>\n<pre><code>def get_bet(self):\n '''returns bet amount'''\n return self.amount\n</code></pre>\n<p>Getter methods usually are named like the variable they are getting, so you should either change the function to <code>def get_amount(self):</code> or change the <code>amount</code>variable to be named <code>bet</code>. But since the class is named <code>Bet</code>, it's not a good idea to have a variable by the same name inside the class, so change the method name.</p>\n<p><strong>Unused code</strong></p>\n<p>You have a bunch of unused variables like <code>reader</code> on line 512 and <code>width, height</code> on line 464, and more. I suggest using a code editor like for example PyCharm, which will spot mistakes like that automatically and help you work more efficiently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T11:32:04.283",
"Id": "485925",
"Score": "0",
"body": "Thank you, this is what i was looking for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:52:20.067",
"Id": "485934",
"Score": "0",
"body": "fixed those issues"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T11:25:08.693",
"Id": "248131",
"ParentId": "248110",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T22:38:00.857",
"Id": "248110",
"Score": "2",
"Tags": [
"python",
"beginner",
"object-oriented",
"game"
],
"Title": "Python Blackjack"
}
|
248110
|
<p>So I have made 2 games without any internet when on vacation. I have used turtle because I did not install pygame. I was wondering how I could improve my games. Here is the code:</p>
<p>Pong:</p>
<pre class="lang-py prettyprint-override"><code>from turtle import *
from time import sleep
import random, keyboard, math
setup(width=800, height=700)
if(input('Do you want to have a AI? (Y or N) ') == 'Y'):
Ai = True
else:
Ai = False
ts = getscreen()
ts.bgcolor('black')
title('Pong')
P1_Score = 0
P2_Score = 0
Paddle_2_dir = 225
Paddle_1_dir = -45
Paddle_2_y_bot = 0
Paddle_2_y_top = 0
Paddle_1_y_bot = 0
Paddle_1_y_top = 0
Ball_y = 0
random_range = []
random_int = 0
in_section = False
if(Ai == True):
for i in range(-90, 90):
random_range.append(i)
Score = Turtle()
Paddle_1 = Turtle()
Ball = Turtle()
Paddle_2 = Turtle()
Score.speed(1000)
Paddle_1.speed(1000)
Ball.speed(1000)
Paddle_2.speed(1000)
Score.ht()
Score.color('white')
Paddle_1.color('white')
Ball.color('white')
Paddle_2.color('white')
Score.pu()
Paddle_1.pu()
Ball.pu()
Paddle_2.pu()
Score.goto(0, 290)
Paddle_2.goto(350, 0)
Paddle_1.goto(-350, 0)
Ball.goto(0, 0)
Score.shape("circle")
Paddle_2.shape("square")
Paddle_2.shapesize(stretch_wid=8, stretch_len=1, outline=None)
Paddle_1.shape("square")
Paddle_1.shapesize(stretch_wid=8, stretch_len=1, outline=None)
Ball.shape("circle")
Ball.seth(0)
Score.write(f"{P1_Score} | {P2_Score}", False, align="center", font='Arial 35 normal')
print('Started!')
def Win(Winner):
Score.clear()
Score.write(f"{Winner} Wins!", False, align="center", font='Arial 35 normal')
ts.bgcolor('red')
ht()
sleep(0.5)
ts.bgcolor('blue')
sleep(0.5)
ts.bgcolor('yellow')
sleep(0.5)
ts.bgcolor('green')
sleep(2)
bye()
while True:
Ball.fd(5)
if keyboard.is_pressed('up'):
Paddle_2.goto(350, Paddle_2.ycor() + 8)
if keyboard.is_pressed('down'):
Paddle_2.goto(350, Paddle_2.ycor() - 8)
if keyboard.is_pressed('w'):
Paddle_1.goto(-350, Paddle_1.ycor() + 8)
if keyboard.is_pressed('s'):
Paddle_1.goto(-350, Paddle_1.ycor() - 8)
if(Ball.xcor() > 400):
Score.clear()
P1_Score += 1
Ball.goto(0, 0)
Ball.seth(180)
Paddle_2.sety(0)
Paddle_1.sety(0)
Score.write(f"{P1_Score} | {P2_Score}", False, align="center", font='Arial 35 normal')
elif(Ball.xcor() < -400):
Score.clear()
P2_Score += 1
Ball.goto(0, 0)
Ball.seth(0)
Paddle_2.sety(0)
Paddle_1.sety(0)
Score.write(f"{P1_Score} | {P2_Score}", False, align="center", font='Arial 35 normal')
if(round(Ball.xcor()) < 0 and in_section == False and Ai == True):
random_int = random.choice(random_range)
fail = random.randint(1, 18)
fail_distance = random.randint(10, 30)
in_section = True
elif(round(Ball.xcor()) > 0 and in_section == True and Ai == True):
in_section = False
if(round(Paddle_1.ycor()) != round(Ball.ycor()) and Ai == True and round(Ball.xcor()) < 0):
if(fail == 1):
Paddle_1.sety(Ball.ycor() + (100 + fail_distance))
elif(fail == 2):
Paddle_1.sety(Ball.ycor() - (100 + fail_distance))
else:
Paddle_1.sety(Ball.ycor() + random_int)
if(Ball.xcor() >= Paddle_2.xcor() and Ball.xcor() <= Paddle_2.xcor() + 5):
Paddle_2_y_top = round(Paddle_2.ycor())
Paddle_2_y_top += 90
Paddle_2_y_bot = round(Paddle_2.ycor())
Paddle_2_y_bot -= 90
Ball_y = round(Ball.ycor())
Paddle_2_dir = 225
for i in range(Paddle_2_y_bot, Paddle_2_y_top):
Paddle_2_dir -= .5
if(int(round(Ball_y)) == int(round(i))):
Ball.seth(Paddle_2_dir + 0.5)
break
if(Ball.xcor() <= Paddle_1.xcor() and Ball.xcor() >= Paddle_1.xcor() - 5):
Paddle_1_y_top = round(Paddle_1.ycor())
Paddle_1_y_top += 90
Paddle_1_y_bot = round(Paddle_1.ycor())
Paddle_1_y_bot -= 90
Ball_y = round(Ball.ycor())
Paddle_1_dir = -45
for i in range(Paddle_1_y_bot, Paddle_1_y_top):
Paddle_1_dir += .5
if(int(round(Ball_y)) == int(round(i))):
Ball.seth(Paddle_1_dir - 0.5)
break
if(round(Paddle_2.ycor()) >= 310):
Paddle_2.goto(350, 300)
elif(round(Paddle_2.ycor()) <= -310):
Paddle_2.goto(350, -300)
if(round(Paddle_1.ycor()) >= 310):
Paddle_1.goto(-350, 300)
elif(round(Paddle_1.ycor()) <= -310):
Paddle_1.goto(-350, -300)
if(round(Ball.ycor()) >= 320 or round(Ball.ycor()) <= -320):
Ball.seth(-Ball.heading())
if(P1_Score == 3):
Win('Player 1')
print('Finished!')
break
if(P2_Score == 3):
Win('Player 2')
print('Finished!')
break
if keyboard.is_pressed('Esc'):
while True:
if not keyboard.is_pressed('Esc'):
break
while True:
keyboard.wait('Esc')
while keyboard.is_pressed('Esc'):
sleep(0.1)
break
</code></pre>
<p>Breakout:</p>
<pre class="lang-py prettyprint-override"><code>from turtle import *
from time import sleep
import random, keyboard, math
ht()
setup(width=800, height=700)
Block_color_row_len = 0
Block_Place_X = 0
Block_Place_y = 0
Blocks = 0
Lives = 3
Alive_blocks_int = 0
Resets = 0
Prev_x = 0
Prev_y = 0
new_x = 0
new_y =0
Ball_x = 0
Paddle_dir = 135
Paddle_x_right = 0
Paddle_x_left = 0
Block_pos = [(-350,250), (-250,250), (-150,250), (-50,250), (50,250), (150,250), (250,250), (350,250),
(-350,210), (-250,210), (-150,210), (-50,210), (50,210), (150,210), (250,210), (350,210),
(-350,170), (-250,170), (-150,170), (-50,170), (50,170), (150,170), (250,170), (350,170),
(-350,130), (-250,130), (-150,130), (-50,130), (50,130), (150,130), (250,130), (350,130),
(-350,90), (-250,90), (-150,90), (-50,90), (50,90), (150,90), (250,90), (350,90)]
Block_default = [True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True,
True, True, True, True, True, True, True, True]
Block_y = [250, 250, 250, 250, 250, 250, 250, 250,
210, 210, 210, 210, 210, 210, 210, 210,
170, 170, 170, 170, 170, 170, 170, 170,
130, 130, 130, 130, 130, 130, 130, 130,
90, 90, 90, 90, 90, 90, 90, 90]
Block_x = [-350, -250, -150, -50, 50, 150, 250, 350,
-350, -250, -150, -50, 50, 150, 250, 350,
-350, -250, -150, -50, 50, 150, 250, 350,
-350, -250, -150, -50, 50, 150, 250, 350,
-350, -250, -150, -50, 50, 150, 250, 350]
Block_color_row = [8, 8, 8, 8, 8]
Block_color = ['red', 'orange', 'yellow', 'green', 'blue']
Block_color_cur = []
Block_alive = []
Blocks = len(Block_pos)
def Block(Turtle, Color):
Block_Place_X = Turtle.xcor() - 40
Block_Place_y = Turtle.ycor() - 10
Turtle.goto(Block_Place_X, Block_Place_y)
Turtle.color(Color)
Turtle.begin_fill()
Turtle.pd()
Turtle.goto(Block_Place_X, Block_Place_y + 20)
Turtle.goto(Block_Place_X + 80, Block_Place_y + 20)
Turtle.goto(Block_Place_X + 80, Block_Place_y)
Turtle.goto(Block_Place_X, Block_Place_y)
Turtle.end_fill()
Turtle.pu()
Turtle.goto(Block_Place_X + (Block_Place_X / 2), Block_Place_y + (Block_Place_y / 2))
def New(Turtle):
global Block_pos, Block, Block_color, Block_color_row_len, Block_color_cur, Block_default, Block_alive, Blocks
Turtle.clear()
Block_color_row_len = len(Block_color_row)
Block_color_cur = []
Block_alive = Block_default
for i in range(Block_color_row_len):
for a in range(Block_color_row[i]):
Block_color_cur.append(Block_color[i])
for i in range(Blocks):
Turtle.goto(Block_pos[i])
Block(Turtle, Block_color_cur[i])
ts = getscreen()
ts.bgcolor('black')
title('Breakout')
Block_Creator = Turtle()
Paddle = Turtle()
Ball = Turtle()
Block_Creator.color('black')
Paddle.color('brown')
Ball.color('white')
Block_Creator.pu()
Paddle.pu()
Ball.pu()
Block_Creator.speed(1000)
Paddle.speed(1000)
Ball.speed(1000)
Block_Creator.goto(0, 0)
Paddle.goto(0, -300)
Ball.goto(0, 0)
Block_Creator.ht()
Paddle.shape("square")
Paddle.shapesize(stretch_wid=1, stretch_len=8, outline=None)
Ball.shape("circle")
New(Block_Creator)
Ball.seth(270)
while True:
prev_x = round(Ball.xcor())
prev_y = round(Ball.ycor())
Ball.fd(8)
new_x = round(Ball.xcor())
new_y = round(Ball.ycor())
if keyboard.is_pressed('a') or keyboard.is_pressed('left') and not Paddle.xcor() < -350:
Paddle.bk(8)
elif keyboard.is_pressed('d') or keyboard.is_pressed('right') and Paddle.xcor() < -340:
Paddle.fd(8)
if keyboard.is_pressed('d') or keyboard.is_pressed('right') and not Paddle.xcor() > 350:
Paddle.fd(8)
elif keyboard.is_pressed('a') or keyboard.is_pressed('left') and Paddle.xcor() > 340:
Paddle.bk(8)
if keyboard.is_pressed('Esc'):
bye()
break
if keyboard.is_pressed('space'):
Ball.goto(random.choice(Block_pos))
if(round(Ball.ycor()) <= Paddle.ycor() and round(Ball.ycor()) >= Paddle.ycor() - 4):
Paddle_x_right = round(Paddle.xcor())
Paddle_x_right += 90
Paddle_x_left = round(Paddle.xcor())
Paddle_x_left -= 90
Ball_x = round(Ball.xcor())
Paddle_dir = 135
for i in range(Paddle_x_left, Paddle_x_right):
Paddle_dir -= .5
if(int(round(Ball_x)) == int(round(i))):
Ball.seth(Paddle_dir + 0.5)
break
if(round(Ball.ycor()) >= 80):
for i in range(Blocks):
for a in range(Block_x[i] - 50, Block_x[i] + 50):
if(round(Ball.xcor()) == a):
for f in range(Block_y[i] - 25, Block_y[i] + 25):
if(round(Ball.ycor()) == f):
if(Block_alive[i] == True):
Block_alive[i] = False
Block_Creator.goto(Block_pos[i])
Block(Block_Creator, 'black')
Ball.sety(Ball.ycor() + 0.01)
Ball.sety(Ball.ycor() - 0.01)
Ball.seth(-Ball.heading())
if(Ball.ycor() < -370):
if(Lives >= 1 and Lives != 0):
Lives -= 1
Ball.seth(270)
Ball.goto(0, 0)
Paddle.setx(0)
for i in range(3):
Ball.color('red')
sleep(0.2)
Ball.color('white')
sleep(0.2)
if(Lives == 0):
Ball.seth(270)
Ball.goto(0, 0)
Paddle.setx(0)
Ball.color('red')
sleep(2)
if(Lives <= 0 or Resets > 3):
# End game event here
bye()
break
if(round(Ball.ycor()) >= 330):
Ball.seth(-Ball.heading())
if(round(Ball.xcor()) >= 400 or round(Ball.xcor()) <= -400):
Ball.seth(-Ball.heading() + 180)
Alive_blocks_int = 0
for i in range(Blocks):
if(Block_alive[i] == False):
Alive_blocks_int += 1
if(Alive_blocks_int == 40):
Resets += 1
New(Block_Creator)
Ball.goto(0, 0)
Ball.seth(270)
Paddle.setx(0)
Block_alive = Block_default
</code></pre>
<p>Both of the games work fine, but if you hit the side of the block the angle calculations do not work and it knocks out the entire row. That's a minor issue I still need to work out, but overall it seems to work.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T03:17:32.143",
"Id": "485878",
"Score": "1",
"body": "Welcome to code review where we review code that is working as expected that you have written and provide suggestions on how to improve that code. Due to `glitches` this question is off-topic. Please read our [guidelines](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:59:13.800",
"Id": "485937",
"Score": "3",
"body": "@pacmaninbw Is it really off-topic when the question is not about fixing the glitches? Any program could have bugs and errors and still be functional. I think there's lots that can be improved in this code, regardless of game glitches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:03:34.927",
"Id": "485938",
"Score": "1",
"body": "@user985366 There were 2 votes to close this question when I first saw it, there are now 4 votes to close out of the necessary 5. Unfortunately you can't see this because you don't have the rep yet. I'm not the first or the last to thing the glitches make it off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:14:22.423",
"Id": "485953",
"Score": "0",
"body": "I removed the word 'glitches', lets just say its a combo move if you hit the side of the block lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:42:47.877",
"Id": "485956",
"Score": "3",
"body": "What is it you want out of this question? Do you want us to remove the combo move? Do you want to know ways your code can be improved without touching the combo move?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T23:00:22.033",
"Id": "485990",
"Score": "0",
"body": "Both, i just want to make the code more effective and shorter and remove the combo move."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T06:10:53.503",
"Id": "486002",
"Score": "0",
"body": "We can't do that. I'll remove all off-topic requests, that's the only way we can make this work. The alternative is closing the question."
}
] |
[
{
"body": "<h1>For Pong:</h1>\n<pre><code>if(input('Do you want to have a AI? (Y or N) ') == 'Y'):\n Ai = True\nelse:\n Ai = False\n</code></pre>\n<p>This can be shortened to simply</p>\n<pre><code>ai = input('Do you want to have a AI? (Y or N) ').upper() == 'Y'\n</code></pre>\n<p><code>==</code> already evaluates to <code>True</code>/<code>False</code>, so using it in a condition then dispatching to <code>True</code>/<code>False</code> is redundant. I also added in a call to <code>upper</code> so the user can enter either case of "y" and it will still work.</p>\n<hr />\n<pre><code>random_range = []\n\nif(ai == True):\n for i in range(-90, 90):\n random_range.append(i)\n</code></pre>\n<p>A few things to note:</p>\n<ul>\n<li><p>Similar to before, comparing against <code>True</code> using <code>==</code> is redundant. <code>ai</code> will either be <code>True</code> or <code>False</code> already, which is what <code>ai == True</code> would evaluate to to anyways. <code>if ai:</code> is fine.</p>\n</li>\n<li><p>If you're ever simply <code>append</code>ing to a list in a loop, you should consider using a list comprehension instead. Here though, your intent is just to turn the <code>range</code> into a list, so <code>random_range = list(range(-90, 90))</code> will work fine.</p>\n</li>\n<li><p><code>random_range</code> is only ever used later if <code>ai == true</code>. You could unconditionally create the list instead of checking what <code>ai</code> is. Ya, that wastes a little bit of time, but for such a small list, the time should be negligible.</p>\n</li>\n</ul>\n<hr />\n<hr />\n<h1>For Breakout:</h1>\n<p>I'd use "list multiplication" to neaten up all the massive lists you have at the top. For example, <code>Block_default</code> can be :</p>\n<pre><code>block_default = [True] * (5 * 8) # Or just [True] * 40\n</code></pre>\n<p>And similarly, <code>Block_y</code> could be something like:</p>\n<pre><code>block_y = [row\n for val in range(250, 89, -40) # Generate each of the vals\n for row in [val] * 8] # Use list multiplication, then flatten\n</code></pre>\n<p>If you make some variables at the top that store the height and width of the block of blocks, you can use them instead, and also use some more sequence operations like <a href=\"https://docs.python.org/3.3/library/functions.html#zip\" rel=\"nofollow noreferrer\">zip</a> to <em>greatly</em> reduce duplication:</p>\n<pre><code>BLOCKS_WIDTH = 8\nBLOCKS_HEIGHT = 5\n\nblock_default = [True] * (BLOCKS_HEIGHT * BLOCKS_WIDTH)\n\nblock_y = [row\n for val in range(250, 89, -40)\n for row in [val] * BLOCKS_WIDTH]\n\nblock_x = list(range(-350, 351, 100)) * BLOCKS_HEIGHT\n\n# Take the two existing coordinate lists, and "zip" them together\nblock_pos = list(zip(block_x, block_y)) \n</code></pre>\n<p>Also note, I fixed up your names. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP8</a> says that plain variables should be in "snake_case"</p>\n<p>Beyond that though, I haven't used Turtle in forever, so I can't comment on much else.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T23:01:46.847",
"Id": "485991",
"Score": "0",
"body": "Thanks, this helped alot!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T23:14:59.767",
"Id": "485992",
"Score": "0",
"body": "And I am still new to python so I did not know about PEP8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T23:17:41.390",
"Id": "485993",
"Score": "0",
"body": "@DrakeFletcher No problem. Glad to help. And PEP8 is Python's style guide, and should be followed when possible. I'd just give a quick read through. Most of it is pretty common sense, and you can always check back on it later for general guidelines for particular cases. If you use an IDE like Pycharm as well, you'll automatically get PEP8 style suggestions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T16:53:17.400",
"Id": "248149",
"ParentId": "248112",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248149",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-18T23:02:26.600",
"Id": "248112",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"game",
"turtle-graphics"
],
"Title": "Pong and Breakout games"
}
|
248112
|
<p>I'm self-learning and pretty new to coding and created a Mastermind game in Ruby.
Any general feedback or advice whatsoever would be greatly appreciated.
The game is completely functional right now, and has a simple AI. At the beginning the player chooses which role they want to choose (codebreaker or code maker).</p>
<p>Cheers</p>
<p><a href="https://repl.it/repls/WeirdFrankButtons" rel="nofollow noreferrer">https://repl.it/repls/WeirdFrankButtons</a></p>
<p>edit: fixed link</p>
<pre><code>class Game
def initialize
puts "---------------------------------"
puts "Welcome to Mastermind"
puts "The goal is to either create a 4 digit code (Code maker role) containing numbers ranging from 1 through 6 or to guess a code (Codebreaker role) created by the computer within 12 turns to win."
puts "After each guess you will be given an accuracy score indicating how close you were to guessing the code correctly."
puts "The letter \"H\" indicates one of the numbers you guessed is in the correct position. The letter \"h\" indicates you guessed a correct number but it is NOT in the correct position"
puts "----------------------------------"
@game_over = false
@turn = 1
until @comp_guess_mode === "Y" || @comp_guess_mode === "N"
print "Is the computer the code breaker? Y/N"
@comp_guess_mode = gets.chomp.upcase
end
game_mode
turn_sequence
end
def game_mode
if @comp_guess_mode == "Y"
human_code_generator
else
code_generator
end
end
def code_generator
@code = Array.new(4) {rand(1..6)}
end
def human_code_generator
@code = ""
puts "Please enter a 4 digit code"
until @code.length == 4
@code = gets.chomp.each_char.map(&:to_i)
end
end
# computer_guesser method that tests if the computer's guess matches the human's
# by iterating through the array, if a direct match ('H') is found it will keep that number in the next guess
def computer_guesser
@updated_comp_guess = [" "," "," "," "]
if @turn == 1
@guess = Array.new(4) {rand(1..6)}
else
i = 0
while i <4
if @guess[i] == @code[i]
@updated_comp_guess[i] = @guess[i]
i+=1
else
i +=1
end
end
end
@guess = Array.new(4) {rand(1..6)}
@updated_comp_guess.each_with_index do |value, idx|
if value != " "
@guess[idx] = value
end
end
puts "Guess: #{@guess.join}"
end
def codebreaker_guess
@guess = []
until @guess.length == 4
puts "Enter your 4 digit guess"
@guess = gets.chomp.each_char.map(&:to_i)
puts "Guess: #{@guess.join}"
if @guess.length != 4
print "Your guess was not 4 digits long, please guess again \n"
end
end
end
def turn_display
puts "-------------------------"
puts "It's turn number: #{@turn}"
end
#Repeats the following guess/check sequence for 12 turns
# or until the code and guess are matched
def turn_sequence
while @turn <13 && @game_over == false
turn_display
if @comp_guess_mode == "Y"
computer_guesser
else
codebreaker_guess
end
guess_checker
@turn += 1
victory_check
end
end
def guess_checker
@guess_accuracy = []
@i=0
@h_counter = 0
while @i<4
if @guess[@i] == @code[@i]
@guess_accuracy.push("H")
@h_counter += 1
@i+=1
else
@i+=1
end
end
if @i == 4
i = 0
compare_array = @code.clone
while i < 4
if compare_array.include?(@guess[i])
compare_array[(compare_array.index(@guess[i]))]= " "
@guess_accuracy.push("h")
i+=1
else
i+=1
end
end
@guess_accuracy.pop(@h_counter)
puts "Guess accuracy: #{@guess_accuracy.join}"
end
end
def victory_check
if @guess[0..3] == @code[0..3]
puts "Code was guessed correctly, it's #{@code}, codebreaker wins"
@game_over = true
elsif @turn == 13 && @game_over == false
puts "Code was not guessed correctly, code maker wins"
@game_over = true
end
end
end
game = Game.new
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p><strong>Code 1</strong></p>\n<pre><code>while i <4\n if @guess[i] == @code[i]\n @updated_comp_guess[i] = @guess[i]\n i+=1\n else\n i +=1\n end\n end\n</code></pre>\n<p>In both the <code>if</code> and <code>else</code> you are incrementing <code>i</code> by 1. That can be made shorter.</p>\n<pre><code>while i <4\n if @guess[i] == @code[i]\n @updated_comp_guess[i] = @guess[i]\n end\n i += 1\n end\n</code></pre>\n<p>Similar in the <code>guess_checker</code> further down, and in the <code>compare_array</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T11:44:15.940",
"Id": "248132",
"ParentId": "248114",
"Score": "2"
}
},
{
"body": "<h1>Consistency</h1>\n<p>Sometimes you are using 1 space for indentation, sometimes you are using 2. Sometimes you are using whitespace around operators, sometimes you don't, sometimes you are using whitespace on one side of the operator, but not the other. Sometimes, you use space after a comma, sometimes you don't. Sometimes you use one empty line after a method, sometimes two, sometimes none.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).</p>\n<h1>Indentation</h1>\n<p>The standard indentation style in Ruby is two spaces. You mostly use 2 spaces, but there is one place where you use 1 space. Stick with two.</p>\n<h1>Whitespace around operators</h1>\n<p>There should be 1 space either side of an operator. You sometimes use 1 space, sometimes no space, and sometimes space only on one side.</p>\n<p>For example here, you have the exact same expression within three lines with two different spacing styles:</p>\n<pre class=\"lang-rb prettyprint-override\"><code> i+=1\nelse\n i +=1\n</code></pre>\n<p>They are inconsistent with each, and both of them don't comply with community guidelines. They should both be:</p>\n<pre class=\"lang-rb prettyprint-override\"><code> i += 1\n</code></pre>\n<h1>Space after comma</h1>\n<p>There should be 1 space after a comma. You sometimes use 1 space, sometimes no space.</p>\n<p>E.g. here:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@updated_comp_guess = [" "," "," "," "]\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@updated_comp_guess = [" ", " ", " ", " "]\n</code></pre>\n<h1>Space in blocks</h1>\n<p>In a block literal, there should be a space after the opening curly brace and one before the closing curly brace:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@code = Array.new(4) { rand(1..6) }\n</code></pre>\n<h1>Single-quoted strings</h1>\n<p>If you don't use string interpolation, it is helpful if you use single quotes for your strings. That way, it is immediately obvious that no string interpolation is taking place.</p>\n<p>In particular, this would also remove the escaping you need to do here:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>puts 'The letter "H" indicates one of the numbers you guessed is in the correct position. The letter "h" indicates you guessed a correct number but it is NOT in the correct position'\n</code></pre>\n<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a magic comment you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files.</p>\n<h1>Conditional modifiers</h1>\n<p>When you have a conditional that executes only one expression, you should use the modifier form instead, e.g. this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if value != " "\n @guess[idx] = value\nend\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@guess[idx] = value if value != " "\n</code></pre>\n<p>Same here:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>until @code.length == 4\n @code = gets.chomp.each_char.map(&:to_i)\nend\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@code = gets.chomp.each_char.map(&:to_i) until @code.length == 4\n</code></pre>\n<h1>Unnecessary parentheses</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>compare_array[(compare_array.index(@guess[i]))]= " "\n</code></pre>\n<p>The parentheses around <code>compare_array.index(@guess[i])</code> are unnecessary.</p>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect all of the style violations I pointed out, and also was able to autocorrect all of them.</p>\n<p>Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can <em>actually</em> correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".</p>\n<p>In particular, running Rubocop on your code, it detects 98 offenses, of which it can automatically correct 76. This leaves you with 22 offenses, of which 11 are very simple.</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n\nclass Game\n def initialize\n puts '---------------------------------'\n puts 'Welcome to Mastermind'\n puts 'The goal is to either create a 4 digit code (Code maker role) containing numbers ranging from 1 through 6 or to guess a code (Codebreaker role) created by the computer within 12 turns to win.'\n puts 'After each guess you will be given an accuracy score indicating how close you were to guessing the code correctly.'\n puts 'The letter "H" indicates one of the numbers you guessed is in the correct position. The letter "h" indicates you guessed a correct number but it is NOT in the correct position'\n puts '----------------------------------'\n @game_over = false\n @turn = 1\n until @comp_guess_mode === 'Y' || @comp_guess_mode === 'N'\n print 'Is the computer the code breaker? Y/N'\n @comp_guess_mode = gets.chomp.upcase\n end\n game_mode\n turn_sequence\n end\n\n def game_mode\n if @comp_guess_mode == 'Y'\n human_code_generator\n else\n code_generator\n end\n end\n\n def code_generator\n @code = Array.new(4) { rand(1..6) }\n end\n\n def human_code_generator\n @code = ''\n puts 'Please enter a 4 digit code'\n @code = gets.chomp.each_char.map(&:to_i) until @code.length == 4\n end\n\n # computer_guesser method that tests if the computer's guess matches the human's\n # by iterating through the array, if a direct match ('H') is found it will keep that number in the next guess\n def computer_guesser\n @updated_comp_guess = [' ', ' ', ' ', ' ']\n if @turn == 1\n @guess = Array.new(4) { rand(1..6) }\n else\n i = 0\n while i < 4\n if @guess[i] == @code[i]\n @updated_comp_guess[i] = @guess[i]\n i += 1\n else\n i += 1\n end\n end\n end\n @guess = Array.new(4) { rand(1..6) }\n @updated_comp_guess.each_with_index do |value, idx|\n @guess[idx] = value if value != ' '\n end\n puts "Guess: #{@guess.join}"\n end\n\n def codebreaker_guess\n @guess = []\n until @guess.length == 4\n puts 'Enter your 4 digit guess'\n @guess = gets.chomp.each_char.map(&:to_i)\n puts "Guess: #{@guess.join}"\n print "Your guess was not 4 digits long, please guess again \\n" if @guess.length != 4\n end\n end\n\n def turn_display\n puts '-------------------------'\n puts "It's turn number: #{@turn}"\n end\n\n # Repeats the following guess/check sequence for 12 turns\n # or until the code and guess are matched\n def turn_sequence\n while @turn < 13 && @game_over == false\n turn_display\n if @comp_guess_mode == 'Y'\n computer_guesser\n else\n codebreaker_guess\n end\n guess_checker\n @turn += 1\n victory_check\n end\n end\n\n def guess_checker\n @guess_accuracy = []\n @i = 0\n @h_counter = 0\n while @i < 4\n if @guess[@i] == @code[@i]\n @guess_accuracy.push('H')\n @h_counter += 1\n @i += 1\n else\n @i += 1\n end\n end\n if @i == 4\n i = 0\n compare_array = @code.clone\n while i < 4\n if compare_array.include?(@guess[i])\n compare_array[compare_array.index(@guess[i])] = ' '\n @guess_accuracy.push('h')\n i += 1\n else\n i += 1\n end\n end\n @guess_accuracy.pop(@h_counter)\n puts "Guess accuracy: #{@guess_accuracy.join}"\n end\n end\n\n def victory_check\n if @guess[0..3] == @code[0..3]\n puts "Code was guessed correctly, it's #{@code}, codebreaker wins"\n @game_over = true\n elsif @turn == 13 && @game_over == false\n puts 'Code was not guessed correctly, code maker wins'\n @game_over = true\n end\n end\nend\n\ngame = Game.new\n</code></pre>\n<p>And here are the offenses that Rubocop could not automatically correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Offenses:\n\ngame.rb:3:1: C: Metrics/ClassLength: Class has too many lines. [116/100]\nclass Game ...\n^^^^^^^^^^\ngame.rb:3:1: C: Style/Documentation: Missing top-level class documentation comment.\nclass Game\n^^^^^\ngame.rb:4:3: C: Metrics/MethodLength: Method has too many lines. [14/10]\n def initialize ...\n ^^^^^^^^^^^^^^\ngame.rb:7:121: C: Layout/LineLength: Line is too long. [202/120]\n puts 'The goal is to either create a 4 digit code (Code maker role) containing numbers ranging from 1 through 6 or to guess a code (Codebreaker role) created by the computer within 12 turns to win.'\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\ngame.rb:8:121: C: Layout/LineLength: Line is too long. [125/120]\n puts 'After each guess you will be given an accuracy score indicating how close you were to guessing the code correctly.'\n ^^^^^\ngame.rb:9:121: C: Layout/LineLength: Line is too long. [186/120]\n puts 'The letter "H" indicates one of the numbers you guessed is in the correct position. The letter "h" indicates you guessed a correct number but it is NOT in the correct position'\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\ngame.rb:13:28: C: Style/CaseEquality: Avoid the use of the case equality operator ===.\n until @comp_guess_mode === 'Y' || @comp_guess_mode === 'N'\n ^^^\ngame.rb:13:56: C: Style/CaseEquality: Avoid the use of the case equality operator ===.\n until @comp_guess_mode === 'Y' || @comp_guess_mode === 'N'\n ^^^\ngame.rb:41:3: C: Metrics/AbcSize: Assignment Branch Condition size for computer_guesser is too high. [<12, 12, 11> 20.22/17]\n def computer_guesser ...\n ^^^^^^^^^^^^^^^^^^^^\ngame.rb:41:3: C: Metrics/MethodLength: Method has too many lines. [19/10]\n def computer_guesser ...\n ^^^^^^^^^^^^^^^^^^^^\ngame.rb:50:11: C: Style/IdenticalConditionalBranches: Move i += 1 out of the conditional.\n i += 1\n ^^^^^^\ngame.rb:52:11: C: Style/IdenticalConditionalBranches: Move i += 1 out of the conditional.\n i += 1\n ^^^^^^\ngame.rb:80:3: C: Metrics/MethodLength: Method has too many lines. [11/10]\n def turn_sequence ...\n ^^^^^^^^^^^^^^^^^\ngame.rb:94:3: C: Metrics/AbcSize: Assignment Branch Condition size for guess_checker is too high. [<16, 13, 11> 23.37/17]\n def guess_checker ...\n ^^^^^^^^^^^^^^^^^\ngame.rb:94:3: C: Metrics/MethodLength: Method has too many lines. [27/10]\n def guess_checker ...\n ^^^^^^^^^^^^^^^^^\ngame.rb:102:9: C: Style/IdenticalConditionalBranches: Move @i += 1 out of the conditional.\n @i += 1\n ^^^^^^^\ngame.rb:104:9: C: Style/IdenticalConditionalBranches: Move @i += 1 out of the conditional.\n @i += 1\n ^^^^^^^\ngame.rb:107:5: C: Style/GuardClause: Use a guard clause (return unless @i == 4) instead of wrapping the code inside a conditional expression.\n if @i == 4\n ^^\ngame.rb:114:11: C: Style/IdenticalConditionalBranches: Move i += 1 out of the conditional.\n i += 1\n ^^^^^^\ngame.rb:116:11: C: Style/IdenticalConditionalBranches: Move i += 1 out of the conditional.\n i += 1\n ^^^^^^\ngame.rb:117:8: W: Layout/EndAlignment: end at 117, 7 is not aligned with if at 111, 8.\n end\n ^^^\ngame.rb:135:1: W: Lint/UselessAssignment: Useless assignment to variable - game.\ngame = Game.new\n^^^^\n\n1 file inspected, 22 offenses detected\n</code></pre>\n<p>Let's look at the simple ones first.</p>\n<h1>Case equality operator</h1>\n<p>You use the case equality operator in a couple of places. Because of the way case equality is defined for strings, your code works purely "by accident". You should use the normal equality operator instead.</p>\n<p>This:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>until @comp_guess_mode === "Y" || @comp_guess_mode === "N"\n</code></pre>\n<p>should be this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>until @comp_guess_mode == "Y" || @comp_guess_mode == "N"\n</code></pre>\n<p>Note that you use the correct equality operator for the exact same check here:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if @comp_guess_mode == "Y"\n</code></pre>\n<h1>Identical expressions in all branches</h1>\n<p>There are three places where you have the same expression in both branches of a conditional expression. That is unnecessary clutter, you can just pull the expression out of the conditional:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if @guess[i] == @code[i]\n @updated_comp_guess[i] = @guess[i]\n i+=1\nelse\n i +=1\nend\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if @guess[i] == @code[i]\n @updated_comp_guess[i] = @guess[i]\nend\n\ni +=1\n</code></pre>\n<p>And as we said above, a conditional with only one expression should use the modifier form (note that this transformation would again be performed automatically by Rubocop if you ran it again):</p>\n<pre class=\"lang-rb prettyprint-override\"><code>@updated_comp_guess[i] = @guess[i] if @guess[i] == @code[i]\n\ni +=1\n</code></pre>\n<h1>Unused local variable</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>game = Game.new\n</code></pre>\n<p><code>game</code> is never used anywhere. Just remove it:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>Game.new\n</code></pre>\n<h1>Guard clauses</h1>\n<p>If you have a case where an entire method or block is wrapped in a conditional, you can replace that with a "guard clause" and reduce the level of nesting.</p>\n<p>E.g. this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def something\n if foo\n bar\n baz\n quux\n else\n 42\n end\nend\n</code></pre>\n<p>can become this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def something\n return 42 unless foo\n\n bar\n baz\n quux\nend\n</code></pre>\n<p>There are a couple of opportunities to do this in your code, and a couple more are created by following the Rubocop advice.</p>\n<p>Here is one example where the improvement is not very big:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def game_mode\n if @comp_guess_mode == "Y"\n human_code_generator\n else\n code_generator\n end\nend\n</code></pre>\n<pre class=\"lang-rb prettyprint-override\"><code>def game_mode\n return human_code_generator if @comp_guess_mode == "Y"\n\n code_generator\nend\n</code></pre>\n<p>but here the gain is somewhat bigger:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def guess_checker\n @guess_accuracy = []\n @i=0\n @h_counter = 0\n while @i<4\n if @guess[@i] == @code[@i]\n @guess_accuracy.push("H")\n @h_counter += 1\n @i+=1\n else\n @i+=1\n end\n end\n if @i == 4\n i = 0\n compare_array = @code.clone\n while i < 4\n if compare_array.include?(@guess[i]) \n compare_array[(compare_array.index(@guess[i]))]= " "\n @guess_accuracy.push("h")\n i+=1\n else\n i+=1\n end\n end\n @guess_accuracy.pop(@h_counter)\n puts "Guess accuracy: #{@guess_accuracy.join}"\n end\nend\n</code></pre>\n<pre class=\"lang-rb prettyprint-override\"><code>def guess_checker\n @guess_accuracy = []\n @i = 0\n @h_counter = 0\n\n while @i < 4\n if @guess[@i] == @code[@i]\n @guess_accuracy.push('H')\n @h_counter += 1\n end\n @i += 1\n end\n\n return unless @i == 4\n\n i = 0\n compare_array = @code.clone\n\n while i < 4\n if compare_array.include?(@guess[i]) \n compare_array[compare_array.index(@guess[i])]= ' '\n @guess_accuracy.push('h')\n end\n\n i += 1\n end\n\n @guess_accuracy.pop(@h_counter)\n puts "Guess accuracy: #{@guess_accuracy.join}"\nend\n</code></pre>\n<h1>Redundant checks</h1>\n<p>But actually, the entire thing is even simpler: since you loop and increment <code>i</code> 4 times, it will <em>always</em> be <code>4</code>, so the condition will always be true and you can just remove it altogether.</p>\n<h1>Equality with booleans</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>@game_over == false\n</code></pre>\n<p><code>@game_over</code> is already a boolean, there is no need to check for equality to <code>false</code>. This is just</p>\n<pre class=\"lang-rb prettyprint-override\"><code>!@game_over\n</code></pre>\n<h1>Unnecessary instance variables</h1>\n<p>The instance variables <code>@updated_comp_guess</code>, <code>@i</code>, <code>@h_counter</code>, and <code>@guess_accuracy</code> are only ever used in one method. They should be local variables instead.</p>\n<h1>Loops</h1>\n<p>In Ruby, you almost never need loops. In fact, I would go so far and say that if you are using a loop in Ruby, you are doing it wrong.</p>\n<p>Here's an example:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>i = 0\nwhile i < 4\n updated_comp_guess[i] = @guess[i] if @guess[i] == @code[i]\n\n i += 1\nend\n</code></pre>\n<p>would be much better written as</p>\n<pre class=\"lang-rb prettyprint-override\"><code>4.times do |i|\n updated_comp_guess[i] = @guess[i] if @guess[i] == @code[i]\nend\n</code></pre>\n<p>This will make the <code>guess_checker</code> method look like this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def guess_checker\n guess_accuracy = []\n h_counter = 0\n\n 4.times do |i|\n if @guess[i] == @code[i]\n guess_accuracy.push('H')\n h_counter += 1\n end\n end\n\n compare_array = @code.clone\n\n 4.times do |i|\n if compare_array.include?(@guess[i])\n compare_array[compare_array.index(@guess[i])] = ' '\n guess_accuracy.push('h')\n end\n end\n\n guess_accuracy.pop(h_counter)\n puts "Guess accuracy: #{guess_accuracy.join}"\nend\n</code></pre>\n<p>which gives us again the opportunity to use guard clauses:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>def guess_checker\n guess_accuracy = []\n h_counter = 0\n\n 4.times do |i|\n next unless @guess[i] == @code[i]\n\n guess_accuracy.push('H')\n h_counter += 1\n end\n\n compare_array = @code.clone\n\n 4.times do |i|\n next unless compare_array.include?(@guess[i])\n\n compare_array[compare_array.index(@guess[i])] = ' '\n guess_accuracy.push('h')\n end\n\n guess_accuracy.pop(h_counter)\n puts "Guess accuracy: #{guess_accuracy.join}"\nend\n</code></pre>\n<h1>Redundant expressions</h1>\n<p>In <code>computer_guesser</code>, if <code>@turn == 1</code>, you initialize <code>@guess</code>, and then you initialize it again without ever using it in between. The first initialization can just be removed, turning this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>if @turn == 1\n @guess = Array.new(4) { rand(1..6) }\nelse\n 4.times do |i|\n updated_comp_guess[i] = @guess[i] if @guess[i] == @code[i]\n end\nend\n\n@guess = Array.new(4) { rand(1..6) }\n</code></pre>\n<p>into this:</p>\n<pre class=\"lang-rb prettyprint-override\"><code>unless @turn == 1\n 4.times do |i|\n updated_comp_guess[i] = @guess[i] if @guess[i] == @code[i]\n end\nend\n\n@guess = Array.new(4) { rand(1..6) }\n</code></pre>\n<h1>Code duplication</h1>\n<pre class=\"lang-rb prettyprint-override\"><code>Array.new(4) { rand(1..6) }\n</code></pre>\n<p>Appears multiple times in your code. It should be extracted into a method.</p>\n<h1><code>length</code> vs. <code>size</code></h1>\n<p>Many Ruby collections have both <code>length</code> and <code>size</code> methods, but some have only one. In general, <em>IFF</em> a collection has a <code>size</code> method, then that method is guaranteed to be "efficient" (usually constant time), whereas <code>length</code> may or may not be efficient (linear time for iterating through the collection and counting all the elements), depending on the collection.</p>\n<p>In your case, you are using arrays and strings, for which both are constant time, but if you want to guarantee efficiency, then it is better to explicitly use <code>size</code> instead.</p>\n<h1>The Elephant in the room</h1>\n<p>One thing I have not addressed so far, and that I unfortunately do not have to time to address, is the fundamental design of the code. Everything I mentioned so far is just cosmetics.</p>\n<p>All work is done in the initializer. All an initializer should do is initialize the object. It shouldn't ask for user input, it shouldn't print anything, it shouldn't play a game.</p>\n<p>Also, you are mixing I/O and logic everywhere. A method should either print something or do something. Your design makes it impossible to test the code without actually playing the game. I cannot prepare a file with codes and guesses and feed it to a test runner, I actually have to manually play the game.</p>\n<p>It is also strange that you have only one "object", namely the game, which is doing something. If you think about how the game is typically played, aren't the objects that are actively doing something the players and not the game? Where are the players in your design?</p>\n<p>Unfortunately, I do not have time to dive into this.</p>\n<p>Here is where the code currently stands:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n\nclass Game\n def initialize\n puts '---------------------------------'\n puts 'Welcome to Mastermind'\n puts 'The goal is to either create a 4 digit code (Code maker role) containing numbers ranging from 1 through 6 or to guess a code (Codebreaker role) created by the computer within 12 turns to win.'\n puts 'After each guess you will be given an accuracy score indicating how close you were to guessing the code correctly.'\n puts 'The letter "H" indicates one of the numbers you guessed is in the correct position. The letter "h" indicates you guessed a correct number but it is NOT in the correct position'\n puts '----------------------------------'\n\n @game_over = false\n @turn = 1\n\n until @comp_guess_mode == 'Y' || @comp_guess_mode == 'N'\n print 'Is the computer the code breaker? Y/N'\n @comp_guess_mode = gets.chomp.upcase\n end\n\n game_mode\n turn_sequence\n end\n\n def game_mode\n return human_code_generator if @comp_guess_mode == 'Y'\n\n code_generator\n end\n\n def code_generator\n @code = Array.new(4) { rand(1..6) }\n end\n\n def human_code_generator\n @code = ''\n puts 'Please enter a 4 digit code'\n @code = gets.chomp.each_char.map(&:to_i) until @code.size == 4\n end\n\n # computer_guesser method that tests if the computer's guess matches the human's\n # by iterating through the array, if a direct match ('H') is found it will keep that number in the next guess\n def computer_guesser\n updated_comp_guess = [' ', ' ', ' ', ' ']\n\n unless @turn == 1\n 4.times do |i|\n updated_comp_guess[i] = @guess[i] if @guess[i] == @code[i]\n end\n end\n\n @guess = Array.new(4) { rand(1..6) }\n updated_comp_guess.each_with_index do |value, idx|\n @guess[idx] = value if value != ' '\n end\n\n puts "Guess: #{@guess.join}"\n end\n\n def codebreaker_guess\n @guess = []\n\n until @guess.size == 4\n puts 'Enter your 4 digit guess'\n @guess = gets.chomp.each_char.map(&:to_i)\n puts "Guess: #{@guess.join}"\n print "Your guess was not 4 digits long, please guess again \\n" if @guess.size != 4\n end\n end\n\n def turn_display\n puts '-------------------------'\n puts "It's turn number: #{@turn}"\n end\n\n # Repeats the following guess/check sequence for 12 turns\n # or until the code and guess are matched\n def turn_sequence\n while @turn < 13 && !@game_over\n turn_display\n if @comp_guess_mode == 'Y'\n computer_guesser\n else\n codebreaker_guess\n end\n guess_checker\n @turn += 1\n victory_check\n end\n end\n\n def guess_checker\n guess_accuracy = []\n h_counter = 0\n\n 4.times do |i|\n next unless @guess[i] == @code[i]\n\n guess_accuracy.push('H')\n h_counter += 1\n end\n\n compare_array = @code.clone\n\n 4.times do |i|\n next unless compare_array.include?(@guess[i])\n\n compare_array[compare_array.index(@guess[i])] = ' '\n guess_accuracy.push('h')\n end\n\n guess_accuracy.pop(h_counter)\n puts "Guess accuracy: #{guess_accuracy.join}"\n end\n\n def victory_check\n if @guess == @code\n puts "Code was guessed correctly, it's #{@code}, codebreaker wins"\n @game_over = true\n elsif @turn == 13 && !@game_over\n puts 'Code was not guessed correctly, code maker wins'\n @game_over = true\n end\n end\nend\n\nGame.new\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-03T20:58:44.177",
"Id": "248887",
"ParentId": "248114",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T00:14:15.510",
"Id": "248114",
"Score": "2",
"Tags": [
"beginner",
"game",
"ruby"
],
"Title": "Ruby Mastermind game project with AI"
}
|
248114
|
<p>Getting my feet wet with Game Development, and was wanting to see where I could improve in my usage of Rust as well as Game Development concepts.</p>
<pre><code>use rand::Rng;
use sfml::graphics::{Color, Font, RectangleShape, RenderStates, RenderTarget, RenderWindow, Text, Transformable, Shape};
use sfml::system::Vector2f;
use sfml::window::{ContextSettings, Event, Key, Style};
const WINDOW_WIDTH: f32 = 800.0;
const WINDOW_HEIGHT: f32 = 600.0;
const PADDLE_MOVE_SPEED: f32 = 2.5;
const PADDLE_WIDTH: f32 = 12.0;
const PADDLE_HEIGHT: f32 = 48.0;
const BALL_MOVE_SPEED: f32 = 3.0;
const BALL_WIDTH: f32 = 8.0;
const BALL_HEIGHT: f32 = 8.0;
#[derive(PartialEq)]
enum GameState { Menu, Game, Pause }
struct Pong {
state: GameState,
left_score: u32,
right_score: u32
}
impl Pong {
fn new() -> Pong {
Pong {
state: GameState::Menu,
left_score: 0,
right_score: 0
}
}
}
fn main() {
let mut window = RenderWindow::new(
(WINDOW_WIDTH as u32, WINDOW_HEIGHT as u32),
"Pong",
Style::CLOSE,
&ContextSettings::default(),
);
window.set_framerate_limit(60);
let mut rng = rand::thread_rng();
let font_primary = Font::from_file("res/Roboto-Medium.ttf").expect("Failed to load font file");
let txt_color_hover = Color::rgba(255, 255, 255, 128);
let txt_color_default = Color::rgb(255, 255, 255);
let mut pong = Pong::new();
let paddle_size = Vector2f::new(PADDLE_WIDTH, PADDLE_HEIGHT);
let mut left_paddle = RectangleShape::with_size(paddle_size);
let mut right_paddle = RectangleShape::with_size(paddle_size);
let mut ball = RectangleShape::with_size(Vector2f::new(BALL_WIDTH, BALL_HEIGHT));
let mut txt_left_score = Text::new("0", &font_primary, 18);
let mut txt_right_score = Text::new("0", &font_primary, 18);
left_paddle.set_position(Vector2f::new(WINDOW_WIDTH * 0.07, (WINDOW_HEIGHT * 0.5) - (PADDLE_HEIGHT / 2.0)));
right_paddle.set_position(Vector2f::new(WINDOW_WIDTH * 0.93, (WINDOW_HEIGHT * 0.5) - (PADDLE_HEIGHT / 2.0)));
ball.set_position(Vector2f::new((WINDOW_WIDTH * 0.5) - (BALL_WIDTH / 2.0), (WINDOW_HEIGHT * 0.5) / (BALL_HEIGHT / 2.0)));
txt_left_score.set_position(Vector2f::new(WINDOW_WIDTH * 0.25, 15.0));
txt_right_score.set_position(Vector2f::new(WINDOW_WIDTH * 0.75, 15.0));
let mut ball_direction = Vector2f::new(rng.gen(), rng.gen());
let mut ball_speed = BALL_MOVE_SPEED;
let mut txt_title = Text::new("Pong", &font_primary, 54);
let mut txt_play = Text::new("play", &font_primary, 22);
let mut txt_menu_quit = Text::new("quit", &font_primary, 22);
txt_title.set_position(Vector2f::new(WINDOW_WIDTH * 0.07, WINDOW_HEIGHT * 0.30));
txt_play.set_position(Vector2f::new(WINDOW_WIDTH * 0.08, WINDOW_HEIGHT * 0.45));
txt_menu_quit.set_position(Vector2f::new(WINDOW_WIDTH * 0.08, WINDOW_HEIGHT * 0.52));
let mut txt_paused = Text::new("Paused", &font_primary, 54);
let mut txt_resume = Text::new("resume", &font_primary, 22);
let mut txt_pause_quit = Text::new("quit", &font_primary, 22);
txt_paused.set_position(Vector2f::new(
(WINDOW_WIDTH / 2.0) - (txt_paused.global_bounds().width / 2.0),
WINDOW_HEIGHT * 0.3
));
txt_resume.set_position(Vector2f::new(
(WINDOW_WIDTH / 2.0) - (txt_resume.global_bounds().width / 2.0),
WINDOW_HEIGHT * 0.45
));
txt_pause_quit.set_position(Vector2f::new(
(WINDOW_WIDTH / 2.0) - (txt_pause_quit.global_bounds().width / 2.0),
WINDOW_HEIGHT * 0.52
));
while window.is_open() {
while let Some(event) = window.poll_event() {
match event {
Event::Closed => window.close(),
Event::MouseButtonPressed { x, y, .. } => {
match &pong.state {
GameState::Menu => {
if txt_play.global_bounds().contains2(x as f32, y as f32) {
pong.state = GameState::Game;
} else if txt_menu_quit.global_bounds().contains2(x as f32, y as f32) {
window.close();
}
}
GameState::Pause => {
if txt_resume.global_bounds().contains2(x as f32, y as f32) {
pong.state = GameState::Game;
} else if txt_pause_quit.global_bounds().contains2(x as f32, y as f32) {
window.close();
}
}
_ => {}
}
},
Event::KeyPressed { code, .. } => {
if code == Key::Escape {
if pong.state == GameState::Pause {
pong.state = GameState::Game;
} else if pong.state == GameState::Game {
pong.state = GameState::Pause;
}
} else if code == Key::Space {
if pong.state == GameState::Menu {
pong.state = GameState::Game;
}
}
}
_ => ()
}
}
let mouse_pos = window.mouse_position();
match &pong.state {
GameState::Menu => {
if txt_play.global_bounds().contains2(mouse_pos.x as f32, mouse_pos.y as f32) {
txt_play.set_fill_color(txt_color_hover);
} else {
txt_play.set_fill_color(txt_color_default);
}
if txt_menu_quit.global_bounds().contains2(mouse_pos.x as f32, mouse_pos.y as f32) {
txt_menu_quit.set_fill_color(txt_color_hover)
} else {
txt_menu_quit.set_fill_color(txt_color_default);
}
window.set_active(true);
window.clear(Color::BLACK);
window.draw_text(&txt_title, RenderStates::default());
window.draw_text(&txt_play, RenderStates::default());
window.draw_text(&txt_menu_quit, RenderStates::default());
window.display();
}
GameState::Game => {
// ~~~ Left Paddle ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if Key::S.is_pressed() {
if left_paddle.position().y >= 0.0 {
left_paddle.move_(Vector2f::new(0.0, -PADDLE_MOVE_SPEED));
}
}
if Key::X.is_pressed() {
if left_paddle.position().y <= (WINDOW_HEIGHT as f32 - left_paddle.global_bounds().height) {
left_paddle.move_(Vector2f::new(0.0, PADDLE_MOVE_SPEED));
}
}
// #########################################################################################
// ~~~ Right Paddle ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if Key::Up.is_pressed() {
if right_paddle.position().y >= 0.0 {
right_paddle.move_(Vector2f::new(0.0, -PADDLE_MOVE_SPEED));
}
}
if Key::Down.is_pressed() {
if right_paddle.position().y <= (WINDOW_HEIGHT as f32 - right_paddle.global_bounds().height) {
right_paddle.move_(Vector2f::new(0.0, PADDLE_MOVE_SPEED));
}
}
// #########################################################################################
// ~~~ Ball ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ball.position().y <= 0.0 || ball.position().y >= (WINDOW_HEIGHT as f32 - ball.global_bounds().width) {
ball_direction.y *= -1.0;
}
if ball.position().x <= 0.0 {
pong.right_score += 1;
txt_right_score.set_string(pong.right_score.to_string().as_str());
left_paddle.set_position(Vector2f::new(WINDOW_WIDTH * 0.07, (WINDOW_HEIGHT * 0.5) - (PADDLE_HEIGHT / 2.0)));
right_paddle.set_position(Vector2f::new(WINDOW_WIDTH * 0.93, (WINDOW_HEIGHT * 0.5) - (PADDLE_HEIGHT / 2.0)));
ball.set_position(Vector2f::new((WINDOW_WIDTH * 0.5) - (BALL_WIDTH / 2.0), (WINDOW_HEIGHT * 0.5) / (BALL_HEIGHT / 2.0)));
}
if ball.position().x >= WINDOW_WIDTH {
pong.left_score += 1;
txt_left_score.set_string(pong.left_score.to_string().as_str());
left_paddle.set_position(Vector2f::new(WINDOW_WIDTH * 0.07, (WINDOW_HEIGHT * 0.5) - (PADDLE_HEIGHT / 2.0)));
right_paddle.set_position(Vector2f::new(WINDOW_WIDTH * 0.93, (WINDOW_HEIGHT * 0.5) - (PADDLE_HEIGHT / 2.0)));
ball.set_position(Vector2f::new((WINDOW_WIDTH * 0.5) - (BALL_WIDTH / 2.0), (WINDOW_HEIGHT * 0.5) / (BALL_HEIGHT / 2.0)));
}
if let Some(_collision) = ball.global_bounds().intersection(&left_paddle.global_bounds()) {
ball_direction.x *= -1.0;
ball_speed += 0.1;
}
if let Some(_collision) = ball.global_bounds().intersection(&right_paddle.global_bounds()) {
ball_direction.x *= -1.0;
ball_speed += 0.1;
}
ball.move_(Vector2f::new(ball_direction.x * ball_speed, ball_direction.y * ball_speed));
// #########################################################################################
window.set_active(true);
window.clear(Color::BLACK);
window.draw_text(&txt_left_score, RenderStates::default());
window.draw_text(&txt_right_score, RenderStates::default());
window.draw_rectangle_shape(&left_paddle, RenderStates::default());
window.draw_rectangle_shape(&right_paddle, RenderStates::default());
window.draw_rectangle_shape(&ball, RenderStates::default());
window.display();
}
GameState::Pause => {
if txt_resume.global_bounds().contains2(mouse_pos.x as f32, mouse_pos.y as f32) {
txt_resume.set_fill_color(txt_color_hover);
} else {
txt_resume.set_fill_color(txt_color_default);
}
if txt_pause_quit.global_bounds().contains2(mouse_pos.x as f32, mouse_pos.y as f32) {
txt_pause_quit.set_fill_color(txt_color_hover);
} else {
txt_pause_quit.set_fill_color(txt_color_default);
}
window.set_active(true);
window.clear(Color::BLACK);
window.draw_text(&txt_paused, RenderStates::default());
window.draw_text(&txt_resume, RenderStates::default());
window.draw_text(&txt_pause_quit, RenderStates::default());
window.display();
}
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T02:55:03.080",
"Id": "248117",
"Score": "2",
"Tags": [
"rust",
"sfml",
"pong"
],
"Title": "Pong Implementation using Rust SFML"
}
|
248117
|
<p>Earlier this year, I posted the following;
<a href="https://codereview.stackexchange.com/questions/239657/extract-data-from-api-using-vba-xml-performance">Extract data from API using VBA & XML (Performance)</a></p>
<p>The purpose of this project is/was to develop a small data extractor for our existing API to ensure that even the smallest of our customers could receive the data they need. As hinted, we provide our data through an API, but we are in an industry where the adaptation to this kind of technology is slow, which ultimately results in many ours of manual data-work on our side, because our customers simply need the data.</p>
<p>Fast forward, the project is kind of done (thanks!). However, I am close to paranoid in terms of security.
The newest version is almost the same as the one I have linked, but now also prompts the user for his/her Username and Password for our API, ultimately allowing them <strong>to get their own data (prices, etc)</strong>.</p>
<p>These are my worries;</p>
<ul>
<li><p>I want to be absolutely sure, that I do not send our customers something that potentially could allow them to check other customer's data (prices, etc.). I have tested my self, and since you need a user and pass to access the API it self - and hence also via this program - you wont get any data if you dont provide login information. <strong>But,</strong> since this is my first time doing something like this, I am naturally (?) scared, that things might be "different" when you do something like this via VBA and httprequest.</p>
</li>
<li><p>Is there anything I can/should do in terms of ensuring security? Any references, code or specific declaration of the username and password variables, which are asked for via Input Boxes (and then inserted into the API-URL)?</p>
</li>
<li><p>Should I password-protect my code or does it not make any difference? I have deleted everything that is not public in the code and have applied the inputboxes for username and password due to the same reason - I dont want confidential information stored, instead the customer inputs themselves.</p>
</li>
</ul>
<p>New Code:
<a href="https://pastebin.com/8gFUqd6e" rel="nofollow noreferrer">https://pastebin.com/8gFUqd6e</a></p>
<p>I must admit that I feel a bit embaressed for asking this question, as my logic is telling me that I am wasting everyones time, but I am a rookie after all and dont want to fuck up my belowed workplace :-)!</p>
<p>As always, I am exremely thankful for any help provided by you guys. Thank you so much for your time.</p>
<p>Snippet to allow posting;</p>
<pre><code>Dim httpRequest As New WinHttpRequest
httpRequest.SetTimeouts 0, 0, 0, 0
httpRequest.Open "GET", strURL, False
httpRequest.Send
</code></pre>
<p>Again, Thanks!</p>
<p>Peder</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T08:54:22.217",
"Id": "248127",
"Score": "1",
"Tags": [
"vba",
"api"
],
"Title": "Ensuring secure API connection VBA"
}
|
248127
|
<p>Im finally done with my project and im going through my code and optimising it and trying to cut down on the chunky lines of code, how would i optimize this, it a series of if statments that matches text and adds value to a corresponding text box</p>
<pre><code>private void btnfinalize_Click(object sender, EventArgs e)
{
for (int i = 0; i < POSDGV.Rows.Count; ++i)
{
if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Manga vol 1-5 ")
{
Global.Book1 = 1 + Global.Book1;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Manga vol 6-15 ")
{
Global.Book2 = 1 + Global.Book2;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Novels 1-199 ")
{
Global.Book3 = 1 + Global.Book3;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Novels 200-400 ")
{
Global.Book4 = 1 + Global.Book4;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Comics series mainstream ")
{
Global.Book5 = 1 + Global.Book5;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Comics series secondary ")
{
Global.Book6 = 1 + Global.Book6;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Text book 1 semester/2 modules ")
{
Global.Book7 = 1 + Global.Book7;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Text book module add-ons ")
{
Global.Book8 = 1 + Global.Book8;
}
else if (POSDGV.Rows[i].Cells[0].Value.ToString() == "Hardcover ")
{
Global.Hardcover = 1 + Global.Hardcover;
}
}
}
</code></pre>
<p>Thx for any help</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T09:35:40.893",
"Id": "485916",
"Score": "3",
"body": "Start with removing repeating code: store this `POSDGV.Rows[i].Cells[0].Value.ToString()` and compare that with the literals."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:05:33.007",
"Id": "485928",
"Score": "0",
"body": "Welcome to code review where we review working code and provide suggestions on how to improve that code. Unfortunately there isn't enough code in this question to provide a context for a code review. We would like to see how the function is used within the class or program. I suspect this is why @anki answered in a comment rather than providing a full answer."
}
] |
[
{
"body": "<p>You can use a dictionary with keys being the strings you're testing and values that are the corresponding book.</p>\n<pre><code>IDictionary<string, int> myDictionary = new Dictionary<string, int>();\nmyDictionary.Add("Manga vol 1-5 ", Global.Book1);\n// and so on\n</code></pre>\n<p>Then simply use something like</p>\n<pre><code>myDictionary[POSDGV.Rows[i].Cells[0].Value.ToString()]++\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T10:49:39.693",
"Id": "248129",
"ParentId": "248128",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T09:30:17.663",
"Id": "248128",
"Score": "-1",
"Tags": [
"c#"
],
"Title": "How would i optimise this if statement"
}
|
248128
|
<p>I am building a tool that interacts with a batched stream of incoming data. This data needs to be processed and the result returned. To split up the work I have created a class that has inbound (<code>_in</code>) and outbound (<code>out</code>) queues and workers that are getting, processing, and depositing the work.</p>
<p>This example takes an iterable of numbers (in <code>pass_data</code>) and multiplies them by <code>f</code>.</p>
<pre class="lang-py prettyprint-override"><code>import queue, random, time
from multiprocessing import Process, Queue
def _worker(_in, out, f):
"""Get work from _in and output processed data to out"""
while True:
try:
work = _in.get()
except queue.Empty:
continue
# simulate blocking for some time
time.sleep(random.uniform(0.01, 0.5))
out.put(work * f)
class C:
def __init__(self, f, threads=2):
self.f = f
self.threads = threads
self._in, self.out = Queue(), Queue()
self.args = (self._in, self.out, self.f)
self.workers = [
Process(target=_worker, args=self.args) for _ in range(self.threads)
]
def __repr__(self):
return f"{self.__class__.__name__}(threads={self.threads})"
def start(self):
"""Start all workers"""
for worker in self.workers:
worker.start()
def terminate(self):
"""Terminate all workers"""
for worker in self.workers:
worker.terminate()
def pass_data(self, data):
"""Pass data to the queue to be processed"""
for rec in data:
self._in.put(rec)
def get_completed(self):
"""Return a list of processed data"""
items = []
while True:
try:
items.append(self.out.get_nowait())
except queue.Empty:
break
return items
if __name__ == "__main__":
c = C(f=12, threads=2)
c.start()
for i in range(5):
s = 0
n = random.randint(1, 20)
c.pass_data(list(range(n)))
print(f"sent: {n}")
while s < n:
r = c.get_completed()
s += len(r)
if r:
print(len(r), end=", ")
time.sleep(random.uniform(0.01, 0.4))
print()
c.terminate()
</code></pre>
<p>This is, at the moment, a proof of concept. Are there any pitfalls to this method? Is there a better way to do this already?!</p>
<p>Aspects that I intend to address:</p>
<ul>
<li>queue size limits</li>
<li>thread number limits</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:25:05.833",
"Id": "485942",
"Score": "2",
"body": "Might want to use `in_` instead of `_in`. I understand that simply `in` would conflict with the keyword. This is better because leading _ is in python considered variable for internal use only, and judging by `out` that has no leading _, you don't want to hide `in`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T14:04:54.790",
"Id": "485950",
"Score": "0",
"body": "A similar thing to what I discussed in my other comment can be found in `tkinter.Grid.config`"
}
] |
[
{
"body": "<h1>Use <code>multiprocessing.Pool</code></h1>\n<p>The <code>multiprocessing</code> library already has a <a href=\"https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool\" rel=\"noreferrer\">worker pool</a> implementation ready to be used. Your code could be rewritten as:</p>\n<pre><code>import time\nfrom multiprocessing import Pool\n\ndef f(x):\n time.sleep(random.uniform(0.01, 0.5))\n return x * 12\n\nif __name__ == "__main__":\n c = Pool(2)\n\n for i in range(5):\n n = random.randint(1, 20)\n r = c.map_async(f, list(range(n)))\n print(f"sent: {n}")\n print(f"got: {len(r.get())}")\n</code></pre>\n<p>While <code>multiprocessing.Pool</code> allows you to check if the results are ready by using <code>.ready()</code> on the result of an <code>apply_async()</code> or <code>map_async()</code> call, you can't get a partial result from <code>map_async()</code>. However, if you do want to process individual results as soon as they are ready, you can consider calling <code>apply_async()</code> with a callback function that handles the result.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T18:24:34.137",
"Id": "248779",
"ParentId": "248136",
"Score": "5"
}
},
{
"body": "<p>Here are some observations and things to consider.</p>\n<p>Are you sure you need multiprocessing or threads? There isn't any information in the question to say why they may be needed. There is overhead for using them. Perhaps an input-compute-output loop is sufficient.</p>\n<p>Do you anticipate the program to have throughput limited by IO or by CPU processing. The general rule of thumb is to use threads or <code>asynchio</code> for the former and processes for the later.</p>\n<p>Does it matter that results may not be returned in the same order they were submitted? Do they need to be time-stamped?</p>\n<p><code>threads</code> is a confusing parameter name when using processes.</p>\n<p>The current main code puts items in the input queue and gets items from the output queue. If the queues have limited sizes it will be possible to deadlock if the main code is blocked on adding to a full input queue and the workers are blocked from adding to a full output queue.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-01T18:44:56.810",
"Id": "248781",
"ParentId": "248136",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "248781",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:56:42.677",
"Id": "248136",
"Score": "4",
"Tags": [
"python",
"multiprocessing"
],
"Title": "Class with multiple workers"
}
|
248136
|
<p>The code below if launched on the command line is a simple guessing game.</p>
<p>A random character 'a', 'b' or 'c' is chosen, and the user is prompted until they guess correctly.</p>
<p>It's arguable that invalid input and a win is not necessarily exceptional. Should exceptions be used in this manner?</p>
<p>I am not sure what's a sensible way to check for a winning situation and to terminate the game.</p>
<pre><code><?php
class ABorCException extends Exception {
const WIN = 'Win';
const INVALID = 'Invalid';
}
class ABorC
{
const CHOICES = ['a', 'b', 'c'];
public $answer;
public $turns;
public function __construct($answer = null)
{
$this->answer = $answer ?? self::CHOICES[array_rand(self::CHOICES)];
}
public function turn($guess)
{
if(!in_array($guess, self::CHOICES))
throw new ABorCException(ABorCException::INVALID);
$this->turns[] = $guess;
if($guess === $this->answer)
throw new ABorCException(ABorCException::WIN);
}
}
$game = new ABorC;
while (true) {
try {
$input = readline("Enter your guess a, b or c?\n");
$game->turn($input);
echo "Wrong!\n", "Guess again.\n";
} catch (ABorCException $e) {
if($e->getMessage()===ABorCException::INVALID) {
echo "Invalid input.\n";
}
if($e->getMessage()===ABorCException::WIN) {
echo "Correct!\n", "You won in ", count($game->turns), " valid attempts.\n";
exit;
}
}
}
</code></pre>
<p>Sample game:</p>
<pre><code>$ php aborc.php
Enter your guess a, b or c?a
Wrong!
Guess again.
Enter your guess a, b or c?z
Invalid input.
Enter your guess a, b or c?b
Correct!
You won in 2 valid attempts.
</code></pre>
|
[] |
[
{
"body": "<p>You are using <a href=\"https://softwareengineering.stackexchange.com/q/189222/118878\">exceptions for flow control, and that is considered an anti-pattern</a>.</p>\n<p>Exceptions are meant for unhandlable conditions that would otherwise corrupt your application. Winning the game should not corrupt the application and cause undefined behavior. If it does, you are likely building a stock trading application (I'm only kidding ;-) of course).</p>\n<p>Invalid input could certainly corrupt things or cause undefined behavior, but in this case your program should expect invalid input and handle it gracefully. Always expect the unexpected with user input.</p>\n<p>When reading input, check that it is correct. Loop until you get correct input.</p>\n<p>The <code>$game-turn()</code> method could return a "result" object, which reports back whether the game has been won, and if so who the winner is (and possibly a score). Again, handle this with a simple <code>if</code> statement:</p>\n<pre><code>$result = $game->turn($input);\n\nif ($result->isWinningTurn()) {\n echo "Winner! {$result->winner}";\n}\nelse {\n echo "next move";\n}\n</code></pre>\n<p>If <code>$game->turn()</code> throws an exception, I would expect it to be an unhandled condition or something unrecoverable like an out of memory exception. As a programmer, I would be VERY surprised if winning the game crashed the program.</p>\n<p>Now, the <code>turn()</code> method should throw an exception if you give it bad input. That makes sense. But you need to check for valid input <em>before</em> calling <code>$game->turn($input)</code>. You likely need an <code>isValidInput</code> method on the game object in order to check this.</p>\n<pre><code>$game-turn("d"); // I expect this to throw\n\nif ($game->isValidInput($input)) {\n $result = $game->turn($input)); // I expect this to always succeed\n\n if ($result.isWinningTurn()) {\n ...\n }\n else {\n ...\n }\n}\nelse {\n echo "Bad input, try again."\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T16:58:47.027",
"Id": "248150",
"ParentId": "248137",
"Score": "7"
}
},
{
"body": "<p>I suppose I am not convinced that your simple game actually needs to establish any exceptions for these predictable failures in flow. I agree with Greg that a win should definitely not be a throwable exception -- because it is predictable.</p>\n<p>I like <a href=\"https://stackoverflow.com/a/41387958/2943403\">this simplistic answer</a> to "When should you use PHP Exceptions?". Because your script is handling very predictable failures in the user's actions, adding exceptions seems like unnecessary overhead / code bloat. With some simple refactoring to return the reason the guess was wrong else no reason (guess was correct), exceptions can be cleanly avoided.</p>\n<p>Code: (tested on <a href=\"https://repl.it\" rel=\"nofollow noreferrer\">https://repl.it</a>)</p>\n<pre><code>class ABorC\n{\n const CHOICES = ['a', 'b', 'c'];\n public $answer;\n public $validGuesses = 0;\n\n public function __construct(?string $answer = null)\n {\n $this->answer = in_array($this->answer, self::CHOICES)\n ? $answer\n : self::CHOICES[array_rand(self::CHOICES)];\n }\n\n public function wrongGuessReason(string $guess): ?string\n {\n if (!in_array($guess, self::CHOICES)) {\n return 'Invalid input';\n }\n ++$this->validGuesses;\n if ($guess === $this->answer) {\n return 'Wrong!';\n }\n return null;\n }\n}\n\n$game = new ABorC;\ndo {\n $reasonIncorrect = $game->wrongGuessReason(readline("Enter your guess a, b or c?\\n"));\n echo $reasonIncorrect . "\\n";\n} while ($reasonIncorrect);\nprintf(\n "Correct!\\nYou won after %d valid attempt%s\\n",\n $game->validGuesses,\n $game->validGuesses === 1 ? '' : 's'\n);\n</code></pre>\n<ol>\n<li>Please review all of the recommendations in PSR-12. I know you like to omit curly braces in your code, but this is <a href=\"https://www.php-fig.org/psr/psr-12/#:%7E:text=An%20if%20structure%20looks%20like,body\" rel=\"nofollow noreferrer\">a violation of PSR guidelines</a>.</li>\n<li>You could also validate that any manually loaded answer is also in the expected range and fallback to a randomized answer.</li>\n<li>I am becoming increasingly supportive of the use of <code>printf()</code> and <code>sprintf()</code> instead of messy concatenation involving variables. If you are going to use commas to concatenate in your <code>echo</code>s, then write a space on either side of the comma so that it gets the same treatment as dot-concatenation. (...not to be confused with commas used to separate arguments.)</li>\n<li>I don't see any reason to cache the guesses in your class, since you are not printing them in the conclusion. For this reason, just use <code>$this->validGuesses</code> as a counter and increment it on each valid turn.</li>\n<li>As soon as the guess is right, break the loop and show the congratulations.</li>\n<li>I try to avoid single-use variables, but if you want to declare a variable to store the <code>readline()</code> value, that's not ridiculous because it may help coders who read your code and do not know what <code>readline()</code> does/returns.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-23T12:32:21.763",
"Id": "248314",
"ParentId": "248137",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T12:58:04.670",
"Id": "248137",
"Score": "3",
"Tags": [
"php",
"exception"
],
"Title": "\"Guess a random letter\" game with command line interface"
}
|
248137
|
<p>Simple star designer for HTML canvas. Allows you to change every variable about how to draw the star.</p>
<p>This can be used to create squares, triangle, circles, hexagons, etc. But isn't an efficient way to create them and is only recommended for creating star shapes.</p>
<p>Note! the rotation is purely for show and isn't included in the produced code snippet.</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 canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const cX = canvas.width / 2;
const cY = canvas.height / 2;
let radius = 25;
let innerRadius = 10;
let steps = 5;
let eachStepRadian = (2 * Math.PI) / steps;
let lineWidth = 5;
let rotationSpeed = 0;
let rotation = 0;
let fillColor = 'blue';
let strokeColor = 'black';
document.getElementById('point-count').addEventListener('change', (e) => {
document.getElementById('code-to-make').innerHTML = '';
steps = e.target.value;
})
document.getElementById('rotation-speed').addEventListener('change', (e) => {
document.getElementById('code-to-make').innerHTML = '';
rotationSpeed = e.target.value;
})
document.getElementById('radius').addEventListener('change', (e) => {
document.getElementById('code-to-make').innerHTML = '';
radius = e.target.value;
})
document.getElementById('inner-radius').addEventListener('change', (e) => {
document.getElementById('code-to-make').innerHTML = '';
innerRadius = e.target.value;
})
document.getElementById('line-width').addEventListener('change', (e) => {
document.getElementById('code-to-make').innerHTML = '';
lineWidth = e.target.value;
})
document.getElementById('fill-color').addEventListener('change', (e) => {
document.getElementById('code-to-make').innerHTML = '';
fillColor = e.target.value;
})
document.getElementById('stroke-color').addEventListener('change', (e) => {
document.getElementById('code-to-make').innerHTML = '';
strokeColor = e.target.value;
})
document.getElementById('produce-code').addEventListener('click', () => {
document.getElementById('code-to-make').innerHTML = `
const canvas = document.getElementById('#your-canvas-id#');
<br>
const ctx = canvas.getContext('2d');
<br>
const cX = canvas.width / 2;
<br>
const cY = canvas.height / 2;
<br>
const eachStepRadian = (2 * Math.PI) / ${steps};
<br><br>
ctx.clearRect(0, 0, canvas.width, canvas.height) // clear canvas before drawing new star
<br>
ctx.beginPath();
<br><br>
// batch drawings together for performance sake
<br>
for (let i = 0; i < ${steps + 1}; i += 1) {
<br>
&nbsp&nbsp&nbsp&nbsplet xHalf = ${radius} * (${innerRadius} / 100) * Math.cos((i * eachStepRadian) - eachStepRadian / 2);
<br>
&nbsp&nbsp&nbsp&nbsplet yHalf = ${radius} * (${innerRadius} / 100) * Math.sin((i * eachStepRadian) - eachStepRadian / 2);
<br>
&nbsp&nbsp&nbsp&nbsplet x = ${radius} * Math.cos(i * eachStepRadian);
<br>
&nbsp&nbsp&nbsp&nbsplet y = ${radius} * Math.sin(i * eachStepRadian);
<br><br>
&nbsp&nbsp&nbsp&nbsp// line to half the next step and specified percentage of the radius
<br>
&nbsp&nbsp&nbsp&nbspctx.lineTo(cX + xHalf, cY + yHalf)
<br><br>
&nbsp&nbsp&nbsp&nbsp// line to next stepRadian
<br>
&nbsp&nbsp&nbsp&nbspctx.lineTo(cX + x, cY + y)
<br>
}
<br><br>
ctx.strokeStyle = '${strokeColor}';<br>
ctx.fillStyle = '${fillColor}';<br>
ctx.lineWidth = ${lineWidth};<br>
ctx.stroke();<br>
ctx.fill();<br>
`
})
// start the animation cycle
requestAnimationFrame(rotate)
function rotate() {
rotation += rotationSpeed / 100;
drawStar(radius, steps, rotationSpeed, fillColor, strokeColor);
requestAnimationFrame(rotate);
}
function drawStar() {
// needs to be reset whenever steps change
eachStepRadian = (2 * Math.PI) / steps;
ctx.clearRect(0, 0, canvas.width, canvas.height) // clear canvas before drawing new star
ctx.beginPath();
// batch drawings together for performance sake
for (let i = 0; i < steps + 1; i += 1) {
let xHalf = radius * (innerRadius / 100) * Math.cos(((i * eachStepRadian) - eachStepRadian / 2) + rotation);
let yHalf = radius * (innerRadius / 100) * Math.sin(((i * eachStepRadian) - eachStepRadian / 2) + rotation);
let x = radius * Math.cos((i * eachStepRadian) + rotation);
let y = radius * Math.sin((i * eachStepRadian) + rotation);
// line to half the next step and specified percentage of the radius
ctx.lineTo(cX + xHalf, cY + yHalf)
// line to next stepRadian
ctx.lineTo(cX + x, cY + y)
}
ctx.strokeStyle = strokeColor;
ctx.fillStyle = fillColor;
ctx.lineWidth = lineWidth;
ctx.stroke();
ctx.fill();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id='canvas' width="200" height="200"></canvas>
<div id='inputs-container'>
<div>
<label for='point-count'>Number of Points</label>
<input id='point-count' type='number' min="0" max="40" value=5>
</div>
<div>
<label for='rotation-speed'>Speed of Rotaion</label>
<input id='rotation-speed' type='number' value=0 min="0" max="10">
</div>
<div>
<label for='radius'>Radius</label>
<input id='radius' type='number' value=25 min="0" max="90">
</div>
<div>
<label for='inner-radius'>Inner Radius %</label>
<input id='inner-radius' type='number' value=10 min="0" max="100">
</div>
<div>
<label for='line-width'>Line Width</label>
<input id='line-width' type='number' value=5 min="0" max="15">
</div>
<div>
<label for='fill-color'>Fill Color</label>
<input id='fill-color' type='color' value="#0000ff">
</div>
<div>
<label for='stroke-color'>Stroke Color</label>
<input id='stroke-color' type='color'>
</div>
</div>
<div >
<button id='produce-code'>Produce Code (No Rotation)</button>
<p id='code-to-make'>
</p>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:07:48.573",
"Id": "248139",
"Score": "1",
"Tags": [
"javascript",
"html5",
"canvas"
],
"Title": "Custom canvas star creator. With code to produce drawing"
}
|
248139
|
<p>I use Java8, I have a subclass of Thread called <code>DelayedThread</code> which wraps a <code>Runnable</code> and executes the <code>Runnable</code> after certain amount of time. It has a method called <code>cancelOnlyIfStillSleeping()</code> which interrupts <code>Thread.sleep</code> but I don't want to interrupt it once <code>Runnable</code> has been called because I'm afraid of interrupting <code>Runnable</code> which might react to the interruption in an unexpected way. The code looks like this:</p>
<pre><code>class DelayedThread extends Thread {
private final long delay;
private final Runnable task;
private boolean starting;
private final Object lock = new Object();
DelayedThread(long delay, Runnable task) {
this.delay = delay;
this.task = task;
}
@Override
public void run() {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
synchronized (lock) {
if (isInterrupted()) {
return;
}
starting = true;
}
task.run();
}
/**
* Interrupts this thread only if it's still sleeping. Once it finished sleeping
* the thread won't get interrupted.
*/
void cancelOnlyIfStillSleeping() {
synchronized (lock) {
if (starting) {
return;
}
interrupt();
}
}
}
</code></pre>
<p>Does this code look safe? Isn't there any race condition where my code doesn't work as intended? Or is there any way better to achieve this?</p>
|
[] |
[
{
"body": "<p>I haven't analysed your code in detail, but it looks threadsafe on a quick scan.</p>\n<p>I'd just suggest that you avoid reinventing the wheel. The java.util.Timer class will, I think, fit your use-case and is clearer that you are <strong>cancelling</strong> rather than <strong>interrupting</strong> your scheduled task. I think we can be fairly confident that it has been well-enough designed, implemented and reviewed to be threadsafe ...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T06:46:38.470",
"Id": "248178",
"ParentId": "248141",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "248178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:44:37.923",
"Id": "248141",
"Score": "1",
"Tags": [
"java",
"multithreading"
],
"Title": "Thread which executes code after Thread.sleep() and can be cancelled only if it's sleeping"
}
|
248141
|
<p>Currently, I have a code which downloads a file from FTP to local hard disk. It then uploads a file in chunks to Azure. Finally, it deletes the file from local and ftp. This code is very slow though. Just wanted to know how to improve it.</p>
<pre><code> private async Task UploadToBlobJobAsync(FtpConfiguration ftpConfiguration, BlobStorageConfiguration blobStorageConfiguration, string fileExtension)
{
try
{
ftpConfiguration.FileExtension = fileExtension;
var filesToProcess = FileHelper.GetAllFileNames(ftpConfiguration).ToList();
var batchSize = 4;
List<Task> uploadBlobToStorageTasks = new List<Task>(batchSize);
for (int i = 0; i < filesToProcess.Count(); i += batchSize)
{
// calculated the remaining items to avoid an OutOfRangeException
batchSize = filesToProcess.Count() - i > batchSize ? batchSize : filesToProcess.Count() - i;
for (int j = i; j < i + batchSize; j++)
{
var fileName = filesToProcess[j];
var localFilePath = SaveFileToLocalAndGetLocation(ftpConfiguration, ftpConfiguration.FolderPath, fileName);
// Spin off a background task to process the file we just downloaded
uploadBlobToStorageTasks.Add(Task.Run(() =>
{
// Process the file
UploadFile(ftpConfiguration, blobStorageConfiguration, fileName, localFilePath).ConfigureAwait(false);
}));
}
Task.WaitAll(uploadBlobToStorageTasks.ToArray());
uploadBlobToStorageTasks.Clear();
}
}
catch (Exception ex)
{
}
}
private async Task UploadFile(FtpConfiguration ftpConfiguration, BlobStorageConfiguration blobStorageConfiguration, string fileName, string localFilePath)
{
try
{
await UploadLargeFiles(GetBlobStorageConfiguration(blobStorageConfiguration), fileName, localFilePath).ConfigureAwait(false);
FileHelper.DeleteFile(ftpConfiguration, fileName); // delete file from ftp
}
catch (Exception exception)
{
}
}
private async Task UploadLargeFiles(BlobStorageConfiguration blobStorageConfiguration, string fileName, string localFilePath)
{
try
{
var output = await UploadFileAsBlockBlob(localFilePath, blobStorageConfiguration).ConfigureAwait(false);
// delete the file from local
Logger.LogInformation($"Deleting {fileName} from the local folder. Path is {localFilePath}.");
if (File.Exists(localFilePath))
{
File.Delete(localFilePath);
}
}
catch (Exception ex)
{
}
}
private async Task UploadFileAsBlockBlob(string sourceFilePath, BlobStorageConfiguration blobStorageConfiguration)
{
string fileName = Path.GetFileName(sourceFilePath);
try
{
var storageAccount = CloudStorageAccount.Parse(blobStorageConfiguration.ConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var cloudContainer = blobClient.GetContainerReference(blobStorageConfiguration.Container);
await cloudContainer.CreateIfNotExistsAsync().ConfigureAwait(false);
var directory = cloudContainer.GetDirectoryReference(blobStorageConfiguration.Path);
var blob = directory.GetBlockBlobReference(fileName);
var blocklist = new HashSet<string>();
byte[] bytes = File.ReadAllBytes(sourceFilePath);
const long pageSizeInBytes = 10485760 * 20; // 20mb at a time
long prevLastByte = 0;
long bytesRemain = bytes.Length;
do
{
long bytesToCopy = Math.Min(bytesRemain, pageSizeInBytes);
byte[] bytesToSend = new byte[bytesToCopy];
Array.Copy(bytes, prevLastByte, bytesToSend, 0, bytesToCopy);
prevLastByte += bytesToCopy;
bytesRemain -= bytesToCopy;
// create blockId
string blockId = Guid.NewGuid().ToString();
string base64BlockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(blockId));
await blob.PutBlockAsync(base64BlockId, new MemoryStream(bytesToSend, true), null).ConfigureAwait(false);
blocklist.Add(base64BlockId);
}
while (bytesRemain > 0);
// post blocklist
await blob.PutBlockListAsync(blocklist).ConfigureAwait(false);
}
catch (Exception ex)
{
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:00:43.493",
"Id": "485952",
"Score": "0",
"body": "`const long pageSizeInBytes = 10485760 * 20; // 20mb at a time` That's 200 MB, not 20. Is your calculation wrong or your comment?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T15:46:30.297",
"Id": "485958",
"Score": "1",
"body": "Why do you need to save the file locally first? Can you show the SaveFileToLocalAndGetLocation code? I would assume you would be getting a stream from the FTP and use that stream for the blob stream."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T18:26:08.690",
"Id": "485967",
"Score": "0",
"body": "Actually I tried reading filestream but its quite slow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-25T14:45:54.973",
"Id": "486561",
"Score": "0",
"body": "@Gauravsa Can please elaborate on this statement: `This code is very slow though`? How did you measure it? Which part of it is slow? (download / local file save / upload)? Did you tried with different files and workloads? etc."
}
] |
[
{
"body": "<p>First, don't write to disk anything you don't need to. It's not entirely clear what your goal is here, but I fail to see why you would have such a need in the first place.</p>\n<p>That said, if you take your send function in a vacuum, what it does right now is:</p>\n<ol>\n<li><p>Read your whole (as you say) large file in memory</p>\n</li>\n<li><p>For each chunk, you allocate a whole new array, copy the chunk over, put a <code>MemoryStream</code> on top of it and then send it over.</p>\n</li>\n</ol>\n<p>That is not how streaming is done.</p>\n<p>Instead, you should open a file stream without reading anything, then loop over it for as many chunks as you need and read each chunk individually in one pre-allocated buffer (don't keep allocating new byte arrays), get the base64 representation if you really need it, and send the chunk, then keep looping. Your garbage collector will thank you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T07:31:58.977",
"Id": "486008",
"Score": "0",
"body": "reading 1 gb file in memory is slow. I am trying now to save the file to local disk. I will try ur suggestion and will let u know"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-20T14:27:49.857",
"Id": "486045",
"Score": "0",
"body": "You're doing the same reading, it's just that the generational GC that .Net uses works very poorly (by design) with very large buffers that you recreate over and over. It's the GC specifically you're fighting with the old implementation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T17:25:15.100",
"Id": "248153",
"ParentId": "248142",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-19T13:53:38.873",
"Id": "248142",
"Score": "2",
"Tags": [
"c#",
"multithreading",
"linq",
"azure"
],
"Title": "How do I make multithreading in sending large file from FTP to Azure large files faster"
}
|
248142
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.